<template>
  <el-dialog
    v-dialogDrag
    :title="formParams.checkName"
    :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="IPQC编号" prop="materialLots">
            <el-input
              v-model="formParams.materialLots"
              placeholder="请输入IQC编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品编码" prop="materialNo">
            <el-input
              v-model="formParams.materialNo"
              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-row>
      <el-row :gutter="20">
        <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="productionName">
            <el-input
              v-model="formParams.productionName"
              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="10" class="mb10">
        <el-col :span="24" class="text-right">
          <el-button
            type="primary"
            icon="el-icon-printer"
            :loading="printLoading"
            size="small"
            :disabled="apiStatus === -1 || apiStatus === 0"
            @click="handlePrint"
            >检验单打印</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-thumb"
            :loading="submitLoading"
            size="small"
            :disabled="apiStatus !== -1 || formParams.additionalStatus === 0"
            @click="handleApply"
            >申请修改检验标准</el-button
          >
        </el-col>
      </el-row>
    </el-form>

    <!-- 表体 -->
    <el-table
      ref="table"
      v-loading="loading"
      :data="list"
      border
      size="mini"
      max-height="400"
    >
      <el-table-column
        label="检查类别(大类)"
        align="center"
        prop="checkCategoryStr"
        width="150"
      />
      <el-table-column label="检验名称" align="center" prop="inspectionName" />
      <el-table-column label="检查标准" align="center" prop="standard" />
      <el-table-column
        label="巡检频次"
        align="center"
        prop="checkQuantity"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="检验工具"
        align="center"
        width="120"
        prop="tool"
      />
      <el-table-column
        :label="'首件时间' + formParams.time0"
        align="center"
        prop="actual0"
      >
        <template slot-scope="{ row }">
          <pre class="qaBreak">{{ row.actual0 }}</pre>
        </template>
      </el-table-column>
      <el-table-column
        :label="'巡检时间' + formParams.time1"
        align="center"
        prop="actual1"
      >
        <template slot-scope="{ row }">
          <pre class="qaBreak">{{ row.actual1 }}</pre>
        </template>
      </el-table-column>
      <el-table-column
        :label="'巡检时间' + formParams.time2"
        align="center"
        prop="actual2"
      >
        <template slot-scope="{ row }">
          <pre class="qaBreak">{{ row.actual2 }}</pre>
        </template>
      </el-table-column>
      <el-table-column
        :label="'巡检时间' + formParams.time3"
        align="center"
        prop="actual3"
      >
        <template slot-scope="{ row }">
          <pre class="qaBreak">{{ row.actual3 }}</pre>
        </template>
      </el-table-column>
      <el-table-column
        :label="'巡检时间' + formParams.time4"
        align="center"
        prop="actual4"
      >
        <template slot-scope="{ row }">
          <pre class="qaBreak">{{ row.actual4 }}</pre>
        </template>
      </el-table-column>
      <el-table-column
        :label="'末件时间' + formParams.time5"
        align="center"
        prop="actual5"
      >
        <template slot-scope="{ row }">
          <pre class="qaBreak">{{ row.actual5 }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="异常备注" align="center" prop="singleResult" />
      <el-table-column
        label="异常上升汇报至"
        align="center"
        prop="measuredResults"
        width="130"
      />
    </el-table>

    <!-- 表尾 -->
    <el-form
      v-show="apiStatus !== -1"
      ref="queryForm"
      :model="adjustForm"
      size="small"
      label-width="88px"
      class="mt20"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="检验员" prop="inspector">
            <el-input
              v-model="adjustForm.inspector"
              placeholder="请输入检验员"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核员" prop="auditor">
            <el-input
              v-model="adjustForm.auditor"
              placeholder="请输入审核员"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button
        type="primary"
        :loading="submitLoading"
        :disabled="apiStatus === 0 || apiStatus === 1 || apiStatus === -1"
        @click="handleTesting"
        >{{ apiStatus === -1 ? "送审" : "批核" }}</el-button
      >
      <el-button
        v-hasPermi="['wms:material-item:update']"
        type="primary"
        :disabled="apiStatus !== 0"
        @click="handleResetInspection"
        >重新检验</el-button
      >
    </span>

    <!-- 修改检验标准 -->
    <UpdateInspection
      ref="updateInspection"
      @updateCase="getList"
      @addComplete="getList"
    />
    <!-- IPQC单据打印 -->
    <IpqcIssuePrint ref="ipqcIssuePrint" />

    <!-- 批核结果 -->
    <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" @click="handleEnsure">确 定</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { finishMaterialItem } from "@/api/wms/quality/inspectionCase";
import {
  getiqcInspectionHead,
  getIqcInspectionDetail_2,
  getIqcInspectionDetail_1,
} from "@/api/wms/quality/inspectionReport";
import { updateReinspection } from "@/api/wms/quality/iqcInspectionExecute";
import { updateAuditStatus } from "@/api/wms/quality/inspectionResultApproval";
import IpqcIssuePrint from "./IpqcIssuePrint.vue";

import UpdateInspection from "./UpdateInspection.vue";
import { parseTime } from "@/utils/ruoyi";
import { mapState } from "vuex";

const AccessTokenKey = "ACCESS_TOKEN";

export default {
  components: {
    UpdateInspection,
    IpqcIssuePrint,
  },
  data() {
    return {
      visible: false,
      open: false,
      loading: false,
      submitLoading: false,
      showSearch: true,
      wmsMaterialAdditionalId: "",
      // 非计量型禁用实测按钮
      // 总条数
      total: 0,
      // 品质检验执行主列表
      list: [],
      list1: [],
      list2: [],
      auditVisible: false,
      // 重新检验
      reloading: false,
      // 是否允许修改检验标准
      ifModify: "",
      // 根据状态判断是否新增
      updateInspectStatus: "",
      // 版本
      version: "",
      // 根据审核状态判断调哪个接口
      apiStatus: "",
      formParams: {
        checkName: "",
      },
      adjustForm: {
        noPassType: "0",
      },
      // 单据打印参数
      tokens: "",
      baseUrl: "",
      reportId: "",
      printLoading: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        id: null,
        badNo: null,
        createTime: [],
        materialLots: null,
        materialNo: null,
        processNo: null,
        queryType: undefined,
        materialLotsHead: undefined,
        headerId: undefined,
        inspectId: undefined,
      },
      // 校验规则
      rules: {
        noPassType: [
          {
            required: true,
            message: "请选择检验结果",
            trigger: "blur",
          },
        ],
      },
      // 批核结果
      auditParams: {
        flag: "",
      },
      auditForm: {},
      auditSelect: [
        {
          label: "合格",
          code: 1,
        },
        {
          label: "不合格",
          code: 2,
        },
      ],
    };
  },
  computed: {
    ...mapState({
      routeLists: (state) => state.permission.addRoutes,
    }),
  },
  methods: {
    /** 查询列表 */
    async getList() {
      this.loading = true;
      // 打印单据report Id
      // const isCurRoute = this.routeLists.find(item => item.path === '/wmsquality')
      // const isNow = isCurRoute.children.find(item => item.path === 'ipqcInspection')
      // const isLastPath = isNow.children.find(item => item.componentName === 'IPQCInspectionExecute')
      // this.reportId = isLastPath.reportId
      this.reportId = this.$route.meta.reportId[0];
      try {
        // 执行查询
        this.formParams.auditTime = parseTime(this.formParams.auditTime);
        // 参数
        const params = {
          materialLots: this.queryParams.materialLots,
          headerId: this.queryParams.headerId,
          showVoid: false,
          processNo: this.queryParams.processNo,
          queryType: this.queryParams.queryType,
          auditStatus: this.apiStatus,
        };
        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.materialLotsHead,
        processNo: this.queryParams.processNo,
        auditStatus: this.apiStatus,
      };
      getiqcInspectionHead(params).then((res) => {
        this.formParams = res.data.data[0] || {};
        const {
          noPassType,
          inspector,
          additionalStatus,
          additionalAuditStatus,
        } = this.formParams;
        this.formParams.checkName = "检验标准";
        this.updateInspectStatus = additionalStatus;
        this.ifModify = additionalAuditStatus;
        this.wmsMaterialAdditionalId = this.formParams.additionalId;
        this.adjustForm.noPassType =
          noPassType === null ? this.adjustForm.noPassType : noPassType;
        this.adjustForm.inspector = inspector;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
    },
    reset() {
      this.form = {
        manage: undefined,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    dialogOpen() {
      this.$nextTick(() => {
        this.handleQuery();
        this.getHeadList();
        // 获取单据打印token和请求路径
        this.tokens = localStorage.getItem(AccessTokenKey);
        this.baseUrl = process.env.VUE_APP_REPORT_API;
      });
    },
    // 送审
    handleTesting() {
      if (this.apiStatus === -1) {
        this.$modal
          .confirm("您正在送审操作，是否继续？")
          .then(() => {
            const params = {
              materialNo: this.queryParams.materialNo,
              materialLots: this.queryParams.materialLots,
              version: this.formParams.version,
              processNo: this.formParams.processNo,
            };
            finishMaterialItem(params)
              .then((res) => {
                this.$modal.msgSuccess("送审完成~");
                this.$emit("complete");
                this.visible = false;
                this.open = false;
                this.reset();
              })
              .finally(() => {
                this.submitLoading = false;
              });
          })
          .catch(() => {
            this.$modal.msg("您已取消操作");
          });
      } else if (this.apiStatus === 0) {
        this.auditVisible = true;
      }
    },
    // 批核
    handleEnsure() {
      const { flag } = this.auditParams;
      const params = {
        id: this.queryParams.inspectId,
        materialNo: this.queryParams.materialNo,
        materialLots: this.queryParams.materialLots,
        processNo: this.formParams.processNo,
        auditStatus: flag,
      };
      updateAuditStatus(params)
        .then((res) => {
          this.$modal.msgSuccess("审核完成！");
          this.$emit("complete");
          this.auditVisible = false;
          this.visible = false;
          this.open = false;
          this.getList();
          this.reset();
          this.submitLoading = false;
          this.queryParams.materialLots = undefined;
          this.queryParams.materialNo = undefined;
        })
        .finally(() => {
          this.submitLoading = false;
          this.queryParams.materialLots = undefined;
          this.queryParams.materialNo = 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,
            auditStatus: 2,
          };
          updateReinspection(params).then((res) => {
            this.$modal.msgSuccess("操作成功");
            this.$emit("resetComplete");
            this.auditVisible = false;
            this.visible = false;
            this.getList();
          });
        })
        .catch(() => {
          this.$modal.msg("您已取消操作");
        });
    },
    // 申请修改-->ipqc
    handleApply() {
      const { materialNo, materialName, processNo } = this.formParams;
      this.$refs.updateInspection.queryParams.name = materialName;
      this.$refs.updateInspection.queryParams.materialNo = materialNo;
      this.$refs.updateInspection.queryParams.wmsMaterialAdditionalId =
        this.wmsMaterialAdditionalId;
      this.$refs.updateInspection.iqcInspectShow = true;
      this.$refs.updateInspection.queryParams.processNo = processNo;
      this.$refs.updateInspection.queryParams.type = this.queryParams.type;

      // updateInspectStatus (既additionalStatus) !== 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;
      }
      this.$refs.updateInspection.visible = true;
    },
    // 弹窗关闭
    dialogClose() {
      this.formParams = {};
      this.list = [];
    },
    // 批核弹窗关闭
    auditDialogClose() {
      this.auditParams.flag = undefined;
    },
    // 检验单打印
    handlePrint() {
      const materialLots = this.formParams.materialLots;
      const processNo = this.formParams.processNo;
      const queryType = this.queryParams.queryType;
      const headerId = this.queryParams.headerId;
      const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&materialLots=${materialLots}&processNo=${processNo}&queryType=${queryType}&headerId=${headerId}&key=${this.queryParams.materialLotsHead}&auditStatus=${this.formParams.auditStatus}`;
      this.$refs.ipqcIssuePrint.dialogVisible = true;
      this.$refs.ipqcIssuePrint.src = src;
    },
  },
};
</script>
<style></style>
