<template>
  <div class="ele-body">
    <el-card shadow="never">
      <seek-page
        :seekList="seekList"
        @search="search"
        ref="search"
        :keyValue="'qms-inspectionReport-index-search'"
      ></seek-page>

      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :pageSize="20"
        :pageSizes="[20, 30, 40, 50, 100]"
        @columns-change="handleColumnChange"
        :cache-key="cacheKeyUrl"
        row-key="id"
        @selection-change="selectionChangeHandle"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <!-- <el-button
            size="small"
            type="primary"
            class="ele-btn-icon"
            @click="batchClose"
            :disabled="selection.length === 0"
          >
            批量关闭
          </el-button> -->
        </template>

        <template v-slot:reportNumber="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="openDetails(row)"
            >{{ row.reportNumber }}</el-link
          >
        </template>

        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            v-if="
              (row.reportApprovalStatus == 0 ||
                row.reportApprovalStatus == 3) &&
              $hasPermission('qms:inspectionReport:update')
            "
            @click="openEdit(row)"
            >编辑</el-link
          >
          <el-link
            v-if="
              isReportApproval == 1 &&
              (row.reportApprovalStatus == 0 ||
                row.reportApprovalStatus == 3) &&
              $hasPermission('qms:inspectionReport:submit')
            "
            type="primary"
            :underline="false"
            @click="reportApprovalSubmit(row)"
            >提交</el-link
          >

          <el-popconfirm
            class="ele-action"
            title="确定要删除吗？"
            @confirm="deleteReportBtn(row)"
            v-if="
              (row.reportApprovalStatus == 0 ||
                row.reportApprovalStatus == 3) &&
              $hasPermission('qms:inspectionReport:delete')
            "
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false"> 删除 </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>

    <component
      v-if="targetVisible"
      :is="targetComponent"
      :key="targetComponent"
      :isView="isView"
      :visible.sync="targetVisible"
      :row="currentRow"
      :item="currentItem"
      @reload="search"
    ></component>

    <process-submit-dialog
      api-fun-name="qmsReportApprovalAPI"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      :isCloseRefresh="false"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="search"
    ></process-submit-dialog>
    <QualityReportDetail
      ref="qualityReportDetailRef"
      :visible.sync="detailVisible"
      :row="currentRow"
    ></QualityReportDetail>
  </div>
</template>
<script>
  import search from './components/search.vue';
  import jimureportBrowse from '@/components/jimureport/browseModal.vue';
  import processSubmitDialog from '@/components/processSubmitDialog/processSubmitDialog.vue';
  import { closeWorkList } from '@/api/inspectionWork';
  import { queryTodo } from '@/api/bpm/task';
  import dictMixins from '@/mixins/dictMixins';
  import { getFile } from '@/api/system/file';
  import { parameterGetByCode } from '@/api/main/index';
  import tabMixins from '@/mixins/tableColumnsMixin';
  import { getCategoryByCode } from '@/api/main/index';
  import { getList, deleteReport } from '@/api/inspectionReport';
  import inspection_report1 from '../inspectionReport/template/inspection_report1.vue';
  import inspection_report2 from '../inspectionReport/template/inspection_report2.vue';
  import QualityReportDetail from '../inspectionReport/components/detailDialog.vue';
  import { recordingMethodList } from '@/utils/util.js';

  export default {
    mixins: [dictMixins, tabMixins],
    components: {
      search,
      jimureportBrowse,
      inspection_report1,
      inspection_report2,
      processSubmitDialog,
      QualityReportDetail
    },
    data() {
      return {
        cacheKeyUrl: 'qsm-c2e9664a-inspectionReport-index',
        targetComponent: null,
        targetVisible: false,
        detailVisible: false,
        isView: false,
        currentRow: {},
        currentItem: {},
        columns: [
          // 新增多选列
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            reserveSelection: true
          },
          {
            type: 'index',
            columnKey: 'index',
            align: 'center',
            label: '序号',
            width: 55,
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'reportNumber',
            label: '报告编码',
            slot: 'reportNumber',
            align: 'center',
            width: 180,
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'code',
            label: '检测工单编码',
            // slot: 'code',
            align: 'center',
            width: 180,
            showOverflowTooltip: true
          },

          {
            prop: 'productCode',
            width: 120,
            label: '产品编码',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'productName',
            width: 120,
            label: '产品名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'brandNo',
            label: '牌号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'recordingMethod',
            label: '记录方法',
            align: 'center',
            formatter: (row) => {
              return (
                recordingMethodList.find(
                  (item) => item.value == row.recordingMethod
                )?.label || ''
              );
            },
            width: 130,
            showOverflowTooltip: true
          },
          {
            label: '创建时间',
            prop: 'reportDate',
            align: 'center',
            width: 160
          },
          {
            label: '创建人',
            prop: 'reportTemplateCreateUserName',
            align: 'center',
            width: 160
          },
          {
            label: '审批时间',
            prop: 'reportApprovalTime',
            align: 'center',
            width: 160
          },
          {
            label: '审批人',
            prop: 'reportApprovalUserName',
            align: 'center',
            width: 160
          },
          {
            prop: 'reportApprovalStatus',
            label: '审批状态',
            align: 'center',
            width: 80,
            formatter: (row, column, cellValue) => {
              switch (cellValue) {
                case 0:
                  return '未提交';
                case 1:
                  return '审核中';
                case 2:
                  return '已审核';
                case 3:
                  return '审核不通过';
                case 7:
                  return '作废';
                default:
                  return '';
              }
            }
          },
          {
            columnKey: 'action',
            label: '操作',
            align: 'center',
            width: 200,
            resizable: false,
            slot: 'action',
            fixed: 'right'
          }
        ],
        formData: {
          certificateNumber: ''
        },
        processSubmitDialogFlag: false,
        rowData: {},
        typeList: [], //类型列表
        qualityMode: [], //取样类型
        statusList: [
          { value: 0, label: '未提交' },
          { value: 1, label: '审核中' },
          { value: 2, label: '已审核' },
          { value: 3, label: '审核不通过' },
          { value: 7, label: '作废' }
        ],
        addOpen: false,
        transferVisible: false,
        transferId: '',
        isReportApproval: 0,
        selection: [] // 存储选中的行数据
      };
    },
    created() {
      this.getCode();
    },
    computed: {
      seekList() {
        return [
          {
            label: '报告编码：',
            value: 'reportNumber',
            type: 'input',
            placeholder: ''
          },
          {
            label: '工单编码：',
            value: 'code',
            type: 'input',
            placeholder: ''
          },
          {
            label: '工单名称：',
            value: 'name',
            type: 'input',
            placeholder: ''
          },
          {
            label: '产品编码：',
            value: 'productCode',
            type: 'input',
            placeholder: ''
          },
          {
            label: '产品名称：',
            value: 'productName',
            type: 'input',
            placeholder: ''
          },
          {
            label: '型号：',
            value: 'modelType',
            type: 'input',
            placeholder: ''
          },
          {
            label: '规格：',
            value: 'specification',
            type: 'input',
            placeholder: ''
          },
          {
            label: '牌号：',
            value: 'brandNo',
            type: 'input',
            placeholder: ''
          },
          {
            label: '审批状态：',
            value: 'reportApprovalStatus',
            type: 'select',
            placeholder: '',
            planList: this.statusList
          },
          {
            label: '记录方法：',
            value: 'recordingMethod',
            type: 'select',
            placeholder: '',
            planList: recordingMethodList
          }
        ];
      },
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      }
    },
    methods: {
      selectionChangeHandle(val) {
        this.selection = val;
      },
      addSampleOpen(row) {
        this.$refs.addSampleRef.open(row);
      },
      // 批量关闭
      batchClose() {
        const validRows = this.selection.filter(
          (row) => row.status === 0 && row.qualityType === 2
        );
        if (validRows.length === 0) {
          this.$message.warning('所选工单中没有可关闭的工单');
          return;
        }

        this.$confirm(`确定关闭选中的 ${validRows.length} 个工单吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await closeWorkList(validRows.map((row) => row.id));
            this.$refs.table.clearSelection();
            this.search();
          } catch (err) {
            this.$message.error('批量关闭失败：' + (err.message || '操作异常'));
          }
        });
      },

      reportApprovalSubmit(res) {
        this.processSubmitDialogFlag = true;
        this.$nextTick(async () => {
          let params = {
            businessId: res.id,
            businessKey: 'qms_report_approval',
            formCreateUserId: res.createUserId,
            variables: {
              businessCode: res.code,
              businessName: res.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);
        });
      },
      getCode() {
        parameterGetByCode({
          code: 'qms_report_approval'
        }).then((res) => {
          this.isReportApproval = res.value;
        });
      },
      async datasource({ page, where, limit }) {
        try {
          await queryTodo({});
        } catch (err) {
          console.error('调用queryTodo失败：', err);
        }

        return getList({
          ...where,
          pageNum: page,
          size: limit
        });
      },
      search(where) {
        this.$refs.table.reload({
          where: where
          // page: 1
        });
      },
      async openEdit(row) {
        console.log(row);
        this.isView = false;
        this.targetComponent = row.reportTemplateCode;
        this.currentRow = row;
        this.$nextTick(() => {
          this.targetVisible = true;
        });
      },
      openDetails(row) {
        this.isView = true;
        this.currentRow = row;
        this.targetComponent = row.reportTemplateCode;
        console.log('currentRow', this.currentRow, this.targetComponent);
        this.$nextTick(() => {
          this.targetVisible = true;
          console.log('targetVisible~~~~', this.targetVisible);
        });
      },
      async deleteReportBtn(row) {
        try {
          await deleteReport(row.id);
          this.$message.success('删除成功');
          this.done();
        } catch (err) {
          // this.$message.error('删除失败：' + (err.message || '操作异常'));
        }
      },
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },
      done() {
        this.$refs.search.search();
      }
    }
  };
</script>
