<template>
  <ele-modal
    :visible="visible"
    width="70%"
    append-to-body
    title="检测报告"
    @close="cancel"
    :maxable="true"
  >
    <div class="switch">
      <div class="switch_left">
        <ul>
          <li
            v-for="item in tabOptions"
            :key="item.key"
            :class="{ active: activeComp == item.key }"
            @click="activeComp = item.key"
          >
            {{ item.name }}
          </li>
        </ul>
      </div>
    </div>
    <component
      :is="targetComponent"
      ref="templateRef"
      v-if="visible"
      v-show="activeComp == 'main'"
      :key="componentName"
      :isView="isView"
      :type="type"
    ></component>

    <template v-slot:footer>
      <el-button v-if="isView" type="primary" @click="print">打印</el-button>
      <el-button v-if="!isView" type="primary" @click="save">确认</el-button>
      <el-button
        v-if="!isView && isReportApproval == 1"
        type="primary"
        @click="save('submit')"
        >提交</el-button
      >
      <el-button @click="cancel">关闭</el-button>
    </template>

    <unqualifiedProduct
      ref="unqualifiedProductRef"
      v-show="activeComp == 'unqualifiedList'"
      @setQualifiedNumber="setQualifiedNumber"
      :total="basicInfoData.total"
      :isView="isView"
      @setLossNumber="setLossNumber"
    >
    </unqualifiedProduct>
    <div style="margin-top: 10px" v-if="activeComp != 'bpm'">
      结论：
      <el-select
        v-model="basicInfoData.qualityResults"
        placeholder="请选择"
        style="width: 120px"
        @change="selectResult"
        :disabled="isView"
      >
        <el-option label="整单合格" :value="1" />
        <el-option label="整单不合格" :value="2" />
        <el-option label="部分合格" :value="3" />
        <el-option label="整单让步接收" :value="4" />
      </el-select>

      合格数：
      <el-input
        v-model="basicInfoData.qualifiedNumber"
        placeholder="合格数"
        style="width: 110px"
        disabled
      ></el-input>

      不合格数：
      <el-input
        v-model="basicInfoData.noQualifiedNumber"
        placeholder="不合格数"
        disabled
        style="width: 110px"
      ></el-input>
      留样数(合格)：
      <el-input
        v-model="basicInfoData.retainedSampleQuantity"
        placeholder=" "
        disabled
        style="width: 80px"
      ></el-input>
      留样数(不合格)：
      <el-input
        v-model="basicInfoData.retainedSampleUnqualified"
        placeholder=" "
        disabled
        style="width: 80px"
      ></el-input>
      消耗数(合格)：
      <el-input
        v-model="basicInfoData.lossNumber"
        placeholder=" "
        disabled
        style="width: 80px"
      ></el-input>
      消耗数(不合格)：
      <el-input
        v-model="basicInfoData.lossNumberUnqualified"
        placeholder=" "
        disabled
        style="width: 80px"
      ></el-input>
    </div>
    <bpmDetail
      v-if="activeComp === 'bpm' && processInstanceId"
      :id="processInstanceId"
    ></bpmDetail>

    <processSubmitDialog
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="search"
    ></processSubmitDialog>
  </ele-modal>
</template>

<script>
  import inspection_report1 from '../template/inspection_report1.vue';
  import inspection_report2 from '../template/inspection_report2.vue';
  import processSubmitDialog from '@/components/processSubmitDialog/processSubmitDialog.vue';
  import { getCategoryByCode, parameterGetByCode } from '@/api/main/index';

  import {
    queryInspectionReportData,
    queryInspectionReportList,
    generateReport,enterprisePage
  } from '@/api/inspectionReport';
  import bpmDetail from '@/views/bpm/processInstance/detail.vue';
  import unqualifiedProduct from '@/views/inspectionReport/components/unqualifiedProduct.vue';
  import { getList } from '@/api/unacceptedProduct/index';
  import { getCode } from '@/api/login';
  const defForm = {
    poList: [],
    unqualifiedProductsCode: '',
    sourceCode: '',
    batchNo: '',
    brandNum: '',
    categoryCode: '',
    categoryId: '',
    categoryName: '',
    specification: '',
    modelType: '',
    produceRoutingId: '',
    produceRoutingName: '',
    taskId: '',
    taskName: '',
    quantity: '',
    measureQuantity: '',
    measureUnit: '',
    weight: '',
    weightUnit: '',
    qualityType: ''
  };
  export default {
    name: 'ReportTemplateWrapper',
    components: {
      inspection_report1,
      inspection_report2,
      unqualifiedProduct,
      bpmDetail,
      processSubmitDialog
    },

    data() {
      return {
        unqualifiedProducts: {
          ...defForm
        },
        isReportApproval: 0,
        isView: false,
        visible: false,
        loading: false,
        processSubmitDialogFlag: false,
        currentRow: {}, // 存储当前行数据
        templateItem: {}, // 存储当前模板项数据
        // 基本信息数据
        basicInfoData: {},
        componentName: '',
        // 检验项目
        inspectionItems: [],
        tabOptions: [],
        activeComp: 'main',
        processInstanceId: '',
        reportApprovalTaskVos: [],
        groupName: ''
      };
    },
    props: {
      type: {
        type: String,
        default: '0'
      }
    },
    methods: {
      /* 打开质检报告 */
      async open({ row, item }, isView) {
        parameterGetByCode({
          code: 'qms_report_approval'
        }).then((res) => {
          this.isReportApproval = res.value;
        });
        this.activeComp = 'main';
        this.isView = isView;
        this.componentName = row.reportTemplateCode;
        this.currentRow = row;
        this.templateItem = item?.id ? item : row;

        this.processInstanceId = row.reportProcessInstanceId;
        this.reportApprovalTaskVos = row.reportApprovalTaskVos;
        this.tabOptions = [{ key: 'main', name: '业务详情' }];
        if (isView) {
          this.tabOptions.push({
            key: 'unqualifiedList',
            name: '不合格品台账'
          });
        }

        if (this.processInstanceId) {
          this.tabOptions.push({ key: 'bpm', name: '流程详情' });
        }

        this.visible = true;
        if (this.currentRow.reportTemplateJson?.basicInfoData) {
          this.basicInfoData =
            this.currentRow.reportTemplateJson.basicInfoData || {};
          this.inspectionItems =
            this.currentRow.reportTemplateJson.inspectionItems || [];

          const reviewTime =
            this.reportApprovalTaskVos?.[
              this.reportApprovalTaskVos.length - 2
            ]?.endTime?.split(' ')[0] || '';
          const approvedDate =
            this.reportApprovalTaskVos?.[
              this.reportApprovalTaskVos.length - 3
            ]?.endTime?.split(' ')[0] || '';
          const reviewer =
            this.reportApprovalTaskVos?.[this.reportApprovalTaskVos.length - 2]
              ?.approvalUserName || '';
          const checker =
            this.reportApprovalTaskVos?.[this.reportApprovalTaskVos.length - 3]
              ?.approvalUserName || '';

          this.$set(
            this.basicInfoData,
            'inspectionTime',
            this.basicInfoData.inspectionTime?.split(' ')[0] || ''
          );
          this.$set(
            this.basicInfoData,
            'reviewTime',
            this.basicInfoData.reviewTime?.split(' ')[0] || reviewTime || ''
          );
          this.$set(
            this.basicInfoData,
            'approvedDate',
            this.basicInfoData.approvedDate?.split(' ')[0] || approvedDate || ''
          );
          this.$set(
            this.basicInfoData,
            'reviewer',
            this.basicInfoData.reviewer || reviewer || ''
          );
          this.$set(
            this.basicInfoData,
            'checker',
            this.basicInfoData.checker || checker || ''
          );
          this.$set(
            this.basicInfoData,
            'qualityResults',
            this.basicInfoData.qualityResults
          );
          this.$set(
            this.basicInfoData,
            'qualifiedNumber',
            this.basicInfoData.qualifiedNumber
          );
          this.$set(
            this.basicInfoData,
            'noQualifiedNumber',
            this.basicInfoData.noQualifiedNumber
          );
          this.$nextTick(() => {
            this.$refs.templateRef.init(
              this.basicInfoData,
              this.inspectionItems
            );
          });
          this.initUnqualifiedProduct();
        } else {
          await this.getBasicInfo();
          await this.getInspectionItems();
          await this.enterprisePage();

          this.$nextTick(() => {
            this.$refs.templateRef.init(
              this.basicInfoData,
              this.inspectionItems
            );
          });
        }
      },

      async initUnqualifiedProduct() {
        const data = await getList({
          sourceCode: this.currentRow.code
        });
        if (data.list[0]) {
          this.unqualifiedProducts = data.list[0];
        }

        this.$nextTick(() => {
          this.$refs.unqualifiedProductRef.init({
            id: this.unqualifiedProducts?.id,
            qualityType: this.basicInfoData.qualityType,
            workOrderCode: this.currentRow.code,
            qualityWorkerId: this.basicInfoData.qualityWorkerId,
            workOrderId: this.currentRow.workOrderId,
            qualityResults: this.basicInfoData.qualityResults
          });
        });
      },

      setQualifiedNumber(data) {
        this.basicInfoData.qualifiedNumber = data.qualifiedNumber;
        this.basicInfoData.noQualifiedNumber = data.noQualifiedNumber;
        if (!data.noQualifiedNumber) {
          if (data.isQualifiedNumber) {
            this.basicInfoData.qualityResults = 1;
          } else {
            this.basicInfoData.qualityResults = 4;
          }
        }
        if (!data.qualifiedNumber) {
          this.basicInfoData.qualityResults = 2;
        }

        if (data.qualifiedNumber && data.noQualifiedNumber) {
          this.basicInfoData.qualityResults = 3;
        }
      },

      selectResult() {
        this.$refs.unqualifiedProductRef.selectResult(
          this.basicInfoData.qualityResults
        );
      },
      getBasicInfo() {
        return queryInspectionReportData({
          id: this.currentRow.id,
          type: this.type || this.currentRow.type || 0
        }).then((res) => {
          this.basicInfoData = res;
          this.basicInfoData.reportCode = res.reportCode || '';

          const reviewTime =
            this.reportApprovalTaskVos?.[
              this.reportApprovalTaskVos.length - 2
            ]?.endTime?.split(' ')[0] || '';
          const approvedDate =
            this.reportApprovalTaskVos?.[
              this.reportApprovalTaskVos.length - 3
            ]?.endTime?.split(' ')[0] || '';
          const reviewer =
            this.reportApprovalTaskVos?.[this.reportApprovalTaskVos.length - 2]
              ?.approvalUserName || '';
          const checker =
            this.reportApprovalTaskVos?.[this.reportApprovalTaskVos.length - 3]
              ?.approvalUserName || '';
          this.$set(
            this.basicInfoData,
            'version',
            this.templateItem.versionSymbol +
              this.templateItem.bigVersion +
              this.templateItem.versionMark +
              this.templateItem.smallVersion
          );
          this.$set(
            this.basicInfoData,
            'inspectionTime',
            this.basicInfoData.inspectionTime?.split(' ')[0] || ''
          );
          this.$set(
            this.basicInfoData,
            'reviewTime',
            this.basicInfoData.reviewTime?.split(' ')[0] || reviewTime || ''
          );
          this.$set(
            this.basicInfoData,
            'approvedDate',
            this.basicInfoData.approvedDate?.split(' ')[0] || approvedDate || ''
          );
          this.$set(
            this.basicInfoData,
            'reviewer',
            this.basicInfoData.reviewer || reviewer || ''
          );
          this.$set(
            this.basicInfoData,
            'checker',
            this.basicInfoData.checker || checker || ''
          );

          this.$set(
            this.basicInfoData,
            'qualityResults',
            this.currentRow.noQualifiedNumber == this.basicInfoData.total
              ? 2
              : this.currentRow.noQualifiedNumber == 0
              ? 1
              : 3
          );
          this.$set(
            this.basicInfoData,
            'qualifiedNumber',
            this.currentRow.qualifiedNumber
          );
          this.$set(
            this.basicInfoData,
            'noQualifiedNumber',
            this.currentRow.noQualifiedNumber
          );
          this.$set(
            this.basicInfoData,
            'noQualifiedNumber',
            this.currentRow.noQualifiedNumber
          );

          this.$set(this.basicInfoData, 'qualityWorkerId', this.currentRow.id);
          this.$set(
            this.basicInfoData,
            'workOrderId',
            this.currentRow.workOrderId
          );
          this.$set(this.basicInfoData, 'type', this.type || 0);
          this.$set(
            this.basicInfoData,
            'qualityType',
            this.currentRow.qualityType
          );
          if (!this.basicInfoData.reportNumber) {
            getCode('quality_Inspection_report_number').then((res) => {
              this.$set(this.basicInfoData, 'reportNumber', res);
            });
          }
          this.initUnqualifiedProduct();
        });
      },
      getInspectionItems() {
        return queryInspectionReportList({
          id: this.currentRow.id,
          type: this.type || this.currentRow.type || 0
        }).then((res) => {
          this.inspectionItems = res;
        });
      },
      enterprisePage() {
        return enterprisePage({
          pageNum: 1,
          size: 200
        }).then((res) => {
          if (res.list?.length > 0) {
            this.$set(this.basicInfoData, 'groupName', res.list[0].name);
          }
        });
      },

      setLossNumber({
        lossNumber,
        lossNumberUnqualified,
        retainedSampleQuantity,
        retainedSampleUnqualified
      }) {
        this.$set(
          this.basicInfoData,
          'retainedSampleQuantity',
          retainedSampleQuantity
        );
        this.$set(
          this.basicInfoData,
          'retainedSampleUnqualified',
          retainedSampleUnqualified
        );
        this.$set(this.basicInfoData, 'lossNumber', lossNumber);
        this.$set(
          this.basicInfoData,
          'lossNumberUnqualified',
          lossNumberUnqualified
        );
      },
      cancel() {
        this.visible = false;
        this.$emit('close');
        this.unqualifiedProducts = { ...defForm };
        this.basicInfoData = {};
      },
      /* 打印 */
      print() {
        const printSection = document.getElementById('printSection');
        console.log('printSection', printSection.innerHTML);
        // 创建打印任务
        const printWindow = window.open('', '_blank');
        printWindow.document.open();
        printWindow.document.write('<html><head><title>打印预览</title>');
        printWindow.document.write(
          '<link rel="stylesheet" href="your-stylesheet-url.css" type="text/css" />'
        );
        printWindow.document.write('</head><body>');
        printWindow.document.write(printSection.innerHTML);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.onload = function () {
          printWindow.print();
        };
      },
      /* 保存编辑 */
      save(type) {
        this.loading = true;
        this.isView = true;

        this.$nextTick(() => {
          const printSection = document.getElementById('printSection');

          const params = {
            id: this.currentRow.id,
            type: this.type || this.basicInfoData.type || 0,
            reportTemplateId:
              this.templateItem.reportTemplateId || this.templateItem.id,
            reportTemplateCode:
              this.templateItem.reportTemplateCode || this.templateItem.code,
            reportTemplateName:
              this.templateItem.reportTemplateName || this.templateItem.name,
            unqualifiedProducts: this.$refs.unqualifiedProductRef.getValue(),
            reportTemplateJson: {
              template: printSection.innerHTML,
              basicInfoData: this.$refs.templateRef.getValue(),
              inspectionItems: this.inspectionItems
            }
          };

          generateReport(params)
            .then((res) => {
              this.loading = false;
              this.isView = false;

              this.$message({
                message: '保存成功',
                type: 'success'
              });

              if (type == 'submit') {
                this.approvalSubmit(this.currentRow.id);
              } else {
                this.cancel();
                this.$emit('reload');
              }
            })
            .catch((err) => {
              this.loading = false;
              this.isView = false;

              this.$message({
                message: err.message,
                type: 'error'
              });
            });
        });
      },
      approvalSubmit(id) {
        this.processSubmitDialogFlag = true;
        this.$nextTick(async () => {
          let params = {
            businessId: id,
            businessKey: 'qms_report_approval',
            // formCreateUserId: this.basicInfoData.createUserId,
            variables: {
              businessCode: this.basicInfoData.code,
              businessName: this.basicInfoData.reportNumber,
              businessType: '检测报告单'
            }
          };
          if (this.clientEnvironmentId == 5) {
            const data = await getCategoryByCode(res.productCode);
            if (data && data.categoryLevelCodePath?.includes('W3-209')) {
              params.businessKey = 'qms_report_approval1';
            } else {
              params.businessKey = 'qms_report_approval';
            }
          }
          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      search() {
        this.$emit('reload');
        this.cancel();
      }
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      targetComponent() {
        return this.componentName;
      }
    }
  };
</script>
