<template>
  <div>
    <!-- 选择物资编号 -->
    <Modal v-model="isShowWuzi" :z-index="10000" width="70" title="库存选择"
     @on-visible-change="visibleChange"
     :loading="showLoading">
      <div class="searchCompanys">
        <el-cascader v-model="wuzifenlei" ref="cascaders" clearable popper-class="select_popper"
                  style="margin-right: 10px;flex-basis: 60%;" :options="fenleiList" :props="{label:'name',value:'id'}"
                  @change="(e)=>{changeFenlei(e)}" />
        <el-input
          v-model="wuzibianmakeyword"
          style="margin-right:10px"
          clearable
          type="text"
          placeholder="请输入种类编码查找库存"
          @keyup.enter.native="getWuzi"
        />
        <el-input
          v-model="wuzimingchengkeyword"
          style="margin-right:10px"
          clearable
          type="text"
          placeholder="请输入物资名称查找"
          @keyup.enter.native="getWuzi"
        />

        <el-button type="primary" @click="getWuzi">查询</el-button>
      </div>

      <Table
        ref="currentRowTable"
        :loading="loadingtable"
        highlight-row
        :columns="wuziColumns"
        :data="wzList"
        @on-current-change="wuziSelect"
      />
      <Page
        :current="wuziPageIndex"
        :total="wuziTotal"
        simple
        style="padding-top: 14px;display: flex;justify-content: center;"
        @on-change="wuziPageChange"
      />

      <div slot="footer" align="right">
        <Button class="btn" size="default" type="default" @click="mingxiCancel">取消</Button>
        <Button class="btn" size="default" type="primary" @click="mingxiConfirm">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
// import {
//   index,
// } from "@/api/system/baseForm.js"
import {
  index
} from '@/api/inventory.js'
  import {
    index as getFenleilist
  } from '@/api/fenlei.js'
export default {
  data() {
    return {
      // 物资
      showLoading: false,
      loadingtable:false,
      isShowWuzi: false,
      wuziPageIndex: 1,
      wuzibianmakeyword: '',
      wuzimingchengkeyword: '',
      wuzifenlei:'',
      fenleiList:[],
      wuziTotal: 0,
      wzList: [],
      selectItem: {},
      wuziColumns: [{
        width: 60,
        _isChecked: false,
        key: 'isSelect',
        resizable: true,
        render: (h, params) => {
          return h('div', [
            h('Radio', {
              props: {
                value: params.row.isSelect
              },
              on: {
                'on-change': (e) => {
                  this.wzList.forEach((items) => {
                    this.$set(items, 'isSelect', false)
                  })
                  this.wzList[params.index].isSelect = e
                }
              }
            })
          ])
        }
      }, {
        title: '物资名称',
        key: 'zichanmingcheng'
      }, {
        title: '所属种类',
        key: 'fenlei_detail.value',
        render: (h, params) => {
          return h('div', [
            h('strong', params.row.wuzibianma_material_infos_wuzibianma_relation
            ? (params.row.wuzibianma_material_infos_wuzibianma_relation.fenlei_detail?
            params.row.wuzibianma_material_infos_wuzibianma_relation.fenlei_detail.name:'') : '')
          ])
        }
      }, {
        title: '种类编码',
        key: 'wuzibianma'
      }, {
        title: '在库数量',
        key: 'zaikushuliang'
      }, {
        title: '入库批次',
        key: 'rukupici'
      }, {
        title: '物资类型',
        key: 'wuzileixing'
      }, {
        title: '物资型号',
        key: 'guigexinghao'
      }, {
        title: '物资规格',
        key: 'wuziguige'
      }, {
        title: '单位',
        key: 'jiliangdanwei'
      }]
    }
  },
  watch: {
    isShowWuzi(newVal) {
      if (newVal) {
        this.getFenlei()
        this.getWuzi()
      }else{
        this.wzList = []
        this.loadingtable = false
        this.wuziPageIndex = 1
      }
    }
  },
  methods: {
    async getFenlei() {
      const res = await getFenleilist({
        tree: 1
      })
      this.fenleiList = this.removeEmptyChildren(res)
    },
    changeFenlei(e, row) {
      console.log('e', e)
      if (e) {
        this.wuzifenlei = e[e.length - 1]
      } else {
        this.wuzifenlei = ''
      }
    },
    // 移除children=[]
    removeEmptyChildren(node) {
      if (Array.isArray(node)) {
        return node.map(child => {
          if (child.children) {
            // 递归处理子节点
            child.children = this.removeEmptyChildren(child.children);
            // 若处理后 children 为空，删除该属性
            if (child.children.length === 0) {
              delete child.children;
            }
          }
          return child;
        });
      }
      return [];
    },
    async getWuzi() {
      this.showLoading = true
      this.loadingtable = true
      const res = await index({
        page_size: 40,
        page: this.wuziPageIndex,
        sort_type: 'DESC',
        sort_name: 'wuzibianma',
        fenlei:this.wuzifenlei,
        // table_name: 'inventorys',
        filter: [{
          'key': 'zichanmingcheng',
          'op': 'like',
          'value': this.wuzimingchengkeyword
        }, {
          'key': 'wuzibianma',
          'op': 'like',
          'value': this.wuzibianmakeyword
        }]
      })

      console.log("res.list.data",res.list.data)
      let arr = this.processInventoryData(res.list.data)
      for (var m of arr) {
        m.isSelect = false
      }
      this.wzList = arr
      console.log("this.wzList",this.wzList)
      this.wuziTotal = res.list.total
      this.showLoading = false
      this.loadingtable = false
      console.log('res', this.wzList)
    },
    wuziSelect(e) {
      console.log(e)
      this.wzList.forEach((items) => {
        this.$set(items, 'isSelect', false)
        if (items.id == e.id) {
          this.$set(items, 'isSelect', true)
        }
      })
      this.selectItem = e
    },
    wuziPageChange(e) {
      console.log('e', e)
      this.wuziPageIndex = e
      this.selectItem = {}
      this.getWuzi()
    },
    visibleChange(e){
      console.log("e",e)
      this.selectItem = {}
      this.wuziPageIndex = 1
      // this.isShowWuzi = false
    },
    mingxiConfirm() {
      if (Object.keys(this.selectItem).length === 0) {
        // this.isShowWuzi = false
        this.$message({
          type: 'warning',
          message: '请选择物资'
        })
        return
      }
      this.$emit('refresh', this.selectItem)
      this.isShowWuzi = false
    },
    mingxiCancel() {
      this.selectItem = {}
      this.wuziPageIndex = 1
      this.isShowWuzi = false
    },
    // 合并 一物一码 物资编码相同，批次相同的数据
    processInventoryData(data) {
      // 筛选出wuzileixing = 一物一码的记录 且 没有等待出库的
      const matchedData = data
        .filter(item => item.wuzileixing === '一物一码' && parseFloat(item.zaikushuliang) !== 0 && parseFloat(item.wait_num) === 0 ); // 新增zaikushuliang !== 0条件

      // 保存不匹配的记录（直接返回）
      const unmatchedData = data
        .filter(item => item.wuzileixing !== '一物一码' || (parseFloat(item.zaikushuliang)-parseFloat(item.wait_num) === 0))
        .filter(item => (parseFloat(item.zaikushuliang)-parseFloat(item.wait_num)) !== 0) // 剔除zaikushuliang=0的记录
      console.log("unmatchedData",unmatchedData)
      unmatchedData.map(item=>{
        item.zaikushuliang = parseFloat(item.zaikushuliang)-parseFloat(item.wait_num)
      })
      // 使用Map来存储合并后的结果
      const mergedMap = new Map();

      // 遍历筛选后的数据进行合并
      matchedData.forEach(item => {
        // 使用wuzibianma和rukupici的组合作为唯一键
        const key = `${item.wuzibianma}_${item.rukupici}`;

        // 如果Map中不存在该组合键，创建新的合并项
        if (!mergedMap.has(key)) {
          // 提取需要保留的字段
          const mergedItem = {
            id:key,
            zichanmingcheng: item.zichanmingcheng,
            wuzibianma: item.wuzibianma,
            rukupici: item.rukupici,
            zaikushuliang: parseFloat(item.zaikushuliang) - parseFloat(item.wait_num) || 0, // 初始化为当前记录的在库数量
            wuzileixing: item.wuzileixing,
            guigexinghao: item.guigexinghao,
            wuziguige: item.wuziguige,
            jiliangdanwei: item.jiliangdanwei,
            shengchanriqi:item.shengchanriqi,
            wuzibianma_material_infos_wuzibianma_relation: item.wuzibianma_material_infos_wuzibianma_relation,
            // 初始化其他元数据数组
            otherMetadata: []
          };

          // 提取其他字段作为元数据
          // const metadata = {};
          // for (const [k, v] of Object.entries(item)) {
          //   if (![
          //     'zichanmingcheng', 'wuzibianma', 'rukupici', 'zaikushuliang',
          //     'wuzileixing', 'guigexinghao', 'wuziguige', 'jiliangdanwei',
          //     'wuzibianma_material_infos_wuzibianma_relation'
          //   ].includes(k)) {
          //     metadata[k] = v;
          //   }
          // }

          mergedItem.otherMetadata.push(item);
          mergedMap.set(key, mergedItem);
        } else {
          // 如果Map中已存在该组合键，更新在库数量并添加到其他元数据数组
          const mergedItem = mergedMap.get(key);

          // 累加在库数量
          if (item.zaikushuliang !== undefined) {
            mergedItem.zaikushuliang += parseFloat(item.zaikushuliang);
          }

          // 提取其他字段作为元数据
          // const metadata = {};
          // for (const [k, v] of Object.entries(item)) {
          //   if (![
          //     'zichanmingcheng', 'wuzibianma', 'rukupici', 'zaikushuliang',
          //     'wuzileixing', 'guigexinghao', 'wuziguige', 'jiliangdanwei',
          //     'wuzibianma_material_infos_wuzibianma_relation'
          //   ].includes(k)) {
          //     metadata[k] = v;
          //   }
          // }

          mergedItem.otherMetadata.push(item);
        }
      });

      // 将合并后的结果转换为数组
      const mergedArray = Array.from(mergedMap.values())
        .filter(item => parseFloat(item.zaikushuliang) !== 0); // 再次过滤合并后zaikushuliang=0的情况

      // 返回合并后的记录和未匹配的记录（均不包含zaikushuliang=0）
      return [...mergedArray, ...unmatchedData]
        .filter(item => parseFloat(item.zaikushuliang) !== 0); // 最终结果过滤
    }
  }
}
</script>

<style scoped>
    .searchCompanys {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
    }
</style>
