<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"
            :cache-key="cacheKeyUrl"
            @columns-change="handleColumnChange"
          >
            <template v-slot:saleCount="{ row }">
              <el-input
                v-model="row.saleCount"
                style="width: 100%"
                placeholder="请输入"
                type="number"
                :min="0"
              ></el-input>
            </template>
            <template v-slot:action="{ row }">
              <el-radio class="radio" v-model="radio" :label="row.id"
                ><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,
    getBatchList,
    getCategoryPackageDisposition
  } from '@/api/wms';
  import ItemSearch from './item-search.vue';
  import { contactQueryByCategoryIdsAPI } from '@/api/saleManage/contact';
  import tabMixins from '@/mixins/tableColumnsMixin';

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

    data() {
      return {
        visible: false,
        currentIndex: null,
        radio: null,
        dictList: {},
        curNodeData: {},
        selection: [],
        treeData: [],
        dimension:'2',
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        treeList: [],
        treeLoading: false,
        cacheKeyUrl: 'eom-sales-selectStockLedgerDialog-202605131603',
        columnsVersion: 1
      };
    },
    watch: {},
    computed: {
      columns() {
        let columnsVersion = this.columnsVersion;
        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,
            selectable: (row) => {
              return row.measureQuantity != 0;
            }

          };
        }

        const tempData = [
          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
          },
          this.dimension=="2"?
          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            showOverflowTooltip: true
          }:{
              width:1
          },
          {
            prop: 'categoryModel',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'colorKey',
            label: '颜色',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'modelKey',
            label: '机型',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'warehouseName',
            label: '仓库',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 90
          },
          {
            prop: 'inventoryCycle',
            label: '存货周期(天)',
            align: 'center',
            width: 150,
            sortable: true,
            showOverflowTooltip: true,
            hide: this.dimension == 1
          },
          {
            prop: 'saleCount',
            slot: 'saleCount',
            label: '订单数量',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 120,
            hide: !this.showSaleCount
          },
          {
            prop: 'measureQuantity',
            label: '库存',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 90
          },
          {
            prop: 'lockQuantity',
            label: '锁库数量',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 90
          },
          {
            prop: 'useQuantity',
            label: '可用数量',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 90,
            formatter: (row) => {
              // 使用toFixed处理浮点数精度问题，保留4位小数
              const measureQuantity = parseFloat(row.measureQuantity) || 0;
              const lockQuantity = parseFloat(row.lockQuantity) || 0;
              const available = measureQuantity - lockQuantity;
              // 使用toFixed避免精度丢失，然后去除末尾多余的0
              return available.toFixed(4).replace(/\.?0+$/, '');
            }
          },
          {
            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
          }
        ];
        return tempData.filter((item) => !item.hide);
      }
    },
    methods: {
      getDictV(code, val) {
        if (!this.dictList[code]) return '';
        return this.dictList[code].find((item) => item.value == val)?.label;
      },
      open(item, currentIndex) {
        console.log(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 }) {
        this.dimension = where.dimension||'2';
        let api = where.dimension == '1' ? getOutindetailtwoList : getBatchList;
        return api({
          ...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;
            }
          });
        }
        let idList = list.map((item) => item.categoryId);

        // 获取包装规格
        let packingSpecification = await getCategoryPackageDisposition({
          categoryIds: idList
        });

        list.forEach((item, index) => {
          item.productName = item.categoryName;
          item.productCode = item.categoryCode;
          item.productCategoryName = '';
          item.productBrand = item.brandNum;
          item.provenance = item.provenance || [];
          if(this.showSaleCount){
            item.saleCount = item.saleCount;
          }
          item['packageDispositionList'] = packingSpecification
            .filter(
              (ite) => item.categoryId == ite.categoryId && ite.conversionUnit
            )
            .sort((a, b) => a.sort - b.sort);
          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>
