<template>
  <el-dialog
    title="库存台账"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    top="5vh"
    :close-on-press-escape="false"
    append-to-body
    width="70%"
    :maxable="true"
    :resizable="true"
  >
    <el-card shadow="never">
      <item-search @search="reload" ref="refSeavch"></item-search>
      <ele-split-layout
        width="244px"
        allow-collapse
        :right-style="{ overflow: 'hidden' }"
      >
        <div class="ele-border-lighter split-layout-right-content">
          <el-tree
            :data="treeList"
            :props="defaultProps"
            ref="treeRef"
            :default-expanded-keys="
              curNodeData && curNodeData.id ? [curNodeData.id] : []
            "
            :highlight-current="true"
            node-key="id"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            ><span class="custom-tree-node" slot-scope="{ node, data }">
              <span
                >{{ data.factoryName ? data.factoryName + '-' : ''
                }}{{ data.name }}</span
              >
            </span></el-tree
          >
        </div>
        <!-- 表格 -->
        <template v-slot:content>
          <ele-pro-table
            ref="table"
            :columns="columns"
            :datasource="datasource"
            row-key="id"
            height="calc(100vh - 480px)"
            class="dict-table"
            @cell-click="cellClick"
            :selection.sync="selection"
          >
            <template v-slot:action="{ row }">
              <el-radio class="radio" v-model="radio" :label="row.categoryCode"
                ><i></i
              ></el-radio>
            </template>
          </ele-pro-table>
        </template>
      </ele-split-layout>
    </el-card>

    <div slot="footer">
      <el-button type="primary" size="small" @click="selected">选择</el-button>
      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getOutindetailtwoList, getTreeByGroup } from '@/api/wms';
  import ItemSearch from './item-search.vue';
  import { contactQueryByCategoryIdsAPI } from '@/api/saleManage/contact';

  export default {
    components: { ItemSearch },
    props: {
      /*已选择的产品*/
      data: {
        type: Array,
        default: () => []
      },
      /*是否需要供应商*/
      isSupplier: {
        type: Boolean,
        default: false
      }
    },

    data() {
      return {
        visible: false,
        currentIndex: null,
        radio: null,
        dictList: {},
        curNodeData: {},
        selection: [],
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        treeList: [],
        treeLoading: false
      };
    },
    watch: {},
    computed: {
      columns() {
        let data = null;
        if (this.currentIndex != -1) {
          data = {
            action: 'action',
            slot: 'action',
            align: 'center',
            label: '选择',
            reserveSelection: true
          };
        }
        if (this.currentIndex == -1) {
          data = {
            label: '选择',
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            reserveSelection: true
          };
        }
        return [
          data,

          {
            columnKey: 'index',
            type: 'index',
            width: 50,
            align: 'center',
            showOverflowTooltip: true,
            label: '序号'
          },
          {
            prop: 'categoryCode',
            label: '编码',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'categoryName',
            label: '名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'brandNum',
            align: 'center',
            label: '牌号',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryModel',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'measureQuantity',
            label: '库存',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 90
          },
          {
            prop: 'measureUnit',
            label: '单位',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 90
          },
          {
            prop: 'weight',
            label: '重量',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 90
          },
          {
            prop: 'weightUnit',
            label: '重量单位',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 90
          },
          {
            prop: 'packingUnit',
            align: 'center',
            label: '包装单位',
            showOverflowTooltip: true
          }
        ];
      }
    },
    methods: {
      getDictV(code, val) {
        if (!this.dictList[code]) return '';
        return this.dictList[code].find((item) => item.value == val)?.label;
      },
      open(item, currentIndex) {
        this.currentIndex = currentIndex;
        this.visible = true;
        this.getTreeData();
      },
      async getTreeData() {
        try {
          this.treeLoading = true;
          let res = null;
          res = await getTreeByGroup({ type: 2 });
          this.treeLoading = false;
          if (res?.code === '0') {
            this.treeList = res.data;
            return this.treeList;
          }
        } catch (error) {
          console.log(error);
        }
        this.treeLoading = false;
      },
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        return getOutindetailtwoList({
          ...where,
          ...order,
          pageNum: page,
          size: limit
        });
      },

      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ pageNum: 1, where: where });
      },

      handleNodeClick(data, node) {
        this.curNodeData = data;
        if (data.id == this.currentId) {
          this.$refs.treeRef.setCurrentKey(null);
          this.reload();
        } else {
          this.reload({ categoryLevelId: data.id });
        }
      },
      async getSupplierObj(productList, queryName) {
      try {
        let categoryIds = productList
          .filter((item) => item.id)
          .map((item) => item.id);
        if (categoryIds.length > 0) {
          return await contactQueryByCategoryIdsAPI({
            categoryIds,
            isQueryEE: 1
          });
        } else {
          return Promise.resolve({});
        }
      } catch (e) {
        return Promise.resolve({});
      }
    },
      // 单击获取id
      cellClick(row) {
        if (this.currentIndex == -1) return;
        this.current = row;
        this.radio = row.id;
      },
      handleClose() {
        this.visible = false;
        this.current = null;
        this.selection = [];
        this.$refs.table.clearSelection();
        this.radio = '';
      },

      async selected() {
        if (!this.current && !this.selection.length) {
          return this.$message.warning('请至少选择一条数据');
        }
        if (this.currentIndex != -1) {
          if (
            this.data
              .map((item) => item.productCode)
              .includes(this.current.code)
          ) {
            return this.$message.error('选择的物品已经存在列表了');
          }
        } else {
          if (
            this.selection.some((item) =>
              this.data.some((i) => i.productCode == item.code)
            )
          ) {
            return this.$message.error('选择的物品已经存在列表了');
          }
        }
        let list = this.currentIndex == -1 ? this.selection : [this.current];
        //获取供应商
        if (this.isSupplier) {
          let supplierList = await this.getSupplierObj(list);
          list.forEach((item) => {
            item['entrustedEnterpriseIdList'] = supplierList[item.id];
            if (supplierList[item.id]?.length === 1) {
              item['entrustedEnterpriseId'] = supplierList[item.id][0].id;
            }
          });
        }
        list.forEach((item, index) => {
          item.productName = item.categoryName;
          item.productCode = item.categoryCode;
          item.productCategoryName = '';
          item.productBrand = item.brandNum;
          item.provenance = item.provenance||[];
          // item.warehouseName = item.warehouseList[0].warehouse_name;
          // item.warehouseId = item.warehouseList[0].warehouse_id;
          this.$set(list[index], 'totalCount', 1);
          // item.totalCount = 1;
          item.measuringUnit = item.measureUnit;
          //item.weightUnit = item.weightUnit;
          // item.warehouseNum = item.measureQuantity;
          item.productId = item.categoryId;
          item.id = '';

          // item.specification = item.specification;
        });
        this.$emit('changeParent',list, this.currentIndex);
        this.handleClose();
      }
    }
  };
</script>

<style lang="scss" scoped>
  .tree_col {
    border: 1px solid #eee;
    padding: 10px 0;
    box-sizing: border-box;
    height: 500px;
    overflow: auto;
  }

  .table_col {
    padding-left: 10px;

    ::v-deep .el-table th.el-table__cell {
      background: #f2f2f2;
    }
  }

  .pagination {
    text-align: right;
    padding: 10px 0;
  }

  .btns {
    text-align: center;
    padding: 10px 0;
  }

  .topsearch {
    margin-bottom: 15px;
  }
</style>
