<template>
  <div class="ele-body">
    <el-card shadow="never" class="tabs_box">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="基本信息" name="1">
          <el-form ref="form1" :model="form" label-width="94px">
            <el-row>
              <el-col :span="6">
                <el-form-item label="编码">
                  <el-input :value="form.code" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品名称">
                  <el-input :value="form.productName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品编码">
                  <el-input :value="form.productCode" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="批次号">
                  <el-input :value="form.batchNo" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="型号">
                  <el-input :value="form.modelType" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="牌号">
                  <el-input :value="form.brandNo" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="计量类型">
                  <el-input :value="form.inspectionStandardsName" disabled />
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="$store.state.user.info.clientEnvironmentId == '10'"
              >
                <el-form-item label="客户" prop="contactName">
                  <el-input v-model="form.contactName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="form.assignType != 1">
                <el-form-item label="接收人部门">
                  <el-input :value="form.groupName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="form.assignType != 1">
                <el-form-item label="接收人">
                  <el-input :value="qualityName" disabled />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="执行部门"
                  prop="executeDeptName"
                  v-if="form.qualityType != 2 && form.assignType != 1"
                >
                  <el-input :value="form.executeDeptName" disabled />
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="form.qualityType == 2 || form.assignType == 1"
              >
                <el-form-item
                  label="执行班组"
                  prop="executeJobName"
                  v-if="$route.query.name != '计划'"
                >
                  <el-input :value="form.executeJobName" disabled />
                </el-form-item>
                <el-form-item
                  label="执行班组"
                  prop="teamName"
                  v-if="$route.query.name == '计划'"
                >
                  <el-input :value="form.teamName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="执行人" prop="executeUserName">
                  <el-input :value="form.executeUserName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="form.assignType == 1">
                <el-form-item label="场站" prop="productLineId">
                  <el-input v-model="form.productLineName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="检测时间">
                  <el-input :value="qualityTime" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工时(h)">
                  <el-input :value="form.hours" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合格率">
                  <el-input :value="form.qualificationRate" disabled />
                </el-form-item>
              </el-col>
              <!-- </el-row> -->
              <!-- <el-row> -->
              <el-col :span="6">
                <el-form-item label="不合格率">
                  <el-input :value="form.noQualificationRate" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="检验方式">
                  <el-input :value="form.qualityModeName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="检测结果">
                  <el-input :value="form.qualityResultsName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="总重量">
                  <el-input :value="form.totalWeight" disabled />
                </el-form-item>
              </el-col>
              <!-- </el-row> -->
              <!-- <el-row> -->
              <el-col :span="6">
                <el-form-item label="总数量">
                  <el-input :value="form.total" disabled />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="样品数">
                  <el-input :value="form.sampleQuantity" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合格数">
                  <el-input :value="form.qualifiedNumber" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="不合格数">
                  <el-input :value="form.noQualifiedNumber" disabled />
                </el-form-item>
              </el-col>
              <!-- </el-row> -->
              <!-- <el-row> -->
              <el-col :span="6">
                <el-form-item label="规格">
                  <el-input :value="form.specification" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-for="el in disposeTypeList" :key="el.id">
                <el-form-item :label="disposalName(el.disposeType)">
                  <el-input :value="el.measureQuantity" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注">
                  <el-input :value="form.remark" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="附件信息">
                  <!-- <el-link @click="openFileModal" type="primary"
                    >查看附件信息<i class="el-icon-view el-icon--right"></i>
                  </el-link> -->

                  <fileMain ref="fileMainRef" type="view" v-model="accessory" />
                </el-form-item>
              </el-col>
              <el-col :span="18" v-if="$route.query.name == '计划'">
                <el-form-item label="周期">
                  <rule-cycle
                    ref="cycleMultipleRef"
                    :formData="form"
                    :pageType="'detail'"
                    :isBindPlan="true"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="样品信息" name="2">
          <el-form label-width="130px">
            <el-row>
              <el-col
                :span="6"
                v-if="
                  showArrange == '1' ||
                  (showArrange == '2' && form.qualityModeName != '抽检')
                "
              >
                <el-form-item label="样品合格数:">
                  <el-input disabled v-model="form.sampleQualifiedNumber"
                    ><template slot="append">{{
                      sourceData2[0]?.measureUnit
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
              <el-col
                :span="6"
                v-if="
                  showArrange == '1' ||
                  (showArrange == '2' && form.qualityModeName != '抽检')
                "
              >
                <el-form-item label="样品不合格数:">
                  <el-input disabled v-model="form.sampleNoQualifiedNumber"
                    ><template slot="append">{{
                      sourceData2[0]?.measureUnit
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="样品合格率:">
                  <el-input v-model="form.sampleQualificationRate" disabled
                    ><template slot="append">%</template></el-input
                  >
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="样品不合格率:">
                  <el-input v-model="form.sampleNoQualificationRate" disabled
                    ><template slot="append">%</template></el-input
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="样品类型:">
                  <el-input
                    disabled
                    :value="sampletypeVal(form.conditionType)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="样品数量:">
                  <el-input disabled v-model="form.sampleQuantity"
                    ><template slot="append">{{
                      sourceData2[0]?.measureUnit
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="样品重量:">
                  <el-input disabled v-model="form.sampleWeight" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="记录方法:" prop="recordingMethod">
                  <el-input
                    disabled
                    :value="
                      recordingMethodList.find(
                        (item) => item.value == form.recordingMethod
                      )?.label
                    "
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item
                  label="留样数(合格品):"
                  prop="retainedSampleQuantity"
                >
                  <el-input disabled :value="form.retainedSampleQuantity"
                    ><template slot="append">{{
                      sourceData2[0]?.measureUnit
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="留样数(不合格品):"
                  prop="retainedSampleUnqualified"
                >
                  <el-input disabled :value="form.retainedSampleUnqualified"
                    ><template slot="append">{{
                      sourceData2[0]?.measureUnit
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="损耗数(合格品):" prop="lossNumber">
                  <el-input disabled :value="form.lossNumber"
                    ><template slot="append">{{
                      sourceData2[0]?.measureUnit
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="损耗数(不合格品):"
                  prop="lossNumberUnqualified"
                >
                  <el-input disabled :value="form.lossNumberUnqualified"
                    ><template slot="append">{{
                      sourceData2[0]?.measureUnit
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="检测内容" name="3">
          <el-tabs v-model="inspectionName">
            <el-tab-pane label="来源清单" name="1">
              <ele-pro-table
                :columns="tableColumns1"
                :datasource="sourceData1"
                :initLoad="false"
                :needPage="false"
                :toolkit="[]"
                height="calc(100vh - 330px)"
              >
              </ele-pro-table>
            </el-tab-pane>
            <el-tab-pane label="样品清单" name="2">
              <ele-pro-table
                :columns="tableColumns2"
                :datasource="sourceData2"
                :initLoad="false"
                :needPage="false"
                :toolkit="[]"
                height="calc(100vh - 330px)"
              >
                <template v-slot:categoryCode="{ row, $index }">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="handleDetail($index, row, 'detail')"
                  >
                    {{ row.categoryCode }}
                  </el-link>
                </template>
                <template v-slot:attachmentUrl="{ row, $index }">
                  <fileMain type="view" v-model="row.attachmentUrl"> </fileMain>
                </template> </ele-pro-table
            ></el-tab-pane>
            <el-tab-pane label="检测方案" name="3">
              <ele-pro-table
                :columns="tableColumns3"
                :datasource="sourceData3"
                :initLoad="false"
                :needPage="false"
                :toolkit="[]"
                height="calc(100vh - 330px)"
              >
                <template v-slot:experimentCode="scope">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="experimentReport(scope.row)"
                    >{{ scope.row.experimentCode }}
                  </el-link>
                </template>
                <template v-slot:useTools="{ row }">
                  <toolButtom
                    v-model="row.useTools"
                    :type="'detail'"
                    :sList="row.toolList"
                  />
                </template>
                <template v-slot:defaultValue="{ row }">
                  <div style="display: flex; justify-content: center">
                    <span v-if="row.textType != 8">{{ row.symbol }}</span>
                    <span v-if="row.textType == 3">
                      {{ row.minValue }}-{{ row.maxValue }}
                    </span>
                    <span v-else-if="row.textType == 8">
                      标准值：{{ row.defaultValue
                      }}{{ row.unitName || '' }} 下限：{{ row.minValue || 0
                      }}{{ row.unitName || '' }} 上限：{{ row.maxValue || 0
                      }}{{ row.unitName || '' }}
                    </span>
                    <span v-else>
                      <span>{{ row.defaultValue }}</span>
                    </span>
                    <span v-if="row.textType != 8">
                      {{ row.unitName }}
                    </span>
                  </div>
                </template>
              </ele-pro-table></el-tab-pane
            >
            <el-tab-pane label="检测任务单" name="4">
              <ele-pro-table
                ref="table"
                :columns="taskColumns"
                :datasource="taskMonadList"
                :needPage="false"
              >
                <template v-slot:code="{ row }">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="report(row, 'inspectionProjectTask')"
                    >{{ row.code }}</el-link
                  >
                </template>
              </ele-pro-table>
            </el-tab-pane>
            <el-tab-pane label="检测请托单" name="5">
              <ele-pro-table
                ref="table"
                :columns="entrustColumns"
                :datasource="requestEntrustList"
                :needPage="false"
              >
                <template v-slot:code="{ row }">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="report(row, 'inspectionProjectRequest')"
                    >{{ row.code }}</el-link
                  >
                </template>
              </ele-pro-table>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
        <el-tab-pane
          label="样品处置"
          name="4"
          v-show="form.status == 1 && activeName == '4'"
        >
          <ele-pro-table
            :columns="tableColumns4"
            :datasource="sourceData4"
            :initLoad="false"
            :needPage="false"
            :toolkit="[]"
            height="calc(100vh - 260px)"
          >
          </ele-pro-table>
        </el-tab-pane>
        <el-tab-pane label="不良品处置" name="5">
          <ele-pro-table
            :columns="tableColumns5"
            :datasource="sourceData5"
            :initLoad="false"
            :needPage="false"
            :toolkit="[]"
            height="calc(100vh - 260px)"
          >
          </ele-pro-table>
        </el-tab-pane>
        <el-tab-pane label="报工详情" name="6">
          <inspectionProjectReportView
            v-if="form.recordingMethod == 1"
            ref="inspectionProjectReportViewRef"
          ></inspectionProjectReportView>
          <sampleListView v-else ref="sampleListViewRef"></sampleListView>
        </el-tab-pane>
      </el-tabs>
      <el-button class="go_back" @click="goBack">返回</el-button>
    </el-card>
    <sampleListDialog ref="detailRef"></sampleListDialog>
    <experimentReport ref="experimentReport"></experimentReport>
    <sampleReport ref="sampleReportRef" @reload="reload"></sampleReport>
    <!-- 编辑弹窗 -->
    <inspectionProjectReport
      ref="inspectionProjectReportRef"
      @reload="reload"
    />
  </div>
</template>

<script>
  import { getDetailById } from '@/api/inspectionWork/index';
  import { planDetails } from '@/api/inspectionPlan/index';
  import { getByCode } from '@/api/system/dictionary-data';
  import detailMixins from './mixins/detailMixins';
  import { parameterGetByCode } from '@/api/main/index';
  import { getUserPage } from '@/api/system/organization';
  import { recordingMethodList } from '@/utils/util.js';
  import sampleListDialog from './components/sampleListDialog.vue';
  import sampleListView from './components/sampleListView.vue';
  import experimentReport from './components/experimentReport.vue';
  import inspectionProjectReportView from './components/inspectionProjectReportView.vue';
  import inspectionProjectReport from '@/views/inspectionWork/components/inspectionProjectReport.vue';
  import sampleReport from '@/views/inspectionWork/components/sampleReport.vue';
  import { getById as getByIdProjectTask } from '@/api/inspectionProjectTask';
  import { getById as getByIdProjectRequest } from '@/api/inspectionProjectRequest';
  import RuleCycle from '@/components/rule-cycle.vue';
  import toolButtom from './components/toolButtom.vue';

  export default {
    mixins: [detailMixins],
    components: {
      sampleListDialog,
      experimentReport,
      inspectionProjectReport,
      inspectionProjectReportView,
      sampleReport,
      sampleListView,
      RuleCycle,
      toolButtom
    },
    data() {
      return {
        activeName: '1',
        inspectionName: '1',
        recordingMethodList,
        sourceData1: [],
        sourceData2: [],
        sourceData3: [],
        sourceData4: [],
        sourceData5: [],
        taskMonadList: [],
        requestEntrustList: [],
        disposeTypeList: [],
        form: {},
        showArrange: '0',
        executorList: [],
        // 文件
        accessory: []
      };
    },
    computed: {
      sampletypeVal() {
        return (row) => {
          if (row == 1) return '整样';
          if (row == 2) return '小样';
          return '';
        };
      },
      disposalName() {
        return (type) => {
          return this.disposeTypeMap[type] || '';
        };
      },
      qualityName() {
        const list = this.form.qualityWorkOrderDetailVO;
        return this.$route.query.name === '计划'
          ? list?.qualityName || ''
          : this.form.qualityName;
      },
      qualityTime() {
        const list = this.form.qualityWorkOrderDetailVO;
        return this.$route.query.name === '计划'
          ? list?.qualityTime || ''
          : this.form.qualityTime;
      }
    },
    created() {
      this.getData();
      // 是否展示合格不合格
      this.getCode();
    },
    methods: {
      getCode() {
        parameterGetByCode({
          code: 'qms_show_arrange'
        }).then((res) => {
          if (res) {
            this.showArrange = res.value || '1';
            // this.time_calc_code = res.value || '0';
          }
        });
      },
      /* 报工 */
      async report(row, type) {
        let api =
          type == 'inspectionProjectTask'
            ? getByIdProjectTask
            : getByIdProjectRequest;
        const res = await api(row.id);
        if (row.recordingMethod == 1) {
          this.$refs.inspectionProjectReportRef.open(
            {
              workData: {
                ...res.data,
                measureUnit: row.measureUnit,
                workSampleCount: res.sampleTotal
              },
              list: res.data.templateList
            },
            'detail',
            type
          );
        } else {
          this.$refs.sampleReportRef.open(res.data, 'detail', type);
        }
      },
      async getUserList(params) {
        if (!params.groupId) return;
        try {
          let data = { pageNum: 1, size: -1 };
          // 如果传了参数就是获取巡点检人员数据
          if (params) {
            data = Object.assign(data, params);
          }
          const res = await getUserPage(data);
          console.log(res, 'resres');
          this.executorList = res.list;
        } catch (error) {}
      },

      handleDetail(index, row, type) {
        // if (!this.sampleList[index] || !this.schemeList) {
        //   return;
        // }
        // const selectedData = [];
        // selectedData.push(this.sampleList[index]);

        // if (this.schemeList.length != 0) {
        //   this.sampleList.forEach((item) => {
        //     if (item.qualitySampleTemplateList.length == 0) {
        //       item.qualitySampleTemplateList.push(...this.schemeList);
        //     }
        //   });
        // }
        // console.log(selectedData, 'selectedData');

        this.$refs.detailRef.openDia(
          index,
          row,
          type,
          this.sourceData2,
          null,
          this.sourceData2.useTools
        );
      },
      async getData() {
        let id = this.$route.query.id;
        let name = this.$route.query.name;
        try {
          const api = name == '计划' ? planDetails : getDetailById;
          const result = await api(id);
          console.log(result, 'result');
          await this.getUserList({ groupId: result.data.groupId });
          const res = result.data;
          console.log('res~~~~', res.qualityWorkOrderDetailVO);
          const qualityName = [];
          if (res.qualityId && this.executorList.length != 0) {
            res.qualityId.split(',').forEach((item) => {
              this.executorList.forEach((el) => {
                if (el.id == item) {
                  qualityName.push(el.name);
                }
              });
            });
          }
          if (qualityName.length != 0) {
            res.qualityName = qualityName.join(',');
          }
          let obj = {};
          this.infoList.map((item) => {
            obj[item.prop] = res[item.prop];
          });
          this.form = res;
          this.form.status = res.status;
          this.form.qualityWorkOrderDetailVO = res.qualityWorkOrderDetailVO;
          this.accessory = res.accessory;
          console.log(this.form, 'result');
          if (name == '计划') {
            this.form.total = result.data.productNumber || 0;
            this.$nextTick(() => {
              this.$refs.cycleMultipleRef?.setRecordRulesCycleList(
                this.form.cycleList
              );
            });
          }
          this.$nextTick(() => {
            if (this.form.recordingMethod == 1) {
              this.$refs.inspectionProjectReportViewRef.init({
                workData: this.form,
                list: this.form.templateList
              });
            } else {
              this.$refs.sampleListViewRef.init(this.form.qualitySampleList);
            }
          });

          this.fieldAssign(res, obj);
          this.sampleInfo(res);
          console.log('this.form~~~~', this.form);
        } catch (err) {
          console.log(err, 'err');
        }
      },
      sampleInfo(res) {
        this.$set(
          this.form,
          'sampleQualifiedNumber',
          res.sampleQualifiedNumber
        );
        this.$set(
          this.form,
          'sampleNoQualifiedNumber',
          res.sampleNoQualifiedNumber
        );
        this.$set(
          this.form,
          'sampleQualificationRate',
          res.sampleQualificationRate
        );
        this.$set(
          this.form,
          'sampleNoQualificationRate',
          res.sampleNoQualificationRate
        );
        this.$set(this.form, 'conditionType', res.conditionType);
        this.$set(this.form, 'sampleQuantity', res.sampleQuantity);
        this.$set(this.form, 'sampleWeight', res.sampleWeight);
        this.$set(this.form, 'qualifiedNumber', res.qualifiedNumber);
        this.$set(this.form, 'noQualifiedNumber', res.sampleNoQualifiedNumber);
        this.$set(this.form, 'remark', res.remark);
        this.sourceData3 = res.templateList || [];
        this.sourceData1 = res.qualityInventoryList || [];
        this.taskMonadList = res.taskMonadList || [];
        this.requestEntrustList = res.requestEntrustList || [];

        let name = this.$route.query.name;
        // const result = name == '计划' ? res.qualityWorkOrderDetailVO : res;
        let result = {};
        if (name == '计划') {
          this.sourceData4 = res.sampleList || [];
          this.sourceData2 = res.sampleList || [];
          result = res.qualityWorkOrderDetailVO
            ? res.qualityWorkOrderDetailVO
            : {};
        } else {
          result = res;
          this.sourceData4 = res.qualitySampleList || [];
          this.sourceData2 = res.qualitySampleList || [];
        }
        this.sourceData5 = result.unqualifiedDetail || [];
        this.disposeTypeList = result.disposeTypeList || [];
      },
      async fieldAssign(res, obj) {
        if (res.qualityMode == 1) {
          obj.qualityModeName = '全检';
        } else if (res.qualityMode == 2) {
          obj.qualityModeName = '抽检';
        } else {
          obj.qualityModeName = '';
        }
        if (res.qualityResults == 1) {
          obj.qualityResultsName = '合格';
        } else if (res.qualityResults == 2) {
          obj.qualityResultsName = '不合格';
        } else {
          obj.qualityResultsName = '';
        }
        let val = res.inspectionStandards;
        obj.inspectionStandardsName = await this.getDictListIqoCode(val);
      },
      async getDictListIqoCode(value) {
        let { data: res } = await getByCode('measurement_type');
        if (value > 0) {
          return res[value - 1][value];
        }
        return '';
      },
      experimentReport(row) {
        this.$refs.experimentReport.open(
          {
            ...row,
            batchNo: this.form.batchNo,
            qualityWorkOrderId: this.form.id
          },
          'detail'
        );
      },
      goBack() {
        let path = this.$route.query.path || '';
        console.log(path, 'path');
        if (path) {
          this.$router.push({ path: path });
        } else {
          this.$router.go(-1);
        }
      },
      openFileModal() {
        this.$refs.fileMainRef.open(this.accessory, 'view');
      }
    }
  };
</script>

<style lang="scss" scoped>
  .ele-body {
    width: 100%;
    height: calc(100% - 32px);
    box-sizing: border-box;

    .el-card {
      width: 100%;
      height: 100%;
    }
  }

  ::v-deep .el-tabs__content {
    margin-top: 16px;
  }

  .tabs_box {
    position: relative;

    .go_back {
      position: absolute;
      right: 25px;
      top: 19px;
      z-index: 99;
    }
  }
</style>
