<template>
  <div>
    <el-dialog
      :title="typeName"
      :visible.sync="dialogVisible"
      width="90%"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="productBox">
        <div class="productsList">
          <header-title title="库存台账"></header-title>
          <div class="control_btn">
            <div
              ><span>包装规格：</span>
              <template v-for="item in packingSpecificationOption">
                <el-tag v-if="item.sort > 0"
                  >{{ item.packageCell }}{{ item.packageUnit }}/{{
                    item.conversionUnit
                  }}</el-tag
                >
              </template>
            </div>
            <div>
              <el-select
                v-if="typeName == '拆包'"
                style="margin-right: 10px"
                v-model="selectValue"
                :placeholder="`请选择${typeName}维度`"
              >
                <template v-for="item in selectList">
                  <el-option
                    :label="item.packageUnit"
                    :value="item.packageUnit"
                    :key="item.packageUnit"
                  >
                  </el-option>
                </template>
              </el-select>
              <el-select
                v-else
                style="margin-right: 10px"
                v-model="selectValue"
                :placeholder="`请选择${typeName}维度`"
              >
                <template v-for="item in selectList">
                  <el-option
                    :label="item.conversionUnit"
                    :value="item.conversionUnit"
                    :key="item.conversionUnit"
                  >
                  </el-option>
                </template>
              </el-select>
              <el-button type="primary" @click="merge">{{
                typeName
              }}</el-button>
            </div>
          </div>
          <el-table
            ref="table"
            :height="600"
            :data="productList"
            row-key="id"
            @selection-change="selecctedRow"
            tooltip-effect="dark"
            border
          >
            <el-table-column
              fixed="left"
              align="center"
              width="50"
              :reserve-selection="true"
              :selectable="checkSelectable"
              type="selection"
            ></el-table-column>
            <el-table-column label="序号" type="index" width="50">
            </el-table-column>
            <el-table-column
              label="物品编码"
              prop="categoryCode"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="物品名称"
              prop="categoryName"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="批次号"
              prop="batchNo"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="牌号"
              prop="brandNum"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="型号"
              prop="categoryModel"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="规格"
              prop="specification"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="包装编码"
              prop="packageNo"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="包装数量"
              prop="packingQuantity"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="包装单位"
              prop="packingUnit"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="计量数量"
              prop="measureQuantity"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="计量单位"
              prop="measureUnit"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="重量"
              prop="weight"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="重量单位"
              prop="weightUnit"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="仓库"
              prop="warehouseName"
              :show-overflow-tooltip="true"
            ></el-table-column>
          </el-table>
        </div>
        <div class="allocateDetails">
          <header-title :title="`${typeName}明细`"></header-title>
          <div class="control_btn">
            <div></div>
            <div>
              <el-button type="primary" @click="clearTable">清空</el-button>
            </div>
          </div>
          <el-table
            :height="600"
            ref="detailTable"
            :data="tableData"
            tooltip-effect="dark"
            border
          >
            <el-table-column label="序号" type="index" width="50">
            </el-table-column>
            <el-table-column
              label="物品编码"
              prop="categoryCode"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="物品名称"
              prop="categoryName"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="批次号"
              prop="batchNo"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="牌号"
              prop="brandNum"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="型号"
              prop="categoryModel"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="规格"
              prop="specification"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="包装编码"
              prop="packageNo"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="包装数量"
              prop="packingQuantity"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="包装单位"
              prop="packingUnit"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="计量数量"
              prop="measureQuantity"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="计量单位"
              prop="measureUnit"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="重量"
              prop="weight"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="重量单位"
              prop="weightUnit"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="仓库"
              prop="warehouseName"
              :show-overflow-tooltip="true"
            ></el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleMine">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { mapActions, mapGetters } from 'vuex';
  import storageApi from '@/api/warehouseManagement';
  import { getCode } from '@/api/codeManagement/index.js';
  export default {
    data() {
      return {
        typeName: '',
        productList: [],
        tableData: [],
        dialogVisible: false,
        selectionIds: [],
        selection: [],
        isSplit: false,
        selectValue: '',
        packingSpecificationOption: []
      };
    },
    computed: {
      ...mapGetters(['dict', 'getDict']),
      selectList() {
        if (this.isSplit) {
          // 计量单位为KG类的情况
          return this.packingSpecificationOption.filter(
            (item) => item.sort > 1
          );
        } else {
          return this.packingSpecificationOption.filter(
            (item) => item.sort > 0
          );
        }
      }
    },
    methods: {
      ...mapActions('dict', ['requestDict']),
      clearTable() {
        this.tableData = [];
        this.selection = [];
        this.selectionIds = [];
        this.$refs.table.clearSelection();
      },
      async merge() {
        if (!this.selectValue) {
          return this.$message.error(`请选择${this.typeName}维度`);
        }
        if (this.selection.length > 0) {
          console.log(this.selection);
          console.log(this.selectionIds);
          let boolen = this.selection.every((item) =>
            this.selectionIds.includes(item.id)
          );
          if (this.selection.length > 0 && !boolen) {
            this.selection = this.selection.filter(
              (item) => !this.selectionIds.includes(item.id)
            );

            console.log('this.selection---------', this.selection);
            console.log('this.selectionIds---', this.selectionIds);
            if (this.typeName == '拆包') {
              // 拆包
              let packageUnitList = this.selection.map(
                (item) => item.packingUnit
              );
              let currentIndex = this.selectList.findIndex(
                (item) => item.packageUnit == this.selectValue
              );
              let split = packageUnitList.every((item) => {
                return (
                  this.selectList.findIndex((ite) => ite.packageUnit == item) >
                    currentIndex ||
                  this.selectList.findIndex(
                    (ite) => ite.conversionUnit == item
                  ) ==
                    this.selectList.length - 1
                );
              });
              if (split) {
                console.log('允许拆分');
                this.selection.map(async (item, index) => {
                  console.log('item---', item);
                  console.log('this.selectList--', this.selectList);
                  let targetIndex = this.selectList.findIndex(
                    (ite) => ite.conversionUnit == item.packingUnit
                  );
                  console.log('targetIndex--', targetIndex);
                  console.log('currentIndex--', currentIndex);
                  let num = item.packingQuantity;
                  for (let i = targetIndex; i >= currentIndex; i--) {
                    num = num * this.selectList[i].packageCell;
                  }
                  console.log(num);
                  let { data } = await storageApi.getAssetNum([
                    {
                      assetCode: item.categoryCode + index,
                      batchNum: item.batchNo,
                      num: num
                    }
                  ]);
                  console.log('data----------', data);
                  for (let i = 0; i < num; i++) {
                    this.tableData.push({
                      ...item,
                      packingQuantity: 1,
                      packageNo: data[i].onlyCode,
                      packingUnit: this.selectValue,
                      measureQuantity: this.$math.format(
                        item.measureQuantity / num,
                        14
                      ),
                      weight: this.$math.format(item.weight / num, 14)
                    });
                  }
                });
              } else {
                return this.$message.error('请检查所选的包装单位是否正确');
              }
              // // 获取包装维度
              // let packingSpecification =
              //   await storageApi.getCategoryPackageDisposition({
              //     categoryIds: this.selection.map((item) => item.categoryId)
              //   });
              // let packingSpecificationOption = this.selection.map((item) => {
              //   return packingSpecification
              //     .filter((ite) => item.categoryId == ite.categoryId)
              //     .sort((a, b) => a.sort - b.sort);
              // });
              // let isBoolen = this.selection.every(
              //   (item, index) =>
              //     item.packingUnit !==
              //     packingSpecificationOption[index][0].packageUnit
              // );
              // if (isBoolen) {
              //   let list = this.selection.map((item, index) => {
              //     let splitIndex = packingSpecificationOption[index].findIndex(
              //       (ite) =>
              //         ite.conversionUnit != ite.packageUnit &&
              //         item.packingUnit == ite.conversionUnit
              //     );
              //     // 计算最小计量数量和数量
              //     let measureQuantity = 1;
              //     let reduceIndex = splitIndex;
              //     for (; reduceIndex > 0; reduceIndex--) {
              //       measureQuantity = this.$math.format(
              //         measureQuantity *
              //           packingSpecificationOption[index][reduceIndex - 1]
              //             .packageCell,
              //         14
              //       );
              //     }
              //     return {
              //       ...item,
              //       packingQuantity: 1,
              //       packingUnit:
              //         packingSpecificationOption[index][splitIndex].packageUnit,
              //       num: packingSpecificationOption[index][splitIndex]
              //         .packageCell,
              //       measureUnit:
              //         packingSpecificationOption[index][1].packageUnit,
              //       measureQuantity,
              //       weight: this.$math.format(
              //         item.weight /
              //           packingSpecificationOption[index][splitIndex]
              //             .packageCell,
              //         14
              //       )
              //     };
              //   });
              //   list.forEach((item) => {
              //     for (let i = 0; i < item.num; i++) {
              //       this.tableData.push({ ...item });
              //     }
              //   });
              //   console.log(list);
              // } else {
              //   return this.$message.error(
              //     `请选择需要正确${this.typeName}选项`
              //   );
              // }
              // console.log(
              //   'packingSpecificationOption-----',
              //   packingSpecificationOption
              // );
            } else {
              // 打包
              let packageUnitList = this.selection.map(
                (item) => item.packingUnit
              );
              let currentIndex = this.selectList.findIndex(
                (item) => item.conversionUnit == this.selectValue
              );
              let split = packageUnitList.every((item) => {
                return (
                  this.selectList.findIndex(
                    (ite) => ite.conversionUnit == item
                  ) ==
                  currentIndex - 1
                );
              });
              if (split) {
                if (
                  this.selection.length ===
                  this.selectList[currentIndex].packageCell
                ) {
                  console.log('开始合并');
                  let { data } = await storageApi.getAssetNum([
                    {
                      assetCode: this.selection[0].categoryCode + '0',
                      batchNum: this.selection[0].batchNo,
                      num: 1
                    }
                  ]);
                  this.tableData.push({
                    ...this.selection[0],
                    packingQuantity: 1,
                    ids: this.selection.map((item) => item.id),
                    packageNo: data[0].onlyCode,
                    packingUnit: this.selectValue,
                    measureQuantity: this.selection.reduce(
                      (a, b) =>
                        this.$math.format(
                          Number(a) + Number(b.measureQuantity),
                          14
                        ),
                      0
                    ),
                    weight: this.selection.reduce(
                      (a, b) =>
                        this.$math.format(Number(a) + Number(b.weight), 14),
                      0
                    )
                  });
                } else {
                  return this.$message.error('请按照包装规格数量进行打包');
                }
              } else {
                return this.$message.error('请检查所选的包装单位是否正确');
              }
              // let isBoolen = this.selection.every(
              //   (item) =>
              //     item.categoryId == this.selection[0].categoryId &&
              //     item.packingUnit == this.selection[0].packingUnit
              // );
              // if (isBoolen) {
              //   let packingSpecification =
              //     await storageApi.getCategoryPackageDisposition({
              //       categoryIds: [this.selection[0].categoryId]
              //     });
              //   let packingSpecificationOption = packingSpecification.sort(
              //     (a, b) => a.sort - b.sort
              //   );
              //   let splitIndex = packingSpecificationOption.findIndex(
              //     (ite) =>
              //       ite.conversionUnit != ite.packageUnit &&
              //       this.selection[0].packingUnit == ite.packageUnit
              //   );
              //   console.log(packingSpecificationOption);
              //   console.log(splitIndex);
              //   if (splitIndex < 0) {
              //     return this.$message.error(
              //       '已经为最大包装维度，不能进行打包'
              //     );
              //   }
              //   if (
              //     this.selection.length <=
              //     packingSpecificationOption[splitIndex].packageCell
              //   ) {
              //     this.tableData.push({
              //       ...this.selection[0],
              //       packingQuantity: 1,
              //       packingUnit:
              //         packingSpecificationOption[splitIndex].conversionUnit,
              //       measureQuantity: this.selection.reduce(
              //         (a, b) =>
              //           this.$math.format(
              //             Number(a) + Number(b.measureQuantity),
              //             14
              //           ),
              //         0
              //       ),
              //       weight: this.selection.reduce(
              //         (a, b) =>
              //           this.$math.format(Number(a) + Number(b.weight), 14),
              //         0
              //       )
              //     });
              //   } else {
              //     return this.$message.error('打包数量超出最大包装数量');
              //   }
              // } else {
              //   return this.$message.error(
              //     `请选择需要正确${this.typeName}选项`
              //   );
              // }
            }
            this.selectionIds = this.selectionIds.concat(
              this.selection.map((item) => item.id)
            );
            console.log('this.selectionIds----', this.selectionIds);
          } else {
            this.$message.error('请选择正确的行');
          }
        } else {
          this.$message.error(`请选择需要${this.typeName}物品`);
        }
      },
      selecctedRow(val) {
        this.selection = val;
      },
      checkSelectable(row) {
        return !this.selectionIds.includes(row.id);
      },
      async handleMine() {
        if (this.tableData.length > 0) {
          if (this.typeName == '拆包') {
            console.log('拆包');
            let params = this.selectionIds.map((item) => {
              return {
                id: item,
                packingLists: this.tableData.filter((ite) => ite.id == item)
              };
            });
            try {
              await storageApi.takeApartPackage(params);
              this.dialogVisible = false;
              this.$emit('flushed');
            } catch (error) {
              return this.$message.error('拆包失败');
            }
          } else {
            console.log('打包');
            let params = this.tableData.map((item) => {
              return {
                ids: item.ids,
                packingInfo: item
              };
            });
            try {
              await storageApi.combinePackage(params);
              this.dialogVisible = false;
              this.$emit('flushed');
            } catch (error) {
              return this.$message.error('打包失败');
            }
          }
        } else {
          return this.$message.error(`请选择需要${this.typeName}的物品`);
        }
      },
      async open(data, typeName) {
        await this.requestDict('不拆物料层规格');
        // 获取包装规格
        let packingSpecification =
          await storageApi.getCategoryPackageDisposition({
            categoryIds: data.map((item) => item.categoryId)
          });
        this.packingSpecificationOption = packingSpecification.sort(
          (a, b) => a.sort - b.sort
        );
        console.log(data[0].measureUnit);
        console.log(this.dict);
        this.isSplit = !!this.getDict('不拆物料层规格', data[0].measureUnit)
          .dictValue;
        console.log(this.isSplit);
        this.productList = data;
        this.typeName = typeName;
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.tableData = [];
          this.selectValue = '';
          this.selectionIds = [];
          this.selection = [];
          this.$refs.table.clearSelection();
        });
      },
      handleClose() {
        this.dialogVisible = false;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .productBox {
    height: 600px;
    display: flex;
    flex: 3;
    > div {
      flex: 1;
      overflow: hidden;
    }
  }
  .productsList {
    margin-right: 10px;
    display: flex;
    flex-direction: column;
    :deep(.el-table) {
      flex: 1;
      display: flex;
      flex-direction: column;
      .el-table__body-wrapper {
        flex: 1;
      }
    }
  }
  .allocateDetails {
    display: flex;
    flex-direction: column;
    :deep(.el-table) {
      flex: 1;
      display: flex;
      flex-direction: column;
      .el-table__body-wrapper {
        flex: 1;
      }
    }
  }
  .control_btn {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 10px;
    > div:first-child {
      flex: 1;
    }
  }
</style>
