<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="poList.filter((item) => item.disposalStatus != 2)"
        :selection.sync="selection"
        :needPage="false"
        row-key="id"
        max-height="500px"
      >
        <!-- 操作列 -->
        <template v-slot:toolbar v-if="showBtn">
          <el-button type="primary" slot="reference" @click="add"
            >新增</el-button
          >
          <el-button
            type="primary"
            slot="reference"
            :disabled="selection.length == 0"
            @click="disposeFn(1)"
            >批量处置</el-button
          >

          <el-popconfirm
            class="ele-action"
            title="确定要删除吗？"
            @confirm="remove"
            style="margin-left: 10px"
          >
            <template v-slot:reference>
              <el-button :disabled="selection.length == 0" type="danger"
                >批量删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>

        <template v-slot:badTypeName="{ row, $index }">
          <el-select
            v-model="row.badTypeId"
            placeholder="请选择不良类型"
            size="small"
            style="width: 100%"
            remote
            filterable
            clearable
          >
            <el-option
              v-for="item in badTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              @click="row.badTypeName = item.name"
            >
            </el-option>
          </el-select>
        </template>

        <template v-slot:badNameName="{ row, $index }">
          <el-select
            v-model="row.badNameId"
            placeholder="请选择不良名称"
            size="small"
            style="width: 100%"
            remote
            filterable
            clearable
          >
            <el-option
              v-for="item in badNameList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              @click="row.badNameName = item.name"
            >
            </el-option>
          </el-select>
        </template>
        <template v-slot:reasonTypeName="{ row, $index }">
          <el-select
            v-model="row.reasonTypeId"
            placeholder="请选择原因类型"
            size="small"
            style="width: 100%"
            remote
            filterable
            clearable
          >
            <el-option
              v-for="item in reasonTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              @click="row.reasonTypeName = item.name"
            >
            </el-option>
          </el-select>
        </template>
        <template v-slot:unqualifiedReason="{ row, $index }">
          <el-input v-model="row.unqualifiedReason"></el-input>
        </template>
      </ele-pro-table>
    </el-card>

    <ele-modal
      :visible.sync="dialogVisible"
      width="35%"
      @close="close"
      append-to-body
      title="处置"
    >
      <el-form
        ref="disposeForm"
        :model="disposeForm"
        label-width="150px"
        :rules="rules"
      >
        <el-form-item label="处置方式：" prop="disposeType">
          <el-select
            v-model="disposeForm.disposeType"
            placeholder="请选择"
            style="width: 100%"
            @change="disposeTypeChange"
          >
            <el-option
              v-for="item in disposeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <template
          v-if="disposeForm.disposeType == 1 || disposeForm.disposeType == 2"
        >
          <el-form-item label="回流工序" prop="taskId" align="center">
            <el-select
              style="width: 100%"
              v-model="disposeForm.taskId"
              clearable
            >
              <el-option
                v-for="item in refluxTaskList"
                :key="item.taskId"
                :value="item.taskId"
                :label="item.taskTypeName"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>

        <template v-if="disposeForm.disposeType == 6">
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="留样数量："
                prop="keepSampleQuantity"
                align="center"
              >
                <el-input
                  v-model="disposeForm.keepSampleQuantity"
                  placeholder="请输入"
                  style="width: 100%"
                >
                  <template slot="append">{{
                    current?.measureUnit
                  }}</template></el-input
                >
              </el-form-item>
            </el-col>
            <el-col :span="6"> </el-col>
          </el-row>
          <el-row style="margin-top: 12px">
            <el-col :span="24">
              <el-form-item label="留样日期：" prop="sampleDate" align="center">
                <el-date-picker
                  class="w100"
                  v-model="disposeForm.sampleDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请输入"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6"> </el-col>
          </el-row>
          <el-row style="margin-top: 12px">
            <el-col :span="24">
              <el-form-item
                label="留样条件："
                prop="sampleCondition"
                align="center"
              >
                <el-input
                  v-model="disposeForm.sampleCondition"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 12px">
            <el-col :span="24">
              <el-form-item
                label="生产商/受托生产："
                prop="producerManufacturer"
                align="center"
              >
                <el-input
                  v-model="disposeForm.producerManufacturer"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 12px">
            <el-col :span="24">
              <el-form-item
                label="留样地点："
                prop="samplePlace"
                align="center"
              >
                <el-input
                  type="textarea"
                  v-model="disposeForm.samplePlace"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 12px">
            <el-col :span="24">
              <el-form-item
                label="留样备注："
                prop="sampleRemark"
                align="center"
              >
                <el-input
                  type="textarea"
                  v-model="disposeForm.sampleRemark"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row style="margin-top: 12px">
            <el-col :span="24"> </el-col>
          </el-row>
        </template>

        <template
          v-if="
            disposeForm.disposeType == 3 ||
            disposeForm.disposeType == 6 ||
            disposeForm.disposeType == 9
          "
        >
          <el-form-item label="入库仓库：" prop="depotId" align="center">
            <el-select style="width: 100%" v-model="disposeForm.depotId">
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
                @click.native="chooseWarehouse(item)"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-form>

      <!-- <DictSelection
        dictName="不良品处理类型"
        :filterArr="all ? ['返工返修'] : []"
        v-model="current.disposalStatus"
      /> -->

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消 </el-button>
        <el-button type="primary" @click="handleDispose">确 定</el-button>
      </div>
    </ele-modal>
    <!-- <Edit ref="edit" @success="save" /> -->
    <ele-modal
      :visible.sync="addDialogVisible"
      width="60%"
      append-to-body
      title="选择"
    >
      <el-table
        :data="inventoryList"
        @selection-change="handleAddSelectionChange"
        row-key="id"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="
            (row, index) => {
              return (
                !poList.map((item) => item.sourceId).includes(row.sourceId) ||
                inventoryList.length == 1
              );
            }
          "
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="sampleCode"
          label="样品编码"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="categoryCode"
          label="物品编码"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="categoryName"
          label="物品名称"
          width="150"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="specification"
          label="规格"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column prop="measureQuantity" label="计量数量" align="center">
          <template slot-scope="scope">
            <template v-if="inventoryList.length === 1">
              <el-input-number
                v-model="singleQuantity"
                :min="0"
                :max="availableTotal"
                style="width: 120px"
              ></el-input-number>
            </template>
            <template v-else>
              {{ scope.row.measureQuantity }}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="measureUnit"
          label="计量单位"
          align="center"
        ></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddSave">确 定</el-button>
      </div>
    </ele-modal>
  </div>
</template>

<script>
  import Edit from './edit.vue';
  import { getWarehouseList } from '@/api/bpm/components/saleManage/saleorder.js';
  import dictMixins from '@/mixins/dictMixins';

  import {
    queryQualitySamplContent,
    queryQualityInventory,
    getById,
    getBadnameList,
    getBadtypeList,
    getReasontypeList
  } from '@/api/bpm/components/qualityReportApproval/qualityReportApproval';
  export default {
    components: {
      Edit
    },
    props: {
      total: {
        type: Number,
        default: 0
      },
      businessType: {
        type: String,
        default: ''
      }
    },
    mixins: [dictMixins],
    data() {
      return {
        cacheKeyUrl: 'qsm-c2e9664a-unqualifiedList-detailList',
        key: '',
        warehouseList: [],
        activeComp: 'main',
        addDialogVisible: false,
        rules: {
          disposeType: [
            { required: true, message: '请选择处置方式', trigger: 'change' }
          ],
          depotId: [
            { required: true, message: '请选择仓库', trigger: 'change' }
          ],
          keepSampleQuantity: [
            {
              validator: (rule, value, callback) => {
                if (
                  this.disposeForm.disposeType === 6 &&
                  this.current &&
                  this.current.measureQuantity !== undefined
                ) {
                  const inputVal = Number(value);
                  const maxVal = Number(this.current.measureQuantity);
                  if (inputVal > maxVal) {
                    return callback(new Error(`不能超过原计量数量${maxVal}`));
                  }
                }
                callback();
              },
              trigger: 'blur'
            }
          ]
        },
        disposeType: '',
        disposeForm: {
          disposeType: '',
          sampleCondition: '',
          sampleDate: '',
          samplePlace: '',
          sampleRemark: '',
          producerManufacturer: '',
          depotId: '',
          depotName: '',
          taskId: '',
          keepSampleQuantity: ''
        },
        loading: false,
        selection: [],
        poList: [],
        id: '',
        dialogVisible: false,
        current: {},
        formData: {},
        all: false,
        qualityType: null,
        allList: [
          { value: 1, label: '返工' },
          { value: 2, label: '返修' },
          { value: 3, label: '报废' },
          { value: 4, label: '降级使用' },
          { value: 5, label: '让步接收' },
          // { value: 6, label: '留样' },
          // { value: 7, label: '消耗' },
          // { value: 8, label: '回用/归批' },
          { value: 9, label: '转试销' },
          { value: 10, label: '退货' }
        ],
        //来料
        disposalStatusListType: [
          {
            value: 5,
            label: '让步接收'
          },
          {
            value: 9,
            label: '退货'
          }
        ],
        //生产
        disposalStatusList: [
          {
            value: 1,
            label: '返工'
          },
          {
            value: 2,
            label: '返修'
          },
          {
            value: 3,
            label: '报废'
          },
          {
            value: 4,
            label: '降级使用'
          },
          {
            value: 5,
            label: '让步接收'
          },
          {
            value: 6,
            label: '留样'
          },
          {
            value: 7,
            label: '消耗'
          },
          {
            value: 8,
            label: '回用'
          }
        ],
        workOrderCode: '',
        qualityWorkerId: '',
        qualityResults: '',
        refluxTaskList: [],
        sampleList: [],
        inventoryList: [],
        oldList: [],
        addSelection: [],
        retainedSampleQuantity: 0,
        retainedSampleUnqualified: 0,
        lossNumber: 0,
        lossNumberUnqualified: 0,
        badTypeList: [],
        badNameList: [],
        reasonTypeList: []
      };
    },
    computed: {
      showBtn() {
        return true;
      },
      disposeList() {
        if (this.qualityType == 1) {
          return this.allList.filter((item) => [5, 10].includes(item.value));
        }
        if (this.qualityType == 2) {
          return this.allList.filter((item) => item.value !== 8);
        }
        if (this.qualityType == 2 || this.qualityType == 3) {
          return this.allList.filter(
            (item) => item.value !== 8 && item.value !== 10
          );
        } else {
          return this.allList;
        }
      },
      // 可用总数 = 总数 - 留样数 - 消耗数
      availableTotal() {
        if (!this.sampleList.length) return this.total;
        const usedQuantity = this.sampleList
          .filter((item) => item.disposeType == 6 || item.disposeType == 7)
          .reduce((sum, item) => sum + (item.measureQuantity || 0), 0);
        return this.total - usedQuantity;
      },
      // 表格列配置
      columns() {
        const arr = [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            reserveSelection: true,
            align: 'center'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            label: '样品编码',
            prop: 'sampleCode',
            width: '150',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryCode',
            label: '物品编码',
            width: '150',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryName',
            label: '物品名称',
            width: '150',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '规格',
            prop: 'specification',
            width: '120',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号',
            align: 'center'
          },
          {
            prop: 'modelType',
            label: '型号',
            align: 'center',
            width: '120',
            showOverflowTooltip: true
          },
          {
            label: '机型',
            prop: 'modelKey',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '颜色',
            prop: 'colorKey',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            width: '120',
            showOverflowTooltip: true
          },
          {
            prop: 'weight',
            label: '重量',
            align: 'center',
            width: '120',
            showOverflowTooltip: true
          },
          {
            prop: 'weightUnit',
            label: '重量单位',
            align: 'center',
            width: '120',
            showOverflowTooltip: true
          },
          {
            prop: 'engrave',
            label: '刻码',
            align: 'center'
          },

          { label: '计量数量', prop: 'measureQuantity', align: 'center' },
          { label: '计量单位', prop: 'measureUnit', align: 'center' },

          {
            prop: 'produceRoutingName',
            label: '工艺路线',
            align: 'center'
          },
          {
            prop: 'produceTaskName',
            label: '工序',
            align: 'center'
          },
          {
            prop: 'badTypeName',
            label: '不良类型',
            slot: 'badTypeName',
            width: '180',
            align: 'center'
          },
          {
            prop: 'badNameName',
            slot: 'badNameName',
            label: '不良名称',
            width: '180',
            align: 'center'
          },
          {
            slot: 'reasonTypeName',
            prop: 'reasonTypeName',
            label: '原因类型',
            width: '180',
            align: 'center'
          },
          {
            slot: 'unqualifiedReason',
            prop: 'unqualifiedReason',
            label: '原因',
            width: '180',
            align: 'center'
          },
          {
            prop: 'disposeTime',
            label: '处置时间',
            align: 'center',
            width: '180',
            showOverflowTooltip: true
          },
          {
            prop: 'disposalStatus',
            label: '处置状态',
            align: 'center',
            fixed: 'right',
            width: '120',
            showOverflowTooltip: true,
            filters: [
              { value: 0, text: '待处置' },
              { value: 1, text: '处置中' }
            ],
            filterMethod: this.disposalStatusFilter,
            formatter: (row, column, cellValue) => {
              return this.disposalStatustList[cellValue ? cellValue : 0];
            }
          },
          {
            prop: 'disposeType',
            label: '处置类型',
            align: 'center',
            fixed: 'right',
            width: '120',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue) => {
              console.log(this.allList.find((item) => item.value == cellValue));

              return this.allList.find((item) => item.value == cellValue)
                ?.label;
            }
          }
        ];
        return arr;
      },
      disposalStatustList() {
        return { 0: '待处置', 1: '处置中', 2: '处置完成' };
      }
    },
    created() {
      this.getBadTypeList();
      this.getBadNameList();
      this.getReasonTypeList();
    },
    methods: {
      disposalStatusFilter(value, row, column) {
        if (value == row.disposalStatus) {
          return row;
        }
      },
      // 查询不良类型
      async getBadTypeList() {
        const res = await getBadtypeList({
          pageNum: 1,
          size: 999
        });
        this.badTypeList = res.list;
      },
      // 查询不良名称
      async getBadNameList() {
        const res = await getBadnameList({
          pageNum: 1,
          size: 999
        });
        this.badNameList = res.list;
      },
      // 查询原因类型
      async getReasonTypeList() {
        const res = await getReasontypeList({
          pageNum: 1,
          size: 999
        });
        this.reasonTypeList = res.list;
      },
      async init(row) {
        this.qualityType = row.qualityType;
        this.id = row.id;
        console.log(row, 'row');
        this.workOrderCode = row.workOrderCode;
        this.qualityWorkerId = row.qualityWorkerId;
        this.qualityResults = row.qualityResults;
        this.warehouseList = await getWarehouseList();
        await this.getQueryQualityInventory();
        await this.queryQualitySamplContent();
        if (this.id) {
          await this.datasource();
        }
      },
      setQualifiedNumber() {
        let isQualifiedNumber = true;
        let noQualifiedNumber = this.poList
          .filter((item) => ![5, 6, 7].includes(item.disposeType))
          .reduce((acc, cur) => acc + cur.measureQuantity, 0);

        if (
          this.poList
            .filter((item) => item.disposeType == 5)
            .reduce((acc, cur) => acc + cur.measureQuantity, 0) ==
          this.availableTotal
        ) {
          isQualifiedNumber = false;
        }
        this.$emit('setQualifiedNumber', {
          noQualifiedNumber,
          qualifiedNumber: this.availableTotal - noQualifiedNumber,
          isQualifiedNumber
        });
      },
      selectResult(qualityResults) {
        if (qualityResults == 1) {
          this.poList = JSON.parse(JSON.stringify(this.oldList));
          this.poList = this.poList.map((item) => {
            if (item.disposalStatus != 2) {
              item.disposalStatus = 1;
              item.disposeType = 5;
            }
            return item;
          });
        }
        if (qualityResults == 4) {
          this.poList = [
            ...JSON.parse(JSON.stringify(this.inventoryList)),
            ...JSON.parse(
              JSON.stringify(
                this.oldList.filter((item) => item.disposalStatus == 2)
              )
            )
          ];
          this.poList = this.poList.map((item) => {
            if (item.disposalStatus != 2) {
              item.disposalStatus = 1;
              item.disposeType = 5;
            }
            return item;
          });
        }
        if (qualityResults == 2) {
          this.poList = [
            ...JSON.parse(JSON.stringify(this.inventoryList)),
            ...JSON.parse(
              JSON.stringify(
                this.oldList.filter((item) => item.disposalStatus == 2)
              )
            )
          ];
        }
        if (qualityResults == 3) {
          this.poList = JSON.parse(JSON.stringify(this.oldList));
        }
        this.qualityResults = qualityResults;
        this.setQualifiedNumber();
      },
      disposeTypeChange() {
        if (this.disposeForm.disposeType == 6) {
          this.disposeForm.keepSampleQuantity =
            this.current?.measureQuantity || '';
        }
      },
      handleAddSelectionChange(selection) {
        this.addSelection = selection;
      },
      handleAddSave() {
        if (this.addSelection.length === 0) {
          this.$message.warning('请选择数据');
          return;
        }
        const poListTotal = this.poList.reduce(
          (sum, item) => sum + Number(item.measureQuantity || 0),
          0
        );
        let selectedTotal = 0;
        if (this.inventoryList.length === 1) {
          selectedTotal =
            this.addSelection.length * Number(this.singleQuantity || 0);
        } else {
          selectedTotal = this.addSelection.reduce(
            (sum, item) => sum + Number(item.measureQuantity || 0),
            0
          );
        }
        if (poListTotal + selectedTotal > this.availableTotal) {
          this.$message.error('选中的计量数量之和加上已有数量不能超过总数');
          return;
        }
        this.addSelection.forEach((item) => {
          const newItem = JSON.parse(JSON.stringify(item));
          if (this.inventoryList.length === 1) {
            newItem.measureQuantity = Number(this.singleQuantity);
          }
          this.poList.push(newItem);
        });
        this.addDialogVisible = false;
        this.setQualifiedNumber();
      },
      add() {
        this.addDialogVisible = true;
        this.addSelection = [];
        if (this.inventoryList.length === 1) {
          this.singleQuantity = this.inventoryList[0].measureQuantity || 0;
        }
      },

      // /* 表格数据源 */
      async datasource() {
        const arr = await getById(this.id);
        this.oldList = JSON.parse(JSON.stringify(arr.poList));
        this.poList = arr.poList;
        this.setQualifiedNumber();
      },

      //   async getRefluxTask() {
      //     await refluxTask({
      //       workOrderCode: this.workOrderCode
      //     }).then((res) => {
      //       this.refluxTaskList = res;
      //     });
      //   },

      remove() {
        let ids = this.selection.map((item) => item.id);
        console.log(ids, 'ids');
        this.poList = this.poList.filter((item) => !ids.includes(item.id));
        this.setQualifiedNumber();
      },
      close() {
        this.dialogVisible = false;
        this.disposeType = '';
        this.all = false;
        this.formData.disposalStatus = '';
      },
      // // 处置
      disposeFn(type, row) {
        if (type == 1) {
          this.all = true;
        } else {
          this.current = row;
        }
        this.formData = { ...row };
        this.dialogVisible = true;
        // let ids = this.current ? [this.current.id] : this.selection.map((item) => item.id);
      },

      async getQueryQualityInventory() {
        const res = await queryQualityInventory({
          qualityWorkerId: this.qualityWorkerId,
          size: -1
        });

        if (res.list.length > 0) {
          this.inventoryList = res.list;
        }
        return;
      },

      async queryQualitySamplContent() {
        const res = await queryQualitySamplContent({
          qualityWorkerId: this.qualityWorkerId,
          size: 1000
        });
        this.sampleList = res.list;
        [
          'retainedSampleQuantity',
          'retainedSampleUnqualified',
          'lossNumber',
          'lossNumberUnqualified'
        ].forEach((key) => {
          this[key] = 0;
        });
        if (this.sampleList.length > 0 && this.inventoryList.length > 0) {
          const processedList = this.sampleList.filter(
            (item) => item.disposeType == 6 || item.disposeType == 7
          );
          console.log(
            processedList.filter((item) => item.disposeType == 6),
            'qwewqe'
          );
          console.log(
            processedList.filter((item) => item.disposeType == 7),
            '123123'
          );
          processedList.forEach((sampleItem) => {
            if (sampleItem.disposeType == 6) {
              sampleItem.qualityResults == 2
                ? (this.retainedSampleUnqualified += sampleItem.measureQuantity)
                : (this.retainedSampleQuantity += sampleItem.measureQuantity);
            } else {
              sampleItem.qualityResults == 2
                ? (this.lossNumberUnqualified += sampleItem.measureQuantity)
                : (this.lossNumber += sampleItem.measureQuantity);
            }
            const inventoryItem = this.inventoryList.find(
              (item) => item.sourceId === sampleItem.sourceId
            );
            if (inventoryItem) {
              inventoryItem.measureQuantity = Math.max(
                0,
                (inventoryItem.measureQuantity || 0) -
                  (sampleItem.measureQuantity || 0)
              );
            }
          });
        }
        this.$emit('setLossNumber', {
          lossNumber: this.lossNumber,
          lossNumberUnqualified: this.lossNumberUnqualified,
          retainedSampleQuantity: this.retainedSampleQuantity,
          retainedSampleUnqualified: this.retainedSampleUnqualified
        });
        if (this.inventoryList.length == 1 && !this.inventoryList[0].sourceId) {
          this.inventoryList[0].measureQuantity =
            this.inventoryList[0].measureQuantity -
            this.lossNumber -
            this.lossNumberUnqualified -
            this.retainedSampleQuantity -
            this.retainedSampleUnqualified;
        }
      },

      async handleDispose() {
        this.$refs['disposeForm'].validate(async (valid) => {
          let ids = this.selection.map((item) => item.id);
          this.poList.forEach((item, index) => {
            if (ids.includes(item.id)) {
              this.$set(this.poList[index], 'disposalStatus', 1);

              for (const key in this.disposeForm) {
                this.$set(this.poList[index], key, this.disposeForm[key]);
              }
            }
          });
          this.dialogVisible = false;
          this.$refs.table.clearSelection();
          this.setQualifiedNumber();
        });
      },
      validate() {},
      getValue() {
        let unqualifiedProducts = { id: this.id };
        let isNodisposeType = false;
        if (this.poList.length > 0) {
          unqualifiedProducts.poList = this.poList.map((item) => {
            if (!item.disposeType && this.businessType.includes('不良品处置')) {
              isNodisposeType = true;
            }
            item.qualityResults = 1;
            item.qualityStatus = 1;
            item.qualityWorkOrderId = this.qualityWorkerId;
            return item;
          });
          [
            'batchNo',
            'brandNum',
            'categoryCode',
            'categoryId',
            'categoryName',
            'factoriesId',
            'measureUnit',
            'modelType',
            'produceRoutingId',
            'produceRoutingName',
            'productCategory'
          ].forEach((item) => {
            unqualifiedProducts[item] = this.poList[0][item];
          });

          unqualifiedProducts.qualityType = this.qualityType;
          unqualifiedProducts.qualityWorkOrderId = this.qualityWorkerId;
          unqualifiedProducts.sourceCode = this.workOrderCode;
          unqualifiedProducts.quantity = this.poList.reduce(
            (total, item) => total + item.measureQuantity,
            0
          );
          unqualifiedProducts.sourceType = this.workOrderId ? 1 : 0;

          return isNodisposeType ? 'isNodisposeType' : unqualifiedProducts;
        }
        return null;
      },
      chooseWarehouse(item) {
        // console.log(item);
        this.disposeForm.depotId = item.id;
        this.disposeForm.depotName = item.name;
      }
    },
    watch: {
      'disposeForm.disposeType': {
        handler(newVal, oldVal) {
          if (newVal == 6) {
            this.rules.depotId = [];
          } else {
            this.rules.depotId = [
              { required: true, message: '请选择仓库', trigger: 'change' }
            ];
          }
          this.disposeForm.sampleCondition = '';
          this.disposeForm.sampleDate = '';
          this.disposeForm.samplePlace = '';
          this.disposeForm.sampleRemark = '';
          this.disposeForm.producerManufacturer = '';
          this.disposeForm.depotId = '';
          this.disposeForm.depotName = '';
          this.disposeForm.taskId = '';
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .unacceptedProductSelect {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
</style>
