<template>
  <el-dialog :visible.sync="visible" title="备品备件申请单" width="90%">
    <div class="sparepart-apply">
      <div class="select-box">
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form label-position="left" label-width="50px">
              <el-form-item label="仓库" required>
                <el-select
                  filterable
                  ref="selectRef"
                  class="w100"
                  size="small"
                  v-model="warehouseId"
                  placeholder="请选择"
                  @change="handleWarehouseChange"
                >
                  <el-option
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                    v-for="(item, index) in warehouseList"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="addGoods">添加物品</el-button>
          </el-col>
        </el-row>
      </div>
      <div class="list-box">
        <div
          class="material-item"
          v-for="(item, index) in registerlist"
          :key="index"
        >
          <el-descriptions
            title=""
            :column="3"
            :labelStyle="{ width: '10%' }"
            size="medium"
            border
          >
            <el-descriptions-item label="物品编码">
              {{ item.informationCode }}
            </el-descriptions-item>
            <el-descriptions-item label="物品名称">
              {{ item.informationName }}
            </el-descriptions-item>
            <el-descriptions-item label="规格型号">
              {{ item.specification }}\{{ item.modelType }}
            </el-descriptions-item>
            <el-descriptions-item label="单位">
              <!-- :label="item.isUnpack ? '包装单位' : '计量单位'" `${item.measuringUnit}/${item.minPackUnit}` -->
              {{ item.isUnpack ? item.measuringUnit : item.minPackUnit }}
            </el-descriptions-item>
            <el-descriptions-item label="所需数量" :span="2">
              <div class="flex-between">
                {{ item.selectNum || 0 }}{{ item.measuringUnit
                }}{{
                  sourceType == 1 ? `/${item.num}${item.measuringUnit}` : ''
                }}
                <el-link @click="addSparepart(item)" type="primary">
                  添加备品备件</el-link
                >
              </div>
            </el-descriptions-item>
            <!-- <el-descriptions-item label=""> 添加备品备件 </el-descriptions-item> -->
          </el-descriptions>
          <el-table
            border
            :data="item.tableData"
            :header-cell-style="{ background: '#F0F3F3' }"
          >
            <el-table-column
              label="序号"
              type="index"
              width="80"
            ></el-table-column>
            <el-table-column
              width="160"
              show-overflow-tooltip
              label="备品备件编码"
              prop="onlyCode"
            ></el-table-column>
            <el-table-column label="批次号" prop="batchNum"></el-table-column>
            <el-table-column
              label="生产日期"
              width="160"
              prop="manufactureTime"
            ></el-table-column>
            <el-table-column
              label="采购日期"
              width="160"
              prop="procurementTime"
            ></el-table-column>
            <el-table-column label="最小包装单元" prop="" v-if="!item.isUnpack"
              ><template slot-scope="{ row }">
                {{ row.measurementUnit }}{{ row.unit }}/{{ row.minPackUnit }}
              </template></el-table-column
            >
            <el-table-column label="包装编码" prop="num"></el-table-column>
            <el-table-column
              label="货位"
              prop=""
              show-overflow-tooltip
              width="300"
            >
              <template slot-scope="{ row }">
                {{ row.warehouseName }}-{{ row.areaName }}-{{
                  row.shelfCode
                }}-{{ row.cargoSpaceCode }}
              </template></el-table-column
            >
            <el-table-column label="操作">
              <template slot-scope="{ row, $index }">
                <el-link type="danger" @click="handleDelete(item, row, $index)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div slot="footer" class="footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <AssetsDialog
      ref="assetsDialogRef"
      title="备品备件"
      :warehousingMaterialList="registerlist"
      :assetType="7"
      :warehouseId="warehouseId"
      @selectTableData="onSelectTableData"
    />

    <detailSelect ref="detailSelectRef" :warehouseId="warehouseId" />
  </el-dialog>
</template>

<script>
  // import detailSelect from './detailSelect.vue'
  // import {
  //   getSparePartsApplyDetail,
  //   sparePartsApplySave
  // } from '@/api/stockManagement/stocking'
  // import { warehouseListValuable } from '@/api/stockManagement/warehouseDefinition'
  // import AssetsDialog from '@/views/warehouseManagement/components/AssetsDialog.vue'
  // import { deepClone } from '@/utils'
  export default {
    components: { detailSelect, AssetsDialog },
    props: {
      sourceType: {
        type: Number, //1,保养工单;2,维修工单
        required: true
      }
    },
    data () {
      return {
        visible: false,
        registerlist: [],
        warehouseIdOld: '',
        warehouseId: '',
        warehouseList: [],
        row: {},
        planList: []
      };
    },
    methods: {
      open (row) {
        this.row = row;
        this.warehouseId = '';
        this.warehouseIdOld = '';
        this.registerlist = [];
        this._getWarehouse();
        if (this.sourceType == 1) {
          this._getSparePartsApplyDetail(row.planCode);
        }
        this.visible = true;
      },
      async submit () {
        const params = {
          sparePartsApplyDetailList: this.registerlist
            .filter((i) => i.tableData.length)
            .map((i) => i.tableData)
            .flat()
            .map((i) => {
              delete i.id;
              return {
                informationCode: i.assetCode,
                informationName: i.assetName,
                assetCode: i.onlyCode
              };
            }),
          sourceCode: this.row.workOrderCode,
          sourceId: this.row.id,
          sourceType: this.sourceType
        };

        if (!params.sparePartsApplyDetailList.length) {
          return this.$message.error('请添加备品备件！');
        }

        const res = await sparePartsApplySave(params);

        if (res?.success) {
          this.$message.success('提交成功！');
          this.visible = false;
          this.$emit('success');
        }
      },
      cancel () {
        this.visible = false;
      },
      addSparepart (item) {
        if (!this.warehouseId) {
          return this.$message.error('请选择仓库！');
        }
        this.$refs.detailSelectRef.open(item, item.tableData).then((res) => {
          item.tableData = res;

          const obj = this.planList.find((i) => i.curId === item.curId);

          item.selectNum = item.tableData.reduce((next, pre) => {
            next += pre.isUnpack ? 1 : pre.measurementUnit || 0;

            return next;
          }, 0);
          if (!obj) {
            // 非计划
            item.num = item.selectNum;
          }
        });
      },
      // 切换仓库清空选择
      handleWarehouseChange () {
        if (
          this.registerlist.length > this.planList.length ||
          this.registerlist.some((i) => i.tableData.length)
        ) {
          Promise.resolve().then(() => {
            this.$refs.selectRef.blur();
            if (this.warehouseIdOld) {
              this.$confirm(
                '仓库修改后，已添加的备品备件信息将会被清空，是否要继续修改仓库？'
              )
                .then(() => {
                  this.registerlist = deepClone(this.planList);
                  this.warehouseIdOld = this.warehouseId;
                })
                .catch(() => {
                  this.warehouseId = this.warehouseIdOld;
                });
            } else {
              this.registerlist = deepClone(this.planList);
              this.warehouseIdOld = this.warehouseId;
            }
          });
        }
      },
      handleDelete (item, row, index) {
        this.$confirm(`确定删除${row.onlyCode}？`).then(() => {
          item.tableData.splice(index, 1);
        });
      },
      async _getSparePartsApplyDetail (planCode) {
        const res = await getSparePartsApplyDetail({ planCode });
        if (res?.success) {
          this.registerlist = res.data.map((item) => ({
            ...item,
            selectNum: 0,
            curId: item.informationCode,
            tableData: []
          }));

          this.planList = deepClone(this.registerlist);
        }
      },
      addGoods () {
        if (!this.warehouseId) {
          return this.$message.error('请选择仓库！');
        }
        this.$refs.assetsDialogRef.open();
      },
      // 选择物品
      onSelectTableData (selectList) {
        this.registerlist = this.registerlist.filter((item) => {
          const index = selectList.findIndex((i) => i.curId === item.curId);

          if (index > -1) {
            selectList.splice(index, 1);
          }

          return index > -1;
        });

        this.registerlist.push(
          ...selectList.map((item) => {
            return {
              curId: item.curId,
              isUnpack: item.isUnpack,
              informationCode: item.assetCode || item.informationCode,
              informationName: item.assetName || item.informationName,
              specification: item.specification,
              minPackUnit: item.minPackUnit,
              modelType: item.modelType,
              measuringUnit: item.unit || item.measuringUnit,
              tableData: item.tableData || [],
              num: 0,
              selectNum: 0
            };
          })
        );
      },
      async _getWarehouse () {
        if (this.warehouseList.length) return;
        const res = await warehouseListValuable();
        if (res?.success) {
          this.warehouseList = res.data.filter((i) => !!i.status);
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .sparepart-apply {
    min-height: 40vh;
    .select-box {
      margin-bottom: 10px;
    }
    .material-item {
      width: 100%;
    }
    .material-item + .material-item {
      margin-top: 10px;
    }
  }

  .flex-between {
    display: flex;
    justify-content: space-between;
    padding-right: 20%;
  }

  .list-box {
    max-height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .footer {
    padding: 10px;
    text-align: right;
    background: #fff;
  }
</style>
