<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" >
            <!-- <el-form-item label="评审主键" prop="reviewId">
              <el-input v-model="queryParams.reviewId" placeholder="请输入评审主键" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="不合格检测单号" prop="unqualifiedReviewNo" label-width="120px">
              <el-input v-model="queryParams.unqualifiedReviewNo" placeholder="请输入不合格检测单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="评审结果" prop="reviewResult">
              <el-select v-model="queryParams.reviewResult" placeholder="请选择评审结果" clearable >
                <el-option v-for="dict in review_result" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="质检单号" prop="inspectionNo">
              <el-input v-model="queryParams.inspectionNo" placeholder="请输入质检单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="检测类型" prop="inspectionType">
              <el-input v-model="queryParams.inspectionType" placeholder="请输入检测类型" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <!-- <el-form-item label="生产日期" prop="productionDate">
              <el-date-picker clearable
                v-model="queryParams.productionDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择生产日期"
              />
            </el-form-item> -->
            <el-form-item label="派工单号" prop="workOrderNo">
              <el-input v-model="queryParams.workOrderNo" placeholder="请输入派工单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="工序名称" prop="processName">
              <el-input v-model="queryParams.processName" placeholder="请输入工序名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物料规格" prop="materialSpec">
              <el-input v-model="queryParams.materialSpec" placeholder="请输入物料规格" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商编码" prop="supplierCode">
              <el-input v-model="queryParams.supplierCode" placeholder="请输入供应商编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="质检数量" prop="inspectionQty">
              <el-input v-model="queryParams.inspectionQty" placeholder="请输入质检数量" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="批次号" prop="batchNo">
              <el-input v-model="queryParams.batchNo" placeholder="请输入批次号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="质检人" prop="inspector">
              <el-input v-model="queryParams.inspector" placeholder="请输入质检人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="质检人ID" prop="inspectorId">
              <el-input v-model="queryParams.inspectorId" placeholder="请输入质检人ID" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="评审人" prop="reviewer">
              <el-input v-model="queryParams.reviewer" placeholder="请输入评审人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="评审人ID" prop="reviewerId">
              <el-input v-model="queryParams.reviewerId" placeholder="请输入评审人ID" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="评审开始时间" label-width="100px">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['qms:qcUnqualifiedReview:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['qms:qcUnqualifiedReview:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['qms:qcUnqualifiedReview:remove']">删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['qms:qcUnqualifiedReview:export']">导出</el-button>
          </el-col>
          <el-divider direction="vertical" />
          <el-col :span="1.5">
            <el-button type="primary" plain @click="handleFlow" :disabled="multiple" v-hasPermi="['qms:qcUnqualifiedReview:flow']">流转</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain @click="handleScrap" :disabled="multiple" v-hasPermi="['qms:qcUnqualifiedReview:scrap']">报废</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain @click="handleConcession" :disabled="multiple" v-hasPermi="['qms:qcUnqualifiedReview:concession']">让步接收</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain @click="handleRework" :disabled="multiple" v-hasPermi="['qms:qcUnqualifiedReview:rework']">返工</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain @click="handleReturn" :disabled="multiple" v-hasPermi="['qms:qcUnqualifiedReview:return']">退货</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="qcUnqualifiedReviewList" @selection-change="handleSelectionChange" @row-click="handleRowClick" highlight-current-row>
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="评审主键" align="center" prop="reviewId" v-if="columns[0].visible"/> -->
         <!-- 自动序号 -->
          <el-table-column type="index" label="序号" width="55" align="center" v-if="columns[0].visible"/>
        <el-table-column label="不合格检测单号" align="center" prop="unqualifiedReviewNo" width="120" v-if="columns[1].visible"/>
        <el-table-column label="评审结果" align="center" prop="reviewResult" v-if="columns[2].visible">
          <template #default="scope">
            <dict-tag :options="review_result" :value="scope.row.reviewResult"/>
          </template>
        </el-table-column>
        <el-table-column label="质检单号" align="center" prop="inspectionNo" v-if="columns[3].visible"/>
        <el-table-column label="检测类型" align="center" prop="typeName" v-if="columns[4].visible"/>
        <el-table-column label="生产日期" align="center" prop="productionDate" width="180" v-if="columns[5].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="派工单号" align="center" prop="workOrderNo" v-if="columns[6].visible"/>
        <el-table-column label="工序名称" align="center" prop="processName" v-if="columns[7].visible"/>
        <el-table-column label="物料名称" align="center" prop="materialName" v-if="columns[8].visible"/>
        <el-table-column label="物料编码" align="center" prop="materialCode" v-if="columns[9].visible"/>
        <el-table-column label="物料规格" align="center" prop="materialSpec" v-if="columns[10].visible"/>
        <el-table-column label="供应商名称" align="center" prop="supplierName" width="120" v-if="columns[11].visible"/>
        <el-table-column label="供应商编码" align="center" prop="supplierCode" width="120" v-if="columns[12].visible"/>
        <el-table-column label="质检数量" align="center" prop="inspectionQty" v-if="columns[13].visible"/>
        <el-table-column label="批次号" align="center" prop="batchNo" v-if="columns[14].visible"/>
        <el-table-column label="质检人" align="center" prop="inspector" v-if="columns[15].visible"/>
        <!-- <el-table-column label="质检人ID" align="center" prop="inspectorId" v-if="columns[16].visible"/> -->
        <el-table-column label="评审人" align="center" prop="reviewer" v-if="columns[16].visible"/>
        <!-- <el-table-column label="评审人ID" align="center" prop="reviewerId" v-if="columns[19].visible"/> -->
        <el-table-column label="评审开始时间" align="center" prop="reviewStartTime" width="180" v-if="columns[17].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.reviewStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="评审结束时间" align="center" prop="reviewEndTime" width="180" v-if="columns[18].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.reviewEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[19].visible"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['qms:qcUnqualifiedReview:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['qms:qcUnqualifiedReview:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 子表显示区域 -->
    <el-card v-if="selectedReviewId" shadow="never" class="mt-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h3>不合格品评审记录 - {{ selectedUnqualifiedReviewNo }}</h3>
          <!-- <el-button type="primary" size="small" icon="Plus" @click="handleAddQcUnqualifiedRecord" v-hasPermi="['qms:qcUnqualifiedRecord:add']">
            新增评审记录
          </el-button> -->
        </div>
      </template>

      <!-- 子表数据表格 -->
      <el-table v-loading="qcUnqualifiedRecordLoading" :data="qcUnqualifiedRecordList" @selection-change="handleQcUnqualifiedRecordSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="记录主键" align="center" prop="recordId" /> -->
        <!-- 自动序号 -->
        <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="description" :show-overflow-tooltip="true"/>
        <el-table-column label="规格下限" align="center" prop="specLower" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdateQcUnqualifiedRecord(scope.row)" v-hasPermi="['qms:qcUnqualifiedRecord:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDeleteQcUnqualifiedRecord(scope.row)" v-hasPermi="['qms:qcUnqualifiedRecord:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="qcUnqualifiedRecordTotal > 0" :total="qcUnqualifiedRecordTotal" v-model:page="qcUnqualifiedRecordParams.pageNum" v-model:limit="qcUnqualifiedRecordParams.pageSize" @pagination="getQcUnqualifiedRecordList" />
    </el-card>

    <!-- 添加或修改不合格品待评审对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
            <el-form ref="qcUnqualifiedReviewFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
        <el-form-item label="不合格检测单号" prop="unqualifiedReviewNo">
          <el-input v-model="form.unqualifiedReviewNo" placeholder="请输入不合格检测单号" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="评审结果" prop="reviewResult">
          <el-select v-model="form.reviewResult" placeholder="请选择评审结果">
            <el-option
                v-for="dict in review_result"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="质检单号" prop="inspectionNo">
          <el-input v-model="form.inspectionNo" placeholder="请输入质检单号" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="检测类型" prop="inspectionType">
          <el-input v-model="form.inspectionType" placeholder="请输入检测类型" />
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="生产日期" prop="productionDate">
            <el-date-picker clearable
                v-model="form.productionDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择生产日期">
            </el-date-picker>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商编码" prop="supplierCode">
              <el-input v-model="form.supplierCode" placeholder="请输入供应商编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="质检数量" prop="inspectionQty">
              <el-input v-model="form.inspectionQty" placeholder="请输入质检数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNo">
              <el-input v-model="form.batchNo" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="质检人" prop="inspector">
              <el-input v-model="form.inspector" placeholder="请输入质检人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评审人" prop="reviewer">
              <el-input v-model="form.reviewer" placeholder="请输入评审人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="评审开始时间" prop="reviewStartTime">
              <el-date-picker clearable
                v-model="form.reviewStartTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择评审时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评审结束时间" prop="reviewEndTime">
              <el-date-picker clearable
                              v-model="form.reviewEndTime"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择评审时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改不合格品评审记录对话框 -->
    <el-dialog :title="qcUnqualifiedRecordDialog.title" v-model="qcUnqualifiedRecordDialog.visible" width="800px" append-to-body>
      <el-form ref="qcUnqualifiedRecordFormRef" :model="qcUnqualifiedRecordForm" :rules="qcUnqualifiedRecordRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="不合格单号" prop="unqualifiedReviewNo">
              <el-input v-model="selectedUnqualifiedReviewNo" placeholder="不合格单号" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测项编码" prop="itemCode">
              <el-input v-model="qcUnqualifiedRecordForm.itemCode" placeholder="请输入检测项编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测名称" prop="itemName">
              <el-input v-model="qcUnqualifiedRecordForm.itemName" placeholder="请输入检测名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测位置" prop="inspectionPosition">
              <el-input v-model="qcUnqualifiedRecordForm.inspectionPosition" placeholder="请输入检测位置" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测方法" prop="inspectionMethod">
              <el-select v-model="qcUnqualifiedRecordForm.inspectionMethod" placeholder="请选择检测方法">
                <el-option v-for="dict in qc_methond" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测方式" prop="detectType">
              <el-select v-model="qcUnqualifiedRecordForm.detectType" placeholder="请选择检测方式">
                <el-option v-for="dict in detect_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测结果" prop="detectResult">
              <el-select v-model="qcUnqualifiedRecordForm.detectResult" placeholder="请选择检测结果">
                <el-option v-for="dict in qc_result" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测值" prop="detectValue">
              <el-input v-model="qcUnqualifiedRecordForm.detectValue" placeholder="请输入检测值" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="控制上限" prop="upperLimit">
              <el-input v-model="qcUnqualifiedRecordForm.upperLimit" placeholder="请输入控制上限" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="控制下限" prop="lowerLimit">
              <el-input v-model="qcUnqualifiedRecordForm.lowerLimit" placeholder="请输入控制下限" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格检测值" prop="specInspectionValue">
              <el-input v-model="qcUnqualifiedRecordForm.specInspectionValue" placeholder="请输入规格检测值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格上限" prop="specUpper">
              <el-input v-model="qcUnqualifiedRecordForm.specUpper" placeholder="请输入规格上限" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格下限" prop="specLower">
              <el-input v-model="qcUnqualifiedRecordForm.specLower" placeholder="请输入规格下限" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="检查项说明" prop="description">
              <el-input v-model="qcUnqualifiedRecordForm.description" type="textarea" placeholder="请输入检查项说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="qcUnqualifiedRecordButtonLoading" type="primary" @click="submitQcUnqualifiedRecordForm">确 定</el-button>
          <el-button @click="cancelQcUnqualifiedRecord">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="QcUnqualifiedReview" lang="ts">
import {
  listQcUnqualifiedReview,
  getQcUnqualifiedReview,
  delQcUnqualifiedReview,
  addQcUnqualifiedReview,
  updateQcUnqualifiedReview,
  handleUnqualified
} from '@/api/qms/qcUnqualifiedReview';
import { QcUnqualifiedReviewVO, QcUnqualifiedReviewQuery, QcUnqualifiedReviewForm } from '@/api/qms/qcUnqualifiedReview/types';
import { listQcUnqualifiedRecord, getQcUnqualifiedRecord, delQcUnqualifiedRecord, addQcUnqualifiedRecord, updateQcUnqualifiedRecord } from '@/api/qms/qcUnqualifiedRecord';
import { QcUnqualifiedRecordVO, QcUnqualifiedRecordQuery, QcUnqualifiedRecordForm } from '@/api/qms/qcUnqualifiedRecord/types';

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 qcUnqualifiedReviewList = ref<QcUnqualifiedReviewVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const inspectionNos = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const qcUnqualifiedReviewFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
        { key: 0, label: `序号`, visible: false },
        { key: 1, label: `不合格检测单号`, visible: true },
        { key: 2, label: `评审结果`, visible: true },
        { key: 3, label: `质检单号`, visible: true },
        { key: 4, label: `检测类型`, visible: true },
        { key: 5, label: `生产日期`, visible: false },
        { key: 6, label: `派工单号`, visible: true },
        { key: 7, label: `工序名称`, visible: true },
        { key: 8, label: `物料名称`, visible: true },
        { key: 9, label: `物料编码`, visible: true },
        { key: 10, label: `物料规格`, visible: false },
        { key: 11, label: `供应商名称`, visible: true },
        { key: 12, label: `供应商编码`, visible: true },
        { key: 13, label: `质检数量`, visible: true },
        { key: 14, label: `批次号`, visible: true },
        { key: 15, label: `质检人`, visible: true },
        // { key: 16, label: `质检人ID`, visible: true },
        { key: 16, label: `评审人`, visible: true },
        // { key: 18, label: `评审人ID`, visible: true },
        { key: 17, label: `评审开始时间`, visible: true },
        { key: 18, label: `评审结束时间`, visible: true },
        { key: 19, label: `备注`, visible: true },

]);

const initFormData: QcUnqualifiedReviewForm = {
  reviewId: undefined,
  unqualifiedReviewNo: undefined,
  reviewResult: undefined,
  inspectionNo: undefined,
  inspectionType: undefined,
  productionDate: undefined,
  workOrderNo: undefined,
  processName: undefined,
  materialName: undefined,
  materialCode: undefined,
  materialSpec: undefined,
  supplierName: undefined,
  supplierCode: undefined,
  inspectionQty: undefined,
  batchNo: undefined,
  inspector: undefined,
  inspectorId: undefined,
  reviewer: undefined,
  reviewerId: undefined,
  reviewStartTime: undefined,
  reviewEndTime: undefined,
  remark: undefined,
}
const data = reactive<PageData<QcUnqualifiedReviewForm, QcUnqualifiedReviewQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    reviewId: undefined,
    unqualifiedReviewNo: undefined,
    reviewResult: undefined,
    inspectionNo: undefined,
    inspectionType: undefined,
    productionDate: undefined,
    workOrderNo: undefined,
    processName: undefined,
    materialName: undefined,
    materialCode: undefined,
    materialSpec: undefined,
    supplierName: undefined,
    supplierCode: undefined,
    inspectionQty: undefined,
    batchNo: undefined,
    inspector: undefined,
    inspectorId: undefined,
    reviewer: undefined,
    reviewerId: undefined,
    reviewStartTime: undefined,
    reviewEndTime: undefined,
    params: {
    }
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

const dateRange = ref([]);

/** 查询不合格品待评审列表 */
const getList = async () => {
  loading.value = true;
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.params = {
      ...queryParams.value.params,
      beginReviewStartTime: dateRange.value[0],
      endReviewStartTime: dateRange.value[1]
    };
  } else {
    if (queryParams.value.params) {
      delete queryParams.value.params.beginReviewStartTime;
      delete queryParams.value.params.endReviewStartTime;
    }
  }
  const res = await listQcUnqualifiedReview(queryParams.value);
  qcUnqualifiedReviewList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  qcUnqualifiedReviewFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  dateRange.value = [];
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: QcUnqualifiedReviewVO[]) => {
  ids.value = selection.map(item => item.reviewId);
  inspectionNos.value = selection.map(item => item.inspectionNo);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加不合格品待评审";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: QcUnqualifiedReviewVO) => {
  reset();
  const _reviewId = row?.reviewId || ids.value[0]
  const res = await getQcUnqualifiedReview(_reviewId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改不合格品待评审";
}

/** 提交按钮 */
const submitForm = () => {
  qcUnqualifiedReviewFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.reviewId) {
        await updateQcUnqualifiedReview(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addQcUnqualifiedReview(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: QcUnqualifiedReviewVO) => {
  const _reviewIds = row?.reviewId || ids.value;
  await proxy?.$modal.confirm('是否确认删除不合格品待评审编号为"' + _reviewIds + '"的数据项？').finally(() => loading.value = false);
  await delQcUnqualifiedReview(_reviewIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('qms/qcUnqualifiedReview/export', {
    ...queryParams.value
  }, `qcUnqualifiedReview_${new Date().getTime()}.xlsx`)
}

/***** 子表 */
const selectedReviewId = ref<string | number>('');
const selectedUnqualifiedReviewNo = ref();
const qcUnqualifiedRecordList = ref<QcUnqualifiedRecordVO[]>([]);
const qcUnqualifiedRecordLoading = ref(false);
const qcUnqualifiedRecordTotal = ref(0);
const qcUnqualifiedRecordIds = ref<Array<string | number>>([]);
const qcUnqualifiedRecordSingle = ref(true);
const qcUnqualifiedRecordMultiple = ref(true);
const qcUnqualifiedRecordButtonLoading = ref(false);

const qcUnqualifiedRecordFormRef = ref<ElFormInstance>();

const qcUnqualifiedRecordDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initQcUnqualifiedRecordFormData: QcUnqualifiedRecordForm = {
  recordId: undefined,
  reviewId: undefined,
  itemCode: undefined,
  itemName: undefined,
  inspectionPosition: undefined,
  categoryId: undefined,
  categoryName: undefined,
  typeId: undefined,
  inspectionMethod: undefined,
  detectType: undefined,
  detectResult: undefined,
  detectValue: undefined,
  upperLimit: undefined,
  lowerLimit: undefined,
  specInspectionValue: undefined,
  specUpper: undefined,
  specLower: undefined,
  description: undefined
};

const qcUnqualifiedRecordData = reactive<PageData<QcUnqualifiedRecordForm, QcUnqualifiedRecordQuery>>({
  form: {...initQcUnqualifiedRecordFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    reviewId: undefined
  },
  rules: {
  }
});

const { queryParams: qcUnqualifiedRecordParams, form: qcUnqualifiedRecordForm, rules: qcUnqualifiedRecordRules } = toRefs(qcUnqualifiedRecordData);

/** 主表行点击事件 */
const handleRowClick = (row: QcUnqualifiedReviewVO) => {
  selectedReviewId.value = row.reviewId;
  selectedUnqualifiedReviewNo.value = row.unqualifiedReviewNo;
  getQcUnqualifiedRecordList();
}

/** 查询不合格品评审记录列表 */
const getQcUnqualifiedRecordList = async () => {
  qcUnqualifiedRecordLoading.value = true;
  qcUnqualifiedRecordParams.value.reviewId = selectedReviewId.value;
  const res = await listQcUnqualifiedRecord(qcUnqualifiedRecordParams.value);
  qcUnqualifiedRecordList.value = res.rows;
  qcUnqualifiedRecordTotal.value = res.total;
  qcUnqualifiedRecordLoading.value = false;
}

/** 子表多选框选中数据 */
const handleQcUnqualifiedRecordSelectionChange = (selection: QcUnqualifiedRecordVO[]) => {
  qcUnqualifiedRecordIds.value = selection.map(item => item.recordId);
  qcUnqualifiedRecordSingle.value = selection.length != 1;
  qcUnqualifiedRecordMultiple.value = !selection.length;
}

/** 子表新增按钮操作 */
const handleAddQcUnqualifiedRecord = () => {
  resetQcUnqualifiedRecord();
  qcUnqualifiedRecordDialog.visible = true;
  qcUnqualifiedRecordDialog.title = "添加不合格品评审记录";
}

/** 子表修改按钮操作 */
const handleUpdateQcUnqualifiedRecord = async (row?: QcUnqualifiedRecordVO) => {
  resetQcUnqualifiedRecord();
  const _recordId = row?.recordId || qcUnqualifiedRecordIds.value[0]
  const res = await getQcUnqualifiedRecord(_recordId);
  Object.assign(qcUnqualifiedRecordForm.value, res.data);
  qcUnqualifiedRecordDialog.visible = true;
  qcUnqualifiedRecordDialog.title = "修改不合格品评审记录";
}

/** 子表提交按钮 */
const submitQcUnqualifiedRecordForm = () => {
  qcUnqualifiedRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      qcUnqualifiedRecordButtonLoading.value = true;
      qcUnqualifiedRecordForm.value.reviewId = selectedReviewId.value;
      if (qcUnqualifiedRecordForm.value.recordId) {
        await updateQcUnqualifiedRecord(qcUnqualifiedRecordForm.value).finally(() =>  qcUnqualifiedRecordButtonLoading.value = false);
      } else {
        await addQcUnqualifiedRecord(qcUnqualifiedRecordForm.value).finally(() =>  qcUnqualifiedRecordButtonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      qcUnqualifiedRecordDialog.visible = false;
      await getQcUnqualifiedRecordList();
    }
  });
}

/** 子表删除按钮操作 */
const handleDeleteQcUnqualifiedRecord = async (row?: QcUnqualifiedRecordVO) => {
  const _recordIds = row?.recordId || qcUnqualifiedRecordIds.value;
  await proxy?.$modal.confirm('是否确认删除不合格品评审记录编号为"' + _recordIds + '"的数据项？').finally(() => {});
  await delQcUnqualifiedRecord(_recordIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getQcUnqualifiedRecordList();
}

/** 子表取消按钮 */
const cancelQcUnqualifiedRecord = () => {
  resetQcUnqualifiedRecord();
  qcUnqualifiedRecordDialog.visible = false;
}

/** 子表表单重置 */
const resetQcUnqualifiedRecord = () => {
  qcUnqualifiedRecordForm.value = {...initQcUnqualifiedRecordFormData};
  qcUnqualifiedRecordFormRef.value?.resetFields();
}

onMounted(() => {
  getList();
});

const getDispositionType = (reviewResult?: number) => {
  switch(reviewResult) {
    case 0: return '报废';
    case 1: return '返工';
    case 2: return '退货';
    case 3: return '流转';
    case 4: return '让步接收';
    default: return '未知处置类型';
  }
}

const handleReviewResult = async (reviewResult?: number) => {
  const _reviewIds = ids.value;
  const _inspectionNos = inspectionNos.value;
  const dispositionType = getDispositionType(reviewResult);
  await proxy?.$modal.confirm('是否确认' + dispositionType + '不合格品待评审编号为"' + _inspectionNos + '"的数据项？').finally(() => loading.value = false);
  await handleUnqualified(reviewResult, _reviewIds);
  proxy?.$modal.msgSuccess(dispositionType + '成功');
  await getList();
}

/** 流转按钮操作 */
const handleFlow = () => {
  handleReviewResult(3);
}

/** 报废按钮操作 */
const handleScrap = () => {
  handleReviewResult(0);
}

/** 让步接收按钮操作 */
const handleConcession = () => {
  handleReviewResult(4);
}

/** 返工按钮操作 */
const handleRework = () => {
  handleReviewResult(1);
}

/** 退货按钮操作 */
const handleReturn = () => {
  handleReviewResult(2);
}
</script>
