<template>
  <el-dialog
    :visible="visibleDialog"
    :before-close="cancel"
    width="80vw"
    title="选择"
  >
    <el-table
      :data="tableData"
      ref="multipleTable"
      border
      height="60vh"
      style="width: 100%"
      :header-cell-style="{ background: '#EEEEEE', border: 'none' }"
    >
      <el-table-column label="仓库" prop="warehouseName"> </el-table-column>
      <el-table-column label="库区" prop="areaName"> </el-table-column>
      <el-table-column label="货架" prop="shelfCode"> </el-table-column>
      <el-table-column label="货位" prop="cargoSpaceCode"> </el-table-column>
      <el-table-column label="批次号" prop="batchNum"> </el-table-column>
      <el-table-column label="生产日期" prop="manufactureTime">
      </el-table-column>
      <template v-if="isMaterial">
        <el-table-column label="计量单位" prop="measurementUnit">
        </el-table-column>
        <el-table-column label="最小单元" prop="minPackUnit">
          <template slot-scope="{ row }">
            {{ row.unit }}/{{ row.minPackUnit }}
          </template>
        </el-table-column>
      </template>
      <template v-else>
        <el-table-column label="单位" prop="unit"> </el-table-column>
      </template>
      <el-table-column label="库存量" prop="realInventoryNum">
      </el-table-column>
      <el-table-column label="需要出库数" prop="minimumUnit">
        <template slot-scope="{ row, $index }">
          <span style="width: 20px; display: inline-block">{{
            selectList[row.curId] ||
            +((confirmMap[row.curId] && confirmMap[row.curId].length) || 0)
          }}</span>
          <el-popover
            placement="bottom"
            width="470"
            :key="row.cargoSpaceId"
            trigger="manual"
            v-model="row.visible"
          >
            <div class="popover-content">
              <div class="title">
                已选{{ isMaterial || !row.unit ? '桶数' : `${row.unit}数` }}（{{
                  selectNum
                }}）
              </div>
              <div
                class="popover-row"
                v-for="(item, index) in curBuketList"
                :key="index"
              >
                <el-checkbox
                  :value="item.checked"
                  @click.native.prevent="handleLineSelected(item, index)"
                ></el-checkbox>
                <div
                  class="items"
                  :class="{ itemActive: itm.isSelected }"
                  v-for="(itm, idx) in item.children"
                  :key="idx"
                  @click="selectBucket(itm, index)"
                >
                  {{ itm.num }}
                </div>
              </div>
            </div>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="bucketCancel(row)"
                >取消</el-button
              >
              <el-button
                type="primary"
                size="mini"
                @click="bucketConfirm(row, $index)"
                >确定</el-button
              >
            </div>
            <el-button
              type="primary"
              size="small"
              slot="reference"
              @click="openBucket(row, $index)"
              >选择{{ isMaterial ? '桶号' : '编码' }}</el-button
            >
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <div class="sum-box">
      <span class="fw">累计出库量</span>
      <span>{{ selectOpt.sumWeight }}</span>
      <span v-if="isMaterial">{{ selectOpt.sumNum }}</span>
    </div>
    <template slot="footer">
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="cancel">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
  // import {
  //   getWarehouseActualDetail,
  //   getWarehouseActualSingle
  // } from '@/api/stockManagement/stockLedger.js'
  import { deepClone } from '@/utils';
  export default {
    props: {
      title: {
        type: String,
        default: '物料'
      },
      warehousingType: {
        type: [Number, String]
      },
      selectedList: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        tableData: [],
        visibleDialog: false,
        buketMap: {}, //桶数据
        curBuketList: [], //当前展示桶数据
        curIndex: '', //当前选中库位
        confirmResolve: null,
        assetCode: '',
        assetType: '',
        confirmMap: {}
      };
    },
    computed: {
      isMaterial() {
        return this.title == '物料';
      },
      selectList() {
        let obj = {};
        for (const key in this.buketMap) {
          obj[key] = this.buketMap[key].reduce((cur, item) => {
            return cur + item.children.filter((i) => i.isSelected).length;
          }, 0);
        }

        return obj;
      },
      // 当前选中
      selectNum() {
        return this.curBuketList
          .map((item) => item.children.filter((i) => i.isSelected))
          .flat().length;
      },
      // 累计选中
      selectOpt() {
        let sum = 0;

        const list = [
          ...Object.values(this.buketMap)
            .map((item) => {
              return item
                .map((i) =>
                  i.children
                    .filter((i) => i.isSelected)
                    .map((i) => {
                      delete i.createTime;

                      sum += i.measurementUnit || 1;
                      return i;
                    })
                )
                .flat();
            })
            .flat(),
          ...Object.values(this.confirmMap)
            .flat()
            .map((item) => {
              delete item.createTime;

              sum += item.measurementUnit || 1;
              return item;
            })
        ];

        const {
          unit = '',
          minPackUnit = '',
          measurementUnit = 1
        } = list[0] || {};
        const outInNum = list.length;
        return {
          sumWeight: sum + unit,
          outInNum,
          sumNum: outInNum + minPackUnit,
          list,
          minPackUnit
        };
      }
    },
    methods: {
      open({ assetCode, assetType }, memo = []) {
        this.visibleDialog = true;
        this.assetType = assetType;
        this.assetCode = assetCode;
        this.confirmMap = {};
        memo.map((item) => {
          if (this.confirmMap[item.pId]) {
            this.confirmMap[item.pId].push(item);
          } else {
            this.$set(this.confirmMap, item.pId, [item]);
          }
        });
        this.handleList(assetCode, assetType);

        return new Promise((res) => (this.confirmResolve = res));
      },
      handleSelectionChange(row, val) {
        this.$set(this.selectOpt, row.id, val);
      },
      // 桶号数据
      async openBucket(row, index) {
        this.tableData.forEach((item) => {
          this.$set(item, 'visible', false);
        });
        this.$set(row, 'visible', true);
        this.curIndex = row.curId;

        if (this.buketMap[row.curId]) {
          this.curBuketList = deepClone(this.buketMap[row.curId]);
          return;
        }

        const res = await getWarehouseActualSingle({
          areaId: row.areaId,
          cargoSpaceId: row.cargoSpaceId,
          shelfId: row.shelfId,
          warehouseId: row.warehouseId,
          batchNum: row.batchNum,
          manufactureTime: row.manufactureTime,
          warehousingType: this.assetType,
          warehousingCode: this.assetCode
        });
        if (res?.success) {
          let len = Math.ceil(res.data.length / 6);

          // res.data.forEach(item => {
          //   const same = this.selectedList.filter(i => i.assetCode === item.assetCode)

          //   item.isSelected = same.length && same
          // })
          // if ((this.buketMap, index))
          const confirmList = this.confirmMap[row.curId] || [];
          this.curBuketList = Array.from(new Array(len), (itm, idx) => {
            const item = {
              id: idx,
              checked: false,
              children: res.data.slice(idx * 6, (idx + 1) * 6).map((i) => {
                if (confirmList.some((itm) => i.num === itm.num)) {
                  i.isSelected = true;
                }
                i.pId = row.curId;
                return i;
              })
            };
            return item;
          });
          this.$set(this.buketMap, row.curId, deepClone(this.curBuketList));
          this.confirmMap[row.curId] = [];
        }
      },
      // 桶 取消
      bucketCancel(row) {
        row.visible = false;
      },
      // 桶 确认
      bucketConfirm(row, index) {
        this.buketMap[row.curId] = deepClone(this.curBuketList);

        this.bucketCancel(row);
      },
      // 桶选中
      selectBucket(itm, parentIndex) {
        this.$set(itm, 'isSelected', !itm.isSelected);

        if (!itm.isSelected) {
          this.curBuketList[parentIndex].checked = false;
        }
      },
      // 桶全选
      handleLineSelected(item, index) {
        item.checked = !item.checked;

        this.curBuketList[index].children.map((itm) => {
          this.$set(itm, 'isSelected', item.checked);
        });
      },
      // 表格数据
      async handleList(assetCode, assetType) {
        const params = {
          assetCode,
          assetType
        };
        const res = await getWarehouseActualDetail(params);
        if (res?.success) {
          this.tableData = res.data.map((item) => {
            item.curId =
              item.areaId +
              item.measurementUnit +
              item.minPackUnit +
              item.unit +
              item.warehouseName +
              item.warehouseId +
              item.shelfId +
              item.cargoSpaceId +
              item.manufactureTime +
              item.batchNum;

            return item;
          });
        }
      },
      confirm() {
        const { list } = this.selectOpt;
        if (!list?.length) return this.$message.error('请选择一条数据！');
        this.confirmResolve && this.confirmResolve(this.selectOpt);
        this.cancel();
      },
      cancel() {
        this.tableData = [];
        this.curBuketList = [];
        this.buketMap = {};
        this.visibleDialog = false;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .pagination {
    display: flex;
    justify-content: flex-end;
    padding: 10px;
  }

  .sum-box {
    width: 288px;
    height: 25px;
    line-height: 25px;
    text-align: center;
    margin: 20px 0 0 auto;
    background-color: rgba(242, 242, 242, 1);

    .fw {
      font-weight: bold;
    }
    span + span {
      margin-left: 20px;
    }
  }

  .popover-content {
    .popover-row {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      .items {
        cursor: pointer;
        width: 63px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        background-color: rgba(242, 242, 242, 1);
        color: #333;
        margin-left: 8px;

        &.itemActive {
          background-color: rgba(112, 182, 3, 1);
          color: #fff;
        }
      }
    }

    .title {
      text-align: right;
      border-bottom: 1px solid #333;
      margin-bottom: 12px;
      font-size: 20px;
    }
  }
</style>
