<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" label-width='120px'>
            <el-form-item label="模板编码" prop="templateCode">
              <el-input v-model="queryParams.templateCode" placeholder="请输入模板编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable @keyup.enter="handleQuery" />
            </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:qcInspectionTemplate:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['qms:qcInspectionTemplate:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['qms:qcInspectionTemplate:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['qms:qcInspectionTemplate:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExportTemplate" v-hasPermi="['qms:qcInspectionTemplate:export']">导出模板</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Upload" @click="handleImport" v-hasPermi="['qms:qcInspectionTemplate:add']">导入</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="qcInspectionTemplateList"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        highlight-current-row
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- 序号前端自动排序 -->
        <el-table-column label="序号" type="index" width="50" align="center" v-if="columns[0].visible"/>
        <el-table-column label="模板编码" align="center" prop="templateCode" v-if="columns[1].visible"/>
        <el-table-column label="模板名称" align="center" prop="templateName" v-if="columns[2].visible"/>
        <el-table-column label="物料编码" align="center" prop="materialCode" v-if="columns[3].visible"/>
        <el-table-column label="物料名称" align="center" prop="materialName" v-if="columns[4].visible"/>
        <el-table-column label="关联类型" align="center" prop="typeName" v-if="columns[5].visible"/>
        <el-table-column label="工位编码" align="center" prop="stationCode" v-if="columns[6].visible"/>
        <el-table-column label="工位名称" align="center" prop="stationName" v-if="columns[7].visible"/>
        <el-table-column label="工序编码" align="center" prop="processCode" v-if="columns[8].visible"/>
        <el-table-column label="工序名称" align="center" prop="processName" v-if="columns[9].visible"/>
        <el-table-column label="供应商编码" align="center" prop="supplierCode" v-if="columns[10].visible"/>
        <el-table-column label="供应商名称" align="center" prop="supplierName" v-if="columns[11].visible"/>
        <el-table-column label="模板说明" align="center" prop="description" v-if="columns[12].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:qcInspectionTemplate:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['qms:qcInspectionTemplate: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="selectedTemplateId" shadow="never" class="mt-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h3>检测模板子表 - {{ selectedTemplateName }}</h3>
          <el-button type="primary" size="small" icon="Plus" @click="handleAddTemplateItem" v-hasPermi="['qms:qcTemplateItem:add']">
            新增检测项
          </el-button>
        </div>
      </template>

      <!-- 子表搜索区域 -->
      <div class="mb-4">
        <el-form :model="templateItemQueryParams" :inline="true" label-width="100px">
          <el-form-item label="检测方式" prop="detectType">
            <el-select v-model="templateItemQueryParams.detectType" placeholder="请选择检测方式" clearable>
              <el-option v-for="dict in detect_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="控制类型" prop="controlType">
            <el-select v-model="templateItemQueryParams.controlType" placeholder="请选择控制类型" clearable>
              <el-option v-for="dict in control_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getTemplateItemList">搜索</el-button>
            <el-button icon="Refresh" @click="resetTemplateItemQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 子表数据表格 -->
      <el-table v-loading="templateItemLoading" :data="templateItemList" @selection-change="handleTemplateItemSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" 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="categoryName" />
        <el-table-column label="检测类型" align="center" prop="inspectionType" />
        <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="controlType">
          <template #default="scope">
            <dict-tag :options="control_type" :value="scope.row.controlType"/>
          </template>
        </el-table-column>
        <el-table-column label="标准值" align="center" prop="standardValue" />
        <el-table-column label="控制上限" align="center" prop="upperLimit" />
        <el-table-column label="控制下限" align="center" prop="lowerLimit" />
        <el-table-column label="规格名称" align="center" prop="specName" />
        <el-table-column label="规格上限" align="center" prop="specUpper" />
        <el-table-column label="规格下限" align="center" prop="specLower" />
        <el-table-column label="说明" align="center" prop="description" />
        <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="handleUpdateTemplateItem(scope.row)" v-hasPermi="['qms:qcTemplateItem:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDeleteTemplateItem(scope.row)" v-hasPermi="['qms:qcTemplateItem:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 添加或修改检测模板对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="qcInspectionTemplateFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="模板编码" prop="templateCode">
          <el-input v-model="form.templateCode" placeholder="请输入模板编码" />
        </el-form-item>
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请点击检索物料" @click="handleMaterialAdd" readonly>
            <template #append>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="关联检测类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择关联检测类型">
            <el-option v-for="item in qcInspectionTypeList" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="工位编码" prop="stationCode">
          <el-input v-model="form.stationCode" placeholder="请输入工位编码" />
        </el-form-item>
        <el-form-item label="工位名称" prop="stationName">
          <el-input v-model="form.stationName" placeholder="请输入工位名称" />
        </el-form-item> -->
        <el-form-item label="工位名称" prop="stationName">
          <el-select v-model="selectedStaionId" placeholder="请选择工位" filterable clearable @change="handleBaseStationInfoChange" style="width: 100%;">
            <el-option v-for="item in baseStationInfoList" :key="item.stationId" :label="item.stationName" :value="item.stationId" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="工序编码" prop="processCode">
          <el-input v-model="form.processCode" placeholder="请输入工序编码" />
        </el-form-item>
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="form.processName" placeholder="请输入工序名称" />
        </el-form-item> -->
        <el-form-item label="工序名称" prop="processName">
          <el-select v-model="selectedProcessId" placeholder="请选择工序" filterable clearable @change="handleBaseProcessInfoChange" style="width: 100%;">
            <el-option v-for="item in baseProcessInfoList" :key="item.processId" :label="item.processName" :value="item.processId" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="供应商编码" prop="supplierCode">
          <el-input v-model="form.supplierCode" placeholder="请输入供应商编码" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
        </el-form-item> -->
        <el-form-item label="供应商名称" prop="supplierName">
          <el-select v-model="selectedSupplierId" placeholder="请选择供应商" filterable clearable @change="handleBaseSupplierInfoChange" style="width: 100%;">
            <el-option v-for="item in baseSupplierInfoList" :key="item.supplierId" :label="item.supplierName" :value="item.supplierId" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板说明" prop="description">
          <el-input v-model="form.description" 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="templateItemDialog.title" v-model="templateItemDialog.visible" width="1200px" append-to-body>
      <el-form ref="templateItemFormRef" :model="templateItemForm" :rules="templateItemRules" label-width="120px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="模板编码" prop="templateCode">
              <el-input v-model="selectedTemplateCode" placeholder="模板编码" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="selectedTemplateName" placeholder="模板名称" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关联检测项定义" prop="itemId">
              <el-select v-model="templateItemForm.itemId" placeholder="请选择关联检测项定义" style="width: 100%;" @change="handleItemChange">
                <el-option v-for="item in filteredQcInspectionItemList" :key="item.itemId" :label="item.itemName" :value="item.itemId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测项编码" prop="itemCode">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input v-model="templateItemForm.itemCode" placeholder="请输入检测项编码" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="检测项名称" prop="itemName">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input v-model="templateItemForm.itemName" placeholder="请输入检测项名称" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测方式" prop="detectType">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-select v-model="templateItemForm.detectType" placeholder="请选择检测方式" style="width: 100%;" :disabled="true">
                  <el-option v-for="dict in detect_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="控制类型" prop="controlType">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-select v-model="templateItemForm.controlType" placeholder="请选择控制类型" style="width: 100%;" :disabled="true">
                  <el-option v-for="dict in control_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测项类别" prop="categoryName">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-select v-model="templateItemForm.categoryName" placeholder="请选择检测项类别" style="width: 100%;" :disabled="true">
                  <el-option v-for="item in qcInspectionItemCategoryList" :key="item.categoryId" :label="item.categoryName" :value="item.categoryName" />
                </el-select>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="检测类型" prop="inspectionType">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input v-model="templateItemForm.inspectionType" placeholder="请输入检测类型" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测位置" prop="inspectionPosition">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input v-model="templateItemForm.inspectionPosition" placeholder="请输入检测位置" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准值" prop="standardValue" v-if="templateItemForm.detectType === 1">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input-number v-model="templateItemForm.standardValue" placeholder="请输入标准值" style="width: 100%;" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="控制上限" prop="upperLimit" v-if="templateItemForm.detectType === 1">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input-number v-model="templateItemForm.upperLimit" placeholder="请输入控制上限" style="width: 100%;" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="templateItemForm.detectType === 1">
          <el-col :span="6">
            <el-form-item label="控制下限" prop="lowerLimit">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input-number v-model="templateItemForm.lowerLimit" placeholder="请输入控制下限" style="width: 100%;" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格名称" prop="specName">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input v-model="templateItemForm.specName" placeholder="请输入规格名称" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格上限" prop="specUpper">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input-number v-model="templateItemForm.specUpper" placeholder="请输入规格上限" style="width: 100%;" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格下限" prop="specLower">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input-number v-model="templateItemForm.specLower" placeholder="请输入规格下限" style="width: 100%;" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="检测项说明" prop="description">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input type="textarea" v-model="templateItemForm.description" placeholder="请输入检测项说明" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="templateItemButtonLoading" type="primary" @click="submitTemplateItemForm">确 定</el-button>
          <el-button @click="cancelTemplateItem">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 添加物料信息对话框 -->
    <el-dialog title='选择物料信息' v-model='materialOpen' width='1200px' append-to-body>
      <MaterialSelect ref='materialSelectRef' v-if='materialOpen'></MaterialSelect>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='submitMaterialForm'>确 定</el-button>
        <el-button @click='materialOpen = false'>取 消</el-button>
      </div>
    </el-dialog>

    <input ref="fileInput" type="file" accept=".xlsx, .xls" style="display: none" @change="onFileChange" />
  </div>
</template>

<script setup name="QcInspectionTemplate" lang="ts">
import { listQcInspectionTemplate, getQcInspectionTemplate, delQcInspectionTemplate, addQcInspectionTemplate, updateQcInspectionTemplate, getQcInspectionTemplateList, importData } from '@/api/qms/qcInspectionTemplate';
import { QcInspectionTemplateVO, QcInspectionTemplateQuery, QcInspectionTemplateForm } from '@/api/qms/qcInspectionTemplate/types';
import { listQcTemplateItem, getQcTemplateItem, delQcTemplateItem, addQcTemplateItem, updateQcTemplateItem } from '@/api/qms/qcTemplateItem';
import { QcTemplateItemVO, QcTemplateItemQuery, QcTemplateItemForm } from '@/api/qms/qcTemplateItem/types';
import { getQcInspectionTypeList } from '@/api/qms/qcInspectionType';
import { QcInspectionTypeVO } from '@/api/qms/qcInspectionType/types';
import { listQcInspectionItem, getQcInspectionItem, delQcInspectionItem, addQcInspectionItem, updateQcInspectionItem, getQcInspectionItemList } from '@/api/qms/qcInspectionItem';
import { getBaseMaterialInfoList } from '@/api/qms/baseMaterialInfo';
import { getStationInfoList } from '@/api/qms/baseStationInfo';
import { getProcessInfoList } from '@/api/qms/baseProcessInfo';
import { getBaseSupplierInfoList } from '@/api/qms/baseSupplierInfo';
import { getQcInspectionItemCategoryList } from '@/api/qms/qcInspectionItemCategory';

import MaterialSelect from "@/views/mes/baseMaterialInfo/addMaterialInQMS.vue";
import { computed } from 'vue';


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

const qcInspectionTemplateList = ref<QcInspectionTemplateVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 子表相关状态
const selectedTemplateId = ref<string | number | null>(null);
const selectedTemplateName = ref<string>('');
const selectedTemplateCode = ref<string>('');
const templateItemList = ref<QcTemplateItemVO[]>([]);
const templateItemLoading = ref(false);
const templateItemTotal = ref(0);
const templateItemIds = ref<Array<string | number>>([]);
const templateItemSingle = ref(true);
const templateItemMultiple = ref(true);
const templateItemButtonLoading = ref(false);

const selectedMaterialId = ref(null);
const selectedProcessId = ref(null);
const selectedStaionId = ref(null);
const selectedSupplierId = ref(null);
// 修改 selectedTypeId 的类型
const selectedTypeId = ref<string | number | null>(null);

const queryFormRef = ref<ElFormInstance>();
const qcInspectionTemplateFormRef = ref<ElFormInstance>();
const templateItemFormRef = ref<ElFormInstance>();

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

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

// 列显隐信息
const columns = ref<FieldOption[]>([
        { key: 0, label: `序号`, visible: true },
        { key: 1, label: `模板编码`, visible: true },
        { key: 2, label: `模板名称`, visible: true },
        { key: 3, label: `物料编码`, visible: true },
        { key: 4, label: `物料名称`, visible: true },
        { key: 5, label: `关联检测类型表`, visible: true },
        { key: 6, label: `工位编码`, visible: true },
        { key: 7, label: `工位名称`, visible: true },
        { key: 8, label: `工序编码`, visible: true },
        { key: 9, label: `工序名称`, visible: true },
        { key: 10, label: `供应商编码`, visible: true },
        { key: 11, label: `供应商名称`, visible: true },
        { key: 12, label: `模板说明`, visible: true },
]);

const initFormData: QcInspectionTemplateForm = {
  templateId: undefined,
  templateCode: undefined,
  templateName: undefined,
  materialCode: undefined,
  materialName: undefined,
  typeId: undefined,
  stationCode: undefined,
  stationName: undefined,
  processCode: undefined,
  processName: undefined,
  supplierCode: undefined,
  supplierName: undefined,
  description: undefined,
}

const initTemplateItemFormData: QcTemplateItemForm = {
  templateItemId: undefined,
  templateId: undefined,
  itemId: undefined,
  itemCode: undefined,
  itemName: undefined,
  inspectionPosition: undefined,
  categoryName: undefined,
  inspectionType: undefined,
  detectType: undefined,
  controlType: undefined,
  standardValue: undefined,
  upperLimit: undefined,
  lowerLimit: undefined,
  specName: undefined,
  specUpper: undefined,
  specLower: undefined,
  description: undefined,
}

const data = reactive<PageData<QcInspectionTemplateForm, QcInspectionTemplateQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateId: undefined,
    templateCode: undefined,
    templateName: undefined,
    materialCode: undefined,
    materialName: undefined,
    typeId: undefined,
    stationCode: undefined,
    stationName: undefined,
    processCode: undefined,
    processName: undefined,
    supplierCode: undefined,
    supplierName: undefined,
    description: undefined,
    params: {
    }
  },
  rules: {
    // templateId: [
    //   { required: true, message: "模板主键不能为空", trigger: "blur" }
    // ],
    templateCode: [
      { required: true, message: "模板编码不能为空", trigger: "blur" }
    ],
    templateName: [
      { required: true, message: "模板名称不能为空", trigger: "blur" }
    ],
  }
});

// 子表数据
const templateItemForm = ref<QcTemplateItemForm>({...initTemplateItemFormData});
const templateItemQueryParams = ref<QcTemplateItemQuery>({
  pageNum: 1,
  pageSize: 10,
  templateItemId: undefined,
  templateId: undefined,
  itemId: undefined,
  itemCode: undefined,
  itemName: undefined,
  inspectionPosition: undefined,
  categoryName: undefined,
  inspectionType: undefined,
  detectType: undefined,
  controlType: undefined,
  standardValue: undefined,
  upperLimit: undefined,
  lowerLimit: undefined,
  specName: undefined,
  specUpper: undefined,
  specLower: undefined,
  description: undefined,
  params: {}
});

const templateItemRules = ref({
  // templateId: [
  //   { required: true, message: "关联模板主表ID不能为空", trigger: "blur" }
  // ],
  itemCode: [
    { required: true, message: "检测项编码不能为空", trigger: "blur" }
  ],
  itemName: [
    { required: true, message: "检测项名称不能为空", trigger: "blur" }
  ],
});

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

/** 查询检测模板主列表 */
const getList = async () => {
  loading.value = true;
  const res = await listQcInspectionTemplate(queryParams.value);
  qcInspectionTemplateList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 查询检测模板子表列表 */
const getTemplateItemList = async () => {
  if (!selectedTemplateId.value) return;

  templateItemLoading.value = true;
  // 设置templateId过滤条件
  templateItemQueryParams.value.templateId = selectedTemplateId.value;
  const res = await listQcTemplateItem(templateItemQueryParams.value);
  templateItemList.value = res.rows;
  templateItemTotal.value = res.total;
  templateItemLoading.value = false;
}

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

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  qcInspectionTemplateFormRef.value?.resetFields();
  selectedMaterialId.value = null;
  selectedStaionId.value = null;
  selectedProcessId.value = null;
  selectedSupplierId.value = null;
}

/** 子表取消按钮 */
const cancelTemplateItem = () => {
  resetTemplateItem();
  templateItemDialog.visible = false;
}

/** 子表表单重置 */
const resetTemplateItem = () => {
  templateItemForm.value = {...initTemplateItemFormData};
  templateItemFormRef.value?.resetFields();
}

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

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

/** 重置子表搜索 */
const resetTemplateItemQuery = () => {
  templateItemQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    templateItemId: undefined,
    templateId: selectedTemplateId.value,
    itemId: undefined,
    itemCode: undefined,
    itemName: undefined,
    inspectionPosition: undefined,
    categoryName: undefined,
    inspectionType: undefined,
    detectType: undefined,
    controlType: undefined,
    standardValue: undefined,
    upperLimit: undefined,
    lowerLimit: undefined,
    specName: undefined,
    specUpper: undefined,
    specLower: undefined,
    description: undefined,
    params: {}
  };
  getTemplateItemList();
}

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

/** 子表多选框选中数据 */
const handleTemplateItemSelectionChange = (selection: QcTemplateItemVO[]) => {
  templateItemIds.value = selection.map(item => item.templateItemId);
  templateItemSingle.value = selection.length != 1;
  templateItemMultiple.value = !selection.length;
}

/** 行点击事件 */
const handleRowClick = (row: QcInspectionTemplateVO) => {
  selectedTemplateId.value = row.templateId;
  selectedTemplateName.value = row.templateName || '';
  selectedTemplateCode.value = row.templateCode || '';
  selectedTypeId.value = row.typeId; // 新增
  // 刷新子表数据
  nextTick(() => {
    getTemplateItemList();
  });
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // getMaterialList();
  getBaseProcessList();
  getBaseStationList();
  getBaseSupplierList();
  dialog.visible = true;
  dialog.title = "添加检测模板";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: QcInspectionTemplateVO) => {
  reset();
  // await getMaterialList();
  await getBaseProcessList();
  await getBaseStationList();
  await getBaseSupplierList();
  const _templateId = row?.templateId || ids.value[0]
  const res = await getQcInspectionTemplate(_templateId);
  Object.assign(form.value, res.data);
  // 设置materialId
  if (form.value.materialCode) {
    const matched = materialList.value.find(item => item.materialCode === form.value.materialCode);
    if (matched) {
      selectedMaterialId.value = matched.materialId;
    }
  }
  // 设置stationId
  if (form.value.stationCode) {
    const matched = baseStationInfoList.value.find(item => item.stationCode === form.value.stationCode);
    if (matched) {
      selectedStaionId.value = matched.stationId;
    }
  }
  // 设置processId
  if (form.value.processCode) {
    const matched = baseProcessInfoList.value.find(item => item.processCode === form.value.processCode);
    if (matched) {
      selectedProcessId.value = matched.processId;
    }
  }
  // 设置supplierId
  if (form.value.supplierCode) {
    const matched = baseSupplierInfoList.value.find(item => item.supplierCode === form.value.supplierCode);
    if (matched) {
      selectedSupplierId.value = matched.supplierId;
    }
  }
  dialog.visible = true;
  dialog.title = "修改检测模板";
}

/** 新增检测项 */
const handleAddTemplateItem = () => {
  resetTemplateItem();
  templateItemForm.value.templateId = selectedTemplateId.value;
  templateItemDialog.visible = true;
  templateItemDialog.title = "添加检测项";
}

/** 修改检测项 */
const handleUpdateTemplateItem = async (row?: QcTemplateItemVO) => {
  resetTemplateItem();
  const _templateItemId = row?.templateItemId || templateItemIds.value[0];
  const res = await getQcTemplateItem(_templateItemId);
  Object.assign(templateItemForm.value, res.data);
  handleItemChange(templateItemForm.value.itemId);
  templateItemDialog.visible = true;
  templateItemDialog.title = "修改检测项";
}

/** 删除检测项 */
const handleDeleteTemplateItem = async (row?: QcTemplateItemVO) => {
  const _templateItemIds = row?.templateItemId || templateItemIds.value;
  await proxy?.$modal.confirm('是否确认删除检测项编号为"' + _templateItemIds + '"的数据项？').finally(() => templateItemLoading.value = false);
  await delQcTemplateItem(_templateItemIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getTemplateItemList();
}

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

/** 子表提交按钮 */
const submitTemplateItemForm = () => {
  templateItemFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      templateItemButtonLoading.value = true;
      if (templateItemForm.value.templateItemId) {
        await updateQcTemplateItem(templateItemForm.value).finally(() => templateItemButtonLoading.value = false);
      } else {
        await addQcTemplateItem(templateItemForm.value).finally(() => templateItemButtonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      templateItemDialog.visible = false;
      await getTemplateItemList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: QcInspectionTemplateVO) => {
  const _templateIds = row?.templateId || ids.value;
  await proxy?.$modal.confirm('是否确认删除检测模板主编号为"' + _templateIds + '"的数据项？').finally(() => loading.value = false);
  await delQcInspectionTemplate(_templateIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

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

/** 导出模板按钮操作 */
const handleExportTemplate = () => {
  proxy?.download('qms/qcInspectionTemplate/exportTemplate', {

  }, `qcInspectionTemplate_template_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
const fileInput = ref<HTMLInputElement>();
const uploading = ref(false);
const handleImport = () => {
  fileInput.value?.click();
}
const onFileChange = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    const file = input.files[0];
    uploading.value = true;
    try {
      await importData(file, true);
      proxy?.$modal.msgSuccess("导入成功");
      await getList();
    } catch (err) {
      proxy?.$modal.msgError("导入失败");
      console.error(err);
    } finally {
      uploading.value = false;
      input.value = '';
    }
  }
}

/** 查询检测项类别列表 */
let qcInspectionItemCategoryList = ref([]);
const getCategoryList = async () => {
  const res = await getQcInspectionItemCategoryList(null);
  qcInspectionItemCategoryList.value = res.data;
};


/** 物料名称选择变化 */
const handleMaterialChange = (value) => {
  const selected = materialList.value.find(item => item.materialId === value);
  if (selected) {
    form.value.materialName = selected.materialName;
    form.value.materialCode = selected.materialCode;
  } else {
    form.value.materialName = '';
    form.value.materialCode = '';
  }
}

/* 工位名称选择变化 */
const handleBaseStationInfoChange = (value) => {
  const selected = baseStationInfoList.value.find(item => item.stationId === value);
  if (selected) {
    form.value.stationName = selected.stationName;
    form.value.stationCode = selected.stationCode;
  } else {
    form.value.stationName = '';
    form.value.stationCode = '';
  }
}

/*工序名称选择变化 */
const handleBaseProcessInfoChange = (value) => {
  const selected = baseProcessInfoList.value.find(item => item.processId === value);
  if (selected) {
    form.value.processName = selected.processName;
    form.value.processCode = selected.processCode;
  } else {
    form.value.processName = '';
    form.value.processCode = '';
  }
}

/** 供应商名称选择变化 */
const handleBaseSupplierInfoChange = (value) => {
  const selected = baseSupplierInfoList.value.find(item => item.supplierId === value);
  if (selected) {
    form.value.supplierName = selected.supplierName;
    form.value.supplierCode = selected.supplierCode;
  } else {
    form.value.supplierName = '';
    form.value.supplierCode = '';
  }
}

/** 关联检测项定义选择变化 */
const handleItemChange = (value) => {
  const selected = qcInspectionItemList.value.find(item => item.itemId === value);
  if (selected) {
    templateItemForm.value.itemCode = selected.itemCode;
    templateItemForm.value.itemName = selected.itemName;
    templateItemForm.value.detectType = selected.detectType;
    templateItemForm.value.controlType = selected.controlType;
    templateItemForm.value.categoryName = selected.categoryName || '';
    templateItemForm.value.inspectionType = selected.inspectionType;
    templateItemForm.value.inspectionPosition = selected.inspectionPosition;
    templateItemForm.value.standardValue = selected.standardValue;
    templateItemForm.value.upperLimit = selected.upperLimit;
    templateItemForm.value.lowerLimit = selected.lowerLimit;
    templateItemForm.value.specName = selected.specName;
    templateItemForm.value.specUpper = selected.specUpper;
    templateItemForm.value.specLower = selected.specLower;
    templateItemForm.value.description = selected.description;
  } else {
    // Optionally reset fields
  }
}


//获取检测类型列表（不分页，获取全部）
let qcInspectionTypeList = ref([]);
const getInspectionTypeList = async () => {
  const res = await getQcInspectionTypeList(null);
  qcInspectionTypeList.value = res.data;
}

//获取检测项列表（不分页，获取全部）
let qcInspectionItemList = ref([]);
const getInspectionItemList = async () => {
  const res = await getQcInspectionItemList(null);
  qcInspectionItemList.value = res.data;
}


// 获取物料列表（不分页，获取全部）
let materialList = ref([]);
const getMaterialList = async () => {
  const res = await getBaseMaterialInfoList(null);
  materialList.value = res.data;
}

// 获取工序列表（不分页，获取全部）
let baseProcessInfoList = ref([]);
const getBaseProcessList = async () => {
  const res = await getProcessInfoList(null);
  baseProcessInfoList.value = res.data;
}



// 获取工位列表（不分页，获取全部）
let baseStationInfoList = ref([]);
const getBaseStationList = async () => {
  const res = await getStationInfoList(null);
  baseStationInfoList.value = res.data;
}

// 获取供应商列表（不分页，获取全部）
let baseSupplierInfoList = ref([]);
const getBaseSupplierList = async () => {
  const res = await getBaseSupplierInfoList(null);
  baseSupplierInfoList.value = res.data;
}

/** 物料选择弹窗 */
const materialOpen = ref(false);
const materialSelectRef = ref();
const handleMaterialAdd = () => {
  materialOpen.value = true;
};
const submitMaterialForm = () => {
  const selected = materialSelectRef.value.tableRef.store.states.currentRow.value;
  if (selected) {
    selectedMaterialId.value = selected.materialId;
    form.value.materialName = selected.materialName;
    form.value.materialCode = selected.materialCode;
  }
  materialOpen.value = false;
};

// 添加 computed
const filteredQcInspectionItemList = computed(() => {
  if (selectedTypeId.value === null) return [];
  return qcInspectionItemList.value.filter(item => item.inspectionType === Number(selectedTypeId.value));
});


onMounted(() => {
  getList();
  getInspectionTypeList();
  getInspectionItemList();
  getCategoryList();
});
</script>
