<template>
  <div class="p-2">
    <el-card shadow="never" class="mb-[10px]">
      <div style="display: flex; justify-content: space-between">
        <div>
          <el-button type="primary" @click="handleApprovalRecord">流程进度</el-button>
        </div>
        <div>
          <el-button @click="goBack()">返回</el-button>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" class="mb-[10px]">
      <h4>不合格品主表信息</h4>
      <el-form :model="approvalForm" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="不合格检测单号">
              <el-input v-model="approvalForm.unqualifiedReviewNo" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检单号">
              <el-input v-model="approvalForm.inspectionNo" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测类型">
              <el-input v-model="approvalForm.typeName" readonly />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="生产日期">
              <el-input :value="parseTime(approvalForm.productionDate, '{y}-{m}-{d}')" readonly />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="派工单号">
              <el-input v-model="approvalForm.workOrderNo" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序名称">
              <el-input v-model="approvalForm.processName" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料名称">
              <el-input v-model="approvalForm.materialName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编码">
              <el-input v-model="approvalForm.materialCode" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="物料规格">
              <el-input v-model="approvalForm.materialSpec" readonly />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="供应商名称">
              <el-input v-model="approvalForm.supplierName" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商编码">
              <el-input v-model="approvalForm.supplierCode" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检数量">
              <el-input v-model="approvalForm.inspectionQty" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次号">
              <el-input v-model="approvalForm.batchNo" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检人">
              <el-input v-model="approvalForm.inspector" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="评审人">
              <el-input v-model="approvalForm.reviewer" readonly />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="评审开始时间">
              <el-input :value="parseTime(approvalForm.reviewStartTime, '{y}-{m}-{d} {h}:{i}:{s}')" readonly />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="评审结束时间">
              <el-input :value="parseTime(approvalForm.reviewEndTime, '{y}-{m}-{d} {h}:{i}:{s}')" readonly />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-form-item label="处置类型">
          <el-tag :type="getDispositionTypeTag(approvalForm.reviewResult)">
            {{ getDispositionTypeName(approvalForm.reviewResult) }}
          </el-tag>
        </el-form-item>
        <!-- <el-form-item label="备注">
          <el-input v-model="approvalForm.remark" type="textarea" :rows="3" readonly />
        </el-form-item> -->
        <!-- <el-form-item label="审批意见" prop="comment">
          <el-input
            v-model="approvalForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
            :maxlength="500"
            show-word-limit
          />
        </el-form-item> -->
      </el-form>
    </el-card>

    <el-card shadow="never" class="mt-4">
      <h4>不合格品子表明细</h4>
      <el-table v-loading="detailLoading" :data="detailRecordList" border>
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column label="检测项编码" align="center" prop="itemCode" />
        <el-table-column label="检测名称" align="center" prop="itemName" />
        <el-table-column label="检测位置" align="center" prop="inspectionPosition" />
        <el-table-column label="检测方法" align="center" prop="inspectionMethod">
          <template #default="scope">
            <dict-tag :options="qc_methond" :value="scope.row.inspectionMethod" />
          </template>
        </el-table-column>
        <el-table-column label="检测方式" align="center" prop="detectType">
          <template #default="scope">
            <dict-tag :options="detect_type" :value="scope.row.detectType" />
          </template>
        </el-table-column>
        <el-table-column label="检测结果" align="center" prop="detectResult">
          <template #default="scope">
            <dict-tag :options="qc_result" :value="scope.row.detectResult"/>
          </template>
        </el-table-column>
        <el-table-column label="检测值" align="center" prop="detectValue" />
        <el-table-column label="控制上限" align="center" prop="upperLimit" />
        <el-table-column label="控制下限" align="center" prop="lowerLimit" />
        <el-table-column label="规格检测值" align="center" prop="specInspectionValue" />
        <el-table-column label="规格上限" align="center" prop="specUpper" />
        <el-table-column label="规格下限" align="center" prop="specLower" />
        <el-table-column label="检查项说明" align="center" prop="description" :show-overflow-tooltip="true"/>
      </el-table>
      <pagination v-show="detailTotal > 0" :total="detailTotal" v-model:page="detailQueryParams.pageNum" v-model:limit="detailQueryParams.pageSize" @pagination="getDetailList" />
    </el-card>

    <el-card shadow="never" class="mt-4">
      <div class="dialog-footer text-center">
        <el-button type="primary" :loading="approvalButtonLoading" @click="handleApprove">审批通过</el-button>
      </div>
    </el-card>

    <!-- 审批记录组件 -->
    <approvalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="QcUnqualifiedApproval" lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getQcUnqualifiedReview, completeTask } from '@/api/qms/qcUnqualifiedReview';
import { listQcUnqualifiedRecord } from '@/api/qms/qcUnqualifiedRecord';
import { QcUnqualifiedReviewVO } from '@/api/qms/qcUnqualifiedReview/types';
import { QcUnqualifiedRecordVO, QcUnqualifiedRecordQuery } from '@/api/qms/qcUnqualifiedRecord/types';
import { parseTime } from '@/utils/ruoyi';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { getCurrentInstance, toRefs } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { review_result, qc_methond, detect_type, qc_result } = toRefs<any>(proxy?.useDict('review_result', 'qc_methond', 'detect_type', 'qc_result'));

const router = useRouter();
const route = useRoute();
const approvalForm = ref<QcUnqualifiedReviewVO>({} as QcUnqualifiedReviewVO);
const detailRecordList = ref<QcUnqualifiedRecordVO[]>([]);
const detailLoading = ref(false);
const detailTotal = ref(0);
const approvalButtonLoading = ref(false);

const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

const detailQueryParams = ref<QcUnqualifiedRecordQuery>({
  pageNum: 1,
  pageSize: 10,
  reviewId: undefined
});

// 加载数据
const loadData = async () => {
  const businessId = route.query.id as string;
  const taskId = route.query.taskId as string;
  if (!businessId || !taskId) {
    proxy?.$modal.msgError('缺少参数');
    return;
  }

  try {
    const res = await getQcUnqualifiedReview(businessId);
    approvalForm.value = { ...res.data, taskId, comment: '' };

    detailQueryParams.value.reviewId = businessId;
    await getDetailList();
  } catch (error) {
    proxy?.$modal.msgError('加载数据失败');
  }
};

const getDetailList = async () => {
  detailLoading.value = true;
  try {
    const res = await listQcUnqualifiedRecord(detailQueryParams.value);
    detailRecordList.value = res.rows;
    detailTotal.value = res.total;
  } catch (error) {
    proxy?.$modal.msgError('加载子表明细失败');
  } finally {
    detailLoading.value = false;
  }
};

/** 审批通过 */
const handleApprove = async () => {
  // if (!approvalForm.value.comment || approvalForm.value.comment.length < 5) {
  //   proxy?.$modal.msgError('审批意见至少5个字符');
  //   return;
  // }

  approvalButtonLoading.value = true;
  try {
    console.log(approvalForm.value);
    const reviewIdValue = approvalForm.value.reviewId; 
    await completeTask({
     reviewId: reviewIdValue
    });
    proxy?.$modal.msgSuccess('审批通过');
    goBack();
  } catch (error) {
    proxy?.$modal.msgError('审批失败');
  } finally {
    approvalButtonLoading.value = false;
  }
};

/** 查看流程记录 */
const handleApprovalRecord = () => {
  approvalRecordRef.value?.init(approvalForm.value.reviewId);
};

const getDispositionTypeName = (value: string | undefined) => {
  return review_result.value.find(item => item.value === value)?.label || '未知';
};

const getDispositionTypeTag = (value: string | undefined) => {
  // 自定义tag样式
  const tagMap = {
    '0': 'danger',
    '1': 'warning',
    '2': 'info',
    '3': 'success',
    '4': 'primary'
  };
  return tagMap[value || ''] || '';
};

const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  loadData();
});
</script>
