<template>
  <el-dialog
    v-dialogDrag
    :title="formParams.wmsMaterialItemMasterName"
    :visible.sync="visible"
    width="1200px"
    append-to-body
    @open="dialogOpen"
    @close="dialogClose"
  >
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="formParams"
      size="small"
      label-width="98px"
      disabled
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="订单号" prop="detailErpId">
            <el-input
              v-model="formParams.detailErpId"
              placeholder="请输入订单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="客户名称" prop="customerName">
            <el-input
              v-model="formParams.customerName"
              placeholder="请输入客户名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="产品名称" prop="materialName">
            <el-input
              v-model="formParams.materialName"
              placeholder="请输入产品名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品批号" prop="materialLots">
            <el-input
              v-model="formParams.materialLots"
              placeholder="请输入产品批号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <!-- <el-col :span="8">
          <el-form-item label="出货数量" prop="deliveredQty">
            <el-input
              v-model="formParams.deliveredQty"
              placeholder="请输入出货数量"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="8">
          <el-form-item label="产品批号" prop="materialLots">
            <el-input
              v-model="formParams.materialLots"
              placeholder="请输入产品批号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="生产日期" prop="ipqcDate">
            <el-input
              v-model="formParams.ipqcDate"
              placeholder="请输入规格"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验标准版本" prop="version">
            <el-input
              v-model="formParams.version"
              placeholder="草稿"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核时间" prop="auditTimeStr">
            <el-input
              v-model="formParams.auditTimeStr"
              placeholder="请输入审核时间"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24" class="text-right">
          <el-button
            type="primary"
            icon="el-icon-printer"
            :loading="printLoading"
            :disabled="apiStatus === -1 || apiStatus === 0"
            size="small"
            @click="handlePrint"
            >检验单打印</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-thumb"
            :loading="submitLoading"
            :disabled="
              apiStatus !== -1 || formParams.additionalAuditStatus === 0
            "
            size="small"
            @click="handleApply"
            >申请修改检验标准</el-button
          >
          <el-button
            v-hasPermi="['wms:ipqc-actual-file:query']"
            type="primary"
            icon="el-icon-upload2"
            :disabled="apiStatus !== -1"
            :loading="printLoading"
            size="small"
            @click="handleUploadFile"
            >上传文件</el-button
          >
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作 -->
    <el-row :gutter="10" class="mb20">
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:ipqc-actual-file:query']"
          type="primary"
          icon="el-icon-upload2"
          :disabled="apiStatus !== -1"
          :loading="printLoading"
          @click="handleUploadFile"
        >上传文件</el-button>
      </el-col> -->
    </el-row>

    <!-- 表体 -->
    <el-table
      ref="table"
      v-loading="loading"
      :data="list"
      border
      size="mini"
      max-height="400"
      :span-method="arraySpanMethod"
      :cell-class-name="delLine"
      @selection-change="tableSelected"
    >
      <el-table-column
        label="检查内容"
        align="center"
        prop="checkCategoryStr"
      />
      <el-table-column
        label="检验项名称"
        align="center"
        prop="inspectionName"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="检查规格/标准"
        align="center"
        width="120"
        prop="standard"
      />
      <el-table-column label="检查工具" align="center" prop="tool" />
      <el-table-column label="检查数量" align="center" prop="checkQuantity" />
      <el-table-column
        label="检查记录(数据)"
        align="center"
        prop="checkQuantity"
      >
        <el-table-column label="NO.1" align="center" prop="actual1">
          <template slot-scope="scope">
            {{
              scope.row.inspectionModel === 1
                ? scope.row.measuredResults
                : scope.row.actual1
            }}
          </template>
        </el-table-column>
        <el-table-column label="NO.2" align="center" prop="actual2" />
        <el-table-column label="NO.3" align="center" prop="actual3" />
        <el-table-column label="NO.4" align="center" prop="actual4" />
        <el-table-column label="NO.5" align="center" prop="actual5" />
      </el-table-column>
      <el-table-column label="判定" align="center" prop="singleResult" />
      <el-table-column
        label="检验文件"
        align="center"
        width="100"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['wms:ipqc-actual-file:query']"
            type="text"
            size="small"
            icon="el-icon-folder-opened"
            @click="handleInspectFile(scope.row)"
            >检验文件</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <span slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button
        type="primary"
        :loading="submitLoading"
        :disabled="apiStatus === 1 || apiStatus === 2 || choiceStatus"
        @click="handleTesting"
        >{{ apiStatus === -1 ? "送审" : "批核" }}</el-button
      >
      <el-button
        v-hasPermi="['wms:material-item:update']"
        type="primary"
        :disabled="apiStatus !== 0"
        :loading="reLoading"
        @click="handleResetInspection"
        >重新检验</el-button
      >
    </span>

    <!-- 批核结果 -->
    <el-dialog
      v-dialogDrag
      title="批核结果"
      :visible.sync="auditVisible"
      width="30%"
      append-to-body
      @close="auditDialogClose"
    >
      <el-form
        ref="auditForm"
        :model="auditParams"
        size="small"
        label-width="98px"
        :rules="rules"
      >
        <el-form-item label="审批结果">
          <el-select v-model="auditParams.flag" placeholder="请选择审核结果">
            <el-option
              v-for="item in auditSelect"
              :key="item.code"
              :label="item.label"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="auditVisible = false">取 消</el-button>
        <el-button type="primary" :loading="ensureLoading" @click="handleEnsure"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改检验标准 -->
    <UpdateInspection
      ref="updateInspection"
      @updateCase="getList"
      @addComplete="getList"
    />
    <!-- 单据打印 -->
    <IssuePrinit ref="issuePrint" />
    <!-- 检验文件 -->
    <InspectFileUploadVue
      ref="inspectFileUpload"
      :process-no="formParams.processNo"
      @uploadComplete="getList"
    />
  </el-dialog>
</template>

<script>
import { finishMaterialItem } from "@/api/wms/quality/inspectionCase";
import {
  getiqcInspectionHead,
  getIqcInspectionDetail_2,
  getIqcInspectionDetail_1,
} from "@/api/wms/quality/inspectionReport";
import { ifChangeMasterAdditional } from "@/api/wms/quality/inspectStandardApproval";
import {
  updateReinspection,
  getURL,
} from "@/api/wms/quality/iqcInspectionExecute";
import IssuePrinit from "../../iqcInspection/components/IssuePrinit.vue";

import { updateAuditStatus } from "@/api/wms/quality/inspectionResultApproval";
// 文件上传
import UpdateInspection from "../../iqcInspection/components/UpdateInspection.vue";
import { parseTime } from "@/utils/ruoyi";
import { mapState } from "vuex";
import { getIpqcResultFiles } from "@/api/wms/quality/ipqcInspectionExecute";
// 检验文件上传
import InspectFileUploadVue from "../../iqcInspection/components/InspectFileUpload.vue";

const AccessTokenKey = "ACCESS_TOKEN";

export default {
  components: {
    UpdateInspection,
    IssuePrinit,
    InspectFileUploadVue,
  },
  data() {
    return {
      visible: false,
      // 遮罩
      finishOpen: false,
      open: false,
      loading: false,
      submitLoading: false,
      // 完成的loading
      buttonLoading: false,
      auditVisible: false,
      ensureLoading: false,

      // 挑选
      choiceStatus: false,
      finishChoice: false,

      reLoading: false,
      showSearch: true,
      // 方案id\additionalId
      wmsMaterialAdditionalId: "",
      wmsMaterialItemMasterId: "",
      // 非计量型禁用实测按钮
      // 总条数
      total: 0,
      // 品质检验执行主列表
      list: [],
      // 挑选查询列表
      choiceList: [],
      // 表体list
      list1: [],
      list2: [],
      valueList: [],
      // 是否允许修改检验标准
      ifModify: "",
      // 根据状态判断是否新增
      updateInspectStatus: "",
      // 版本
      version: "",
      // 重新检验
      reloading: false,
      // 根据审核状态判断调哪个接口
      apiStatus: "",
      formParams: {
        checkName: "",
      },
      // 批核结果参数
      adjustForm: {
        noPassType: "0",
      },
      // 单据打印参数
      tokens: "",
      baseUrl: "",
      reportId: "",
      printLoading: false,
      // 选中的
      currentRows: [],
      // 查询参数
      queryParams: {
        id: null,
        inspectionRegisterId: null,
        inspectionNo: null,
        inspectionResult: null,
        badNo: null,
        createTime: [],
        materialLots: null,
        materialNo: null,
        processNo: null,
        key: null,
        inspectId: null,
      },
      // 批核结果
      auditParams: {
        flag: "",
      },
      auditForm: {},
      auditSelect: [
        {
          label: "合格",
          code: 1,
        },
        {
          label: "不合格",
          code: 2,
        },
      ],
      // 校验规则
      rules: {
        noPassType: [
          {
            required: true,
            message: "请选择检验结果",
            trigger: "blur",
          },
        ],
      },
      // 挑选参数
      choiceParams: {
        materialLots: null,
      },
    };
  },
  computed: {
    ...mapState({
      routeLists: (state) => state.permission.addRoutes,
    }),
  },
  methods: {
    /** 查询列表 */
    async getList() {
      this.loading = true;
      try {
        // 执行查询
        this.formParams.auditTime = parseTime(this.formParams.auditTime);
        // 参数
        const params = {
          materialLots: this.queryParams.materialLots,
          showVoid: false,
          processNo: "FQC",
        };
        // 表头表体列表
        const raw1 = await getIqcInspectionDetail_2(params);
        const raw2 = await getIqcInspectionDetail_1(params);
        const list = [...raw2.data.data, ...raw1.data.data];

        // 数据合并
        this.list = list.reduce((acc, cur) => {
          const data = { ...cur };
          acc.push(data);
          return acc;
        }, []);
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    // 获取iqc报告表头
    getHeadList() {
      const params = {
        key: this.queryParams.key,
        processNo: "FQC",
      };
      getiqcInspectionHead(params).then((res) => {
        this.formParams = res.data.data[0] || {};
        const { title, noPassType, inspector } = this.formParams;
        this.formParams.checkName = title;
        this.adjustForm.noPassType =
          noPassType === null ? this.adjustForm.noPassType : noPassType;
        this.adjustForm.inspector = inspector;
        if (this.adjustForm.noPassType === "2") {
          const { materialLots } = this.queryParams;
          this.choiceParams.materialLots = materialLots;
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
    },
    reset() {
      this.form = {
        manage: undefined,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.pageNo = 1
      this.getList();
    },
    dialogOpen() {
      this.$nextTick(() => {
        this.handleQuery();
        this.getHeadList();
        this.tokens = localStorage.getItem(AccessTokenKey);
        // 打印单据reportId
        this.reportId = this.$route.meta.reportId;
        this.baseUrl = process.env.VUE_APP_REPORT_API;
      });
    },
    // 选择批核结果
    noPassChange(v) {
      //  v === '2' --》挑选
      if (v === "2") {
        const { materialLots } = this.queryParams;
        this.choiceParams.materialLots = materialLots;
        const isEmpty = this.choiceList.some(
          (item) =>
            item.badQty === undefined ||
            item.badQty === "" ||
            item.badQty === null
        );
        // 只允许挑选一次，挑选完批核按钮高亮
        if (isEmpty) {
          this.choiceStatus = true;
          this.finishChoice = false;
        } else {
          this.choiceStatus = false;
          this.finishChoice = true;
        }
      }
    },
    // 送审
    handleTesting() {
      //  apiStatus === -1 为待检验 操作 送审
      if (this.apiStatus === -1) {
        const { materialLots, processNo } = this.formParams;
        this.$modal
          .confirm("您正在送审操作，是否继续？")
          .then(() => {
            const params = {
              materialNo: this.queryParams.materialNo,
              materialLots: this.queryParams.materialLots,
              version: this.formParams.version,
              processNo: this.formParams.processNo,
              excelConfigId: this.reportId || null,
              token: this.tokens,
              queryParam: {
                materialLots,
                processNo,
                key: this.queryParams?.key,
              },
            };
            this.submitLoading = true;
            finishMaterialItem(params)
              .then((res) => {
                this.$modal.msgSuccess("送审完成~");
                this.$emit("complete");
                this.visible = false;
                this.open = false;
                this.submitLoading = false;
                this.reset();
              })
              .finally(() => {
                this.submitLoading = false;
              });
          })
          .catch(() => {
            this.$modal.msg("您已取消操作");
          });
      } else if (this.apiStatus === 0) {
        // apiStatus === 0 为待审核 操作批核
        this.auditVisible = true;
      }
    },
    // 批核
    handleEnsure() {
      const { flag } = this.auditParams;
      const params = {
        noPassType: this.adjustForm.noPassType,
        // id: this.queryParams.inspectId,
        materialNo: this.queryParams.materialNo,
        materialLots: this.queryParams.materialLots,
        processNo: this.formParams.processNo,
        auditStatus: flag,
        wmsSaleOutOrderId: this.formParams.wmsSaleOutOrderId,
        id: this.formParams.wmsIncomingReceiptInspectionId,
      };
      this.ensureLoading = true;
      updateAuditStatus(params)
        .then((res) => {
          this.$modal.msgSuccess("批核完成！");
          this.$emit("complete");
          this.visible = false;
          this.auditVisible = false;
          this.open = false;
          this.getList();
          this.reset();
        })
        .finally(() => {
          this.ensureLoading = false;
          this.queryParams.materialLots = undefined;
          this.queryParams.materialNo = undefined;
          this.queryParams.id = undefined;
        });
    },
    // 重新检验
    handleResetInspection() {
      this.$modal
        .confirm("您正在执行重新检验操作，该操作会导致数据全部清空，是否继续？")
        .then(() => {
          const params = {
            id: this.queryParams.inspectId,
            materialNo: this.queryParams.materialNo,
            materialLots: this.queryParams.materialLots,
            type: this.queryParams.type,
            processNo: this.formParams.processNo,
          };
          this.reLoading = true;
          updateReinspection(params).then((res) => {
            this.$modal.msgSuccess("操作成功");
            this.$emit("resetComplete");
            this.visible = false;
            this.getList();
            this.reLoading = false;
          });
        })
        .catch(() => {
          this.$modal.msg("您已取消操作");
        })
        .finally(() => {
          this.reLoading = false;
        });
    },
    // 填入实测值
    handleEditTestItem(row) {
      const { id } = row;
      this.$refs.measuredDialog.form = row;
      this.$refs.measuredDialog.queryParams.materialItemResultId = id;
      this.$refs.measuredDialog.form.version = this.formParams.version;
      this.$refs.measuredDialog.visible = true;
    },
    // 编辑检验结果
    handleUpdate(row) {
      const { id, inspectionModel } = row;
      this.$refs.editInspectItem.visible = true;
      this.$refs.editInspectItem.form.id = id;
      this.$refs.editInspectItem.inspectionModel = inspectionModel;
      this.$refs.editInspectItem.allInspectShow = true;
    },
    // 申请修改
    handleApply() {
      // this.$refs.updateInspection.queryParams = this.formParams
      const { materialNo, materialName } = this.formParams;
      this.$refs.updateInspection.queryParams.name = materialName;
      this.$refs.updateInspection.queryParams.materialNo = materialNo;
      if (this.formParams.wmsMaterialItemMasterName !== null) {
        this.$refs.updateInspection.queryObj.name =
          this.formParams.wmsMaterialItemMasterName;
      }
      this.$refs.updateInspection.queryParams.wmsMaterialAdditionalId =
        this.wmsMaterialAdditionalId;
      this.$refs.updateInspection.queryParams.wmsMaterialItemMasterId =
        this.formParams.wmsMaterialItemMasterId;
      this.$refs.updateInspection.iqcInspectShow = true;
      this.$refs.updateInspection.queryParams.processNo = "FQC";
      this.$refs.updateInspection.queryParams.type = 2;
      this.$refs.updateInspection.processNameShow = true;

      // page返回的status为0 检验标准详情按钮则为保存， 否则按钮为新增
      if (this.updateInspectStatus !== 0) {
        this.$refs.updateInspection.btnText = "add";
        this.$refs.updateInspection.commitDisable = true;
        this.$refs.updateInspection.refreshDisable = true;
      } else {
        this.$refs.updateInspection.btnText = "save";
        this.$refs.updateInspection.commitDisable = false;
        this.$refs.updateInspection.selectDisable = true;
        this.$refs.updateInspection.wmsMaterialAdditionalId =
          this.wmsMaterialAdditionalId;
        const changeParams = {
          id: this.wmsMaterialAdditionalId,
          code: this.formParams.materialNo,
        };
        // 判断方案是否为最新，不是最新则提示用户刷新
        ifChangeMasterAdditional(changeParams).then((res) => {
          if (res.data === false) {
            this.$refs.updateInspection.refreshDisable = true;
          } else {
            this.$modal.notifyWarning(
              "该方案或已被他人修改，如您需要最新方案，请点击刷新按钮获取！"
            );
            this.$refs.updateInspection.refreshDisable = false;
          }
        });
      }
      this.$refs.updateInspection.visible = true;
    },
    // 弹窗关闭
    dialogClose() {
      this.formParams = {};
      this.list = [];
      this.adjustForm.noPassType = "0";
    },
    // 表格列合并
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      const { inspectionModel } = row;
      // 合并列
      if (inspectionModel === 1) {
        if (columnIndex === 5) {
          return [1, 5];
        } else if (
          columnIndex === 6 ||
          columnIndex === 7 ||
          columnIndex === 8 ||
          columnIndex === 9
        ) {
          return [0, 0];
        }
      }
    },
    // 检验单打印
    handlePrint() {
      const materialLots = this.formParams.materialLots;
      const processNo = this.formParams.processNo;
      const keys = this.queryParams.key;
      const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&materialLots=${materialLots}&processNo=${processNo}&key=${keys}`;
      this.$refs.issuePrint.dialogVisible = true;
      this.$refs.issuePrint.src = src;
    },
    // 作废的数据添加删除线
    delLine({ row, column }) {
      const { voidOrNot } = row;
      if (voidOrNot === "1") {
        return "del_line";
      }
    },
    // 选中的
    tableSelected(val) {
      this.currentRows = val;
    },
    // 上传文件
    async handleUploadFile() {
      this.$refs.inspectFileUpload.wmsIncomingReceiptInspectionId =
        this.formParams.id;
      const params = {
        id: this.formParams.id,
        processNo: "PURCHASE",
      };
      const { data } = await getURL(params);
      this.$refs.inspectFileUpload.fileList = data;
      this.$refs.inspectFileUpload.visible = true;
    },
    auditDialogClose() {
      this.auditParams.flag = undefined;
    },
    // 检验文件
    async handleInspectFile(row) {
      const { id } = row;
      this.$refs.inspectFileUpload.wmsMaterialItemResultId = id;
      const params = {
        id,
        processNo: this.formParams.processNo,
      };
      const { data } = await getIpqcResultFiles(params);
      this.$refs.inspectFileUpload.fileList = data;
      this.$refs.inspectFileUpload.isUploadShow = this.formParams.auditStatus;
      this.$refs.inspectFileUpload.visible = true;
    },
  },
};
</script>
<style scoped>
.stander {
  position: relative;
}
.standVal {
  position: absolute;
  top: 10px;
  left: -10px;
}
.max {
  height: 24px;
}
.line {
  display: block;
  height: 10px;
  margin-top: -14px;
}
.el-table /deep/ .del_line {
  text-decoration: line-through !important;
}
</style>
