<template>
  <div class="app-container">
    <div style="margin-bottom: 16px;">
      <div style="display: flex; align-items: center; margin-bottom: 6px;">
        <span
          style="font-size: 13px; color: #909399; white-space: nowrap; margin-right: 12px; width: 68px; text-align: right;">所属单位：</span>
        <el-radio-group v-model="selectedCompany" @change="handleCompanyChange" size="small">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button v-for="company in companyOptions" :key="company" :label="company">{{ company }}</el-radio-button>
        </el-radio-group>
      </div>
      <div v-if="selectedCompany" style="display: flex; align-items: center;">
        <span
          style="font-size: 13px; color: #909399; white-space: nowrap; margin-right: 12px; width: 68px; text-align: right;">方案名称：</span>
        <el-radio-group v-model="selectedScheme" @change="handleSchemeChange" size="small">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button v-for="scheme in schemeOptions" :key="scheme" :label="scheme">{{ scheme }}</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <el-form :model="taskQueryParams" ref="taskQueryForm" size="small" :inline="true" v-show="showSearch"
      label-width="68px">
      <el-form-item label="任务编号" prop="taskCode">
        <el-input v-model="taskQueryParams.taskCode" placeholder="请输入任务编号" clearable
          @keyup.enter.native="handleTaskQuery" />
      </el-form-item>
      <el-form-item label="任务类型" prop="taskType">
        <el-select v-model="taskQueryParams.taskType" placeholder="请选择任务类型" clearable filterable allow-create>
          <el-option label="内控检验" value="内控检验" />
          <el-option label="产品检验" value="产品检验" />
        </el-select>
      </el-form-item>
      <el-form-item label="检验人" prop="inspectUser">
        <el-input v-model="taskQueryParams.inspectUser" placeholder="请输入检验人" clearable
          @keyup.enter.native="handleTaskQuery" />
      </el-form-item>
      <el-form-item label="审核人" prop="auditUser">
        <el-input v-model="taskQueryParams.auditUser" placeholder="请输入审核人" clearable
          @keyup.enter.native="handleTaskQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleTaskQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetTaskQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="!readonly">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleTaskAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="!readonly">
        <el-button type="primary" plain icon="el-icon-circle-plus-outline" size="mini"
          @click="handleQuickCreate">快捷创建</el-button>
      </el-col>
      <el-col :span="1.5" v-if="!readonly">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="taskSingle"
          @click="handleTaskUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5" v-if="!readonly">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="taskMultiple"
          @click="handleTaskDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5" v-if="!readonly">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleTaskExport">导出</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getTaskList"></right-toolbar>
    </el-row>

    <el-table v-loading="taskLoading" :data="inspectionTaskList" @selection-change="handleTaskSelectionChange"
      highlight-current-row @row-click="handleRowClick">
      <el-table-column type="selection" width="55" align="center" v-if="!readonly" />
      <el-table-column label="任务ID" align="center" prop="taskId" v-if="false" />
      <el-table-column label="任务编号" align="center" prop="taskCode" />
      <el-table-column label="任务类型" align="center" prop="taskType" />
      <el-table-column label="所属单位" align="center" prop="belongCompany" />
      <el-table-column label="方案名称" align="center" prop="schemeName" />
      <el-table-column label="状态" align="center" prop="status" width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0 || scope.row.status === '0'" type="info" size="small">待检验</el-tag>
          <el-tag v-else-if="scope.row.status === 1 || scope.row.status === '1'" type="warning"
            size="small">已检验</el-tag>
          <el-tag v-else-if="scope.row.status === 2 || scope.row.status === '2'" type="success"
            size="small">已审核</el-tag>
          <span v-else>{{ scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检验情况" align="center" prop="inspectTime" width="180">
        <template slot-scope="scope">
          <div v-if="scope.row.inspectUser">检验人：{{ scope.row.inspectUser }}</div>
          <div>{{ parseTime(scope.row.inspectTime, '{y}-{m}-{d}') }}</div>
        </template>
      </el-table-column>
      <el-table-column label="审核情况" align="center" prop="auditTime" width="160">
        <template slot-scope="scope">
          <div v-if="scope.row.auditUser">审核人：{{ scope.row.auditUser }}</div>
          <div>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d}') }}</div>
        </template>
      </el-table-column>
      <el-table-column label="最终结果" align="center" prop="result" />
      <el-table-column label="关联钢卷" align="center" width="140">
        <template slot-scope="scope">
          <div v-if="scope.row.coilList && scope.row.coilList.length > 0"
            style="display: flex; flex-wrap: wrap; gap: 4px;">
            <div v-for="(coil, index) in scope.row.coilList" :key="coil.coilId || index">
              <CurrentCoilNo :currentCoilNo="coil.currentCoilNo || coil.coilNo || ''" />
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button v-if="!readonly" size="mini" type="text" icon="el-icon-edit"
            @click="handleTaskUpdate(scope.row)">修改</el-button>
          <el-button v-if="!readonly" size="mini" type="text" icon="el-icon-delete"
            @click="handleTaskDelete(scope.row)">删除</el-button>
          <div>
            <el-button v-if="scope.row.status === '0' || scope.row.status === 0" size="mini" type="text"
              icon="el-icon-check" @click="handleInspect(scope.row)" style="color: #67c23a;">检验</el-button>
            <el-button v-if="scope.row.status === '1' || scope.row.status === 1" size="mini" type="text"
              icon="el-icon-s-flag" @click="handleAudit(scope.row)" style="color: #409eff;">审核</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="taskTotal > 0" :total="taskTotal" :page.sync="taskQueryParams.pageNum"
      :limit.sync="taskQueryParams.pageSize" @pagination="getTaskList" />

    <div v-if="currentTask"
      style="margin: 16px 0; padding: 10px 16px; background: #f0f9eb; border-left: 4px solid #67c23a; border-radius: 4px; font-size: 14px;">
      <span>当前选中任务：<strong>{{ currentTask.taskCode }}</strong> - {{ currentTask.schemeName }}</span>
    </div>

    <div v-if="currentTask">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5" v-if="!itemReadonly">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleItemAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5" v-if="!itemReadonly">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="itemSingle"
            @click="handleItemUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5" v-if="!itemReadonly">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="itemMultiple"
            @click="handleItemDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5" v-if="!itemReadonly">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleItemExport">导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getItemList"></right-toolbar>
      </el-row>

      <el-table v-loading="itemLoading" :data="inspectionItemList" @selection-change="handleItemSelectionChange" border>
        <el-table-column type="selection" width="45" align="center" v-if="!itemReadonly" />
        <el-table-column label="明细ID" align="center" prop="itemId" v-if="false" />
        <el-table-column label="检验项目名称" align="center" prop="itemName" min-width="100" />
        <el-table-column label="标准值" align="center" prop="standardValue" width="80">
          <template slot-scope="scope">
            <span v-if="itemReadonly">{{ scope.row.standardValue }}</span>
            <el-input v-else v-model="scope.row.standardValue" size="mini" />
          </template>
        </el-table-column>
        <el-table-column label="上限" align="center" prop="upperLimit" width="80">
          <template slot-scope="scope">
            <span v-if="itemReadonly">{{ scope.row.upperLimit }}</span>
            <el-input v-else v-model="scope.row.upperLimit" size="mini" />
          </template>
        </el-table-column>
        <el-table-column label="下限" align="center" prop="lowerLimit" width="80">
          <template slot-scope="scope">
            <span v-if="itemReadonly">{{ scope.row.lowerLimit }}</span>
            <el-input v-else v-model="scope.row.lowerLimit" size="mini" />
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="unit" width="60">
          <template slot-scope="scope">
            <span v-if="itemReadonly">{{ scope.row.unit }}</span>
            <el-input v-else v-model="scope.row.unit" size="mini" />
          </template>
        </el-table-column>
        <el-table-column label="定性/定量" align="center" prop="itemType" width="80" />
        <el-table-column label="检验值" align="center" prop="inspectValue" width="100">
          <template slot-scope="scope">
            <span v-if="itemReadonly">{{ scope.row.inspectValue }}</span>
            <el-input v-else v-model="scope.row.inspectValue" size="mini" />
          </template>
        </el-table-column>
        <el-table-column label="是否合格" align="center" prop="isQualified" width="90">
          <template slot-scope="scope">
            <span v-if="itemReadonly">{{ scope.row.isQualified }}</span>
            <el-select v-else v-model="scope.row.isQualified" size="mini" style="width: 100%;">
              <el-option label="合格" :value="1" />
              <el-option label="不合格" :value="0" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="判定结果" align="center" prop="judgeResult" width="100">
          <template slot-scope="scope">
            <span v-if="itemReadonly">{{ scope.row.judgeResult }}</span>
            <el-input v-else v-model="scope.row.judgeResult" size="mini" />
          </template>
        </el-table-column>
        <el-table-column label="检验人" align="center" prop="inspectUser" width="80">
          <template slot-scope="scope">
            <span v-if="itemReadonly">{{ scope.row.inspectUser }}</span>
            <el-input v-else v-model="scope.row.inspectUser" size="mini" />
          </template>
        </el-table-column>
        <el-table-column label="检验时间" align="center" prop="inspectTime" width="170">
          <template slot-scope="scope">
            <span v-if="itemReadonly">{{ parseTime(scope.row.inspectTime, '{y}-{m}-{d}') }}</span>
            <el-date-picker v-else v-model="scope.row.inspectTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              size="mini" style="width: 100%;" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="100">
          <template slot-scope="scope">
            <span v-if="itemReadonly">{{ scope.row.remark }}</span>
            <el-input v-else v-model="scope.row.remark" size="mini" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="130" fixed="right" v-if="!itemReadonly">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleItemSave(scope.row)">保存</el-button>
            <el-button type="danger" size="mini" @click="handleItemDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="itemTotal > 0" :total="itemTotal" :page.sync="itemQueryParams.pageNum"
        :limit.sync="itemQueryParams.pageSize" @pagination="getItemList" />
    </div>
    <div v-else style="text-align: center; padding: 40px 0; color: #999; font-size: 14px;">
      <i class="el-icon-inbox" style="font-size: 48px; display: block; margin-bottom: 12px; color: #ddd;"></i>
      请先在上方选择一个检验任务
    </div>

    <el-dialog :title="taskTitle" :visible.sync="taskOpen" width="500px" append-to-body>
      <el-form ref="taskForm" :model="taskForm" :rules="taskRules" label-width="80px">
        <el-form-item label="任务编号" prop="taskCode">
          <el-input v-model="taskForm.taskCode" placeholder="请输入任务编号" />
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-select v-model="taskForm.taskType" placeholder="请选择任务类型" clearable filterable allow-create>
            <el-option label="内控检验" value="内控检验" />
            <el-option label="产品检验" value="产品检验" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属单位" prop="belongCompany">
          <el-input v-model="taskForm.belongCompany" placeholder="请输入所属单位" />
        </el-form-item>
        <el-form-item label="方案名称" prop="schemeName">
          <el-input v-model="taskForm.schemeName" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="最终结果" prop="result">
          <el-input v-model="taskForm.result" placeholder="请输入最终结果" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="taskForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div style="margin: 0 0 12px 80px;">
        <CoilSelector use-trigger multiple @confirm="handleTaskCoilConfirm">
          <el-button type="primary" plain icon="el-icon-plus" size="small">选择钢卷</el-button>
        </CoilSelector>
        <span v-if="taskCoilList.length > 0" style="margin-left: 8px; font-size: 13px; color: #67c23a;">
          已选 {{ taskCoilList.length }} 卷
        </span>
        <el-button v-if="taskCoilList.length > 0" type="text" size="small" style="margin-left: 4px; color: #f56c6c;"
          @click="taskCoilList = []">清除</el-button>
      </div>
      <div v-if="taskCoilList.length > 0" style="display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 12px 80px;">
        <div v-for="(coil, index) in taskCoilList" :key="coil.coilId || index"
          style="display: flex; align-items: center; gap: 4px;">
          <CurrentCoilNo :currentCoilNo="coil.currentCoilNo || coil.coilNo || ''" />
          <el-button type="text" icon="el-icon-close" size="mini" @click="taskCoilList.splice(index, 1)"></el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitTaskForm">确 定</el-button>
        <el-button @click="cancelTask">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="itemTitle" :visible.sync="itemOpen" width="500px" append-to-body>
      <el-form ref="itemForm" :model="itemForm" :rules="itemRules" label-width="80px">
        <el-form-item label="检验项目名称" prop="itemName">
          <el-input v-model="itemForm.itemName" placeholder="请输入检验项目名称" />
        </el-form-item>
        <el-form-item label="标准值" prop="standardValue">
          <el-input v-model="itemForm.standardValue" placeholder="请输入标准值" />
        </el-form-item>
        <el-form-item label="上限" prop="upperLimit">
          <el-input v-model="itemForm.upperLimit" placeholder="请输入上限" />
        </el-form-item>
        <el-form-item label="下限" prop="lowerLimit">
          <el-input v-model="itemForm.lowerLimit" placeholder="请输入下限" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="itemForm.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="检验值" prop="inspectValue">
          <el-input v-model="itemForm.inspectValue" placeholder="请输入检验值" />
        </el-form-item>
        <el-form-item label="是否合格" prop="isQualified">
          <el-input v-model="itemForm.isQualified" placeholder="请输入是否合格" />
        </el-form-item>
        <el-form-item label="判定结果" prop="judgeResult">
          <el-input v-model="itemForm.judgeResult" placeholder="请输入判定结果" />
        </el-form-item>
        <el-form-item label="检验人" prop="inspectUser">
          <el-input v-model="itemForm.inspectUser" placeholder="请输入检验人" />
        </el-form-item>
        <el-form-item label="检验时间" prop="inspectTime">
          <el-date-picker clearable v-model="itemForm.inspectTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择检验时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="itemForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitItemForm">确 定</el-button>
        <el-button @click="cancelItem">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="resultTitle" :visible.sync="resultOpen" width="400px" append-to-body>
      <el-form ref="resultForm" :model="resultForm" label-width="80px" size="small">
        <el-form-item label="最终结果" prop="result">
          <el-input v-model="resultForm.result" type="textarea" :rows="3" placeholder="请输入最终结果" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="resultLoading" type="primary" @click="submitResult">确 定</el-button>
        <el-button @click="resultOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <SchemeSelect :visible.sync="schemeVisible" @confirm="handleSchemeConfirm" />
  </div>
</template>

<script>
import { listInspectionTask, getInspectionTask, delInspectionTask, addInspectionTask, updateInspectionTask, addInspectionTaskWithItems } from "@/api/mes/qc/inspectionTask";
import { listInspectionItem, getInspectionItem, delInspectionItem, addInspectionItem, updateInspectionItem } from "@/api/mes/qc/inspectionItem";
import { listInspectionItemTemplate } from "@/api/mes/qc/inspectionItemTemplate";
import { SchemeSelect } from "@/components/KLPService";
import CoilSelector from "@/components/CoilSelector/index.vue";
import CurrentCoilNo from "@/components/KLPService/Renderer/CurrentCoilNo.vue";
import { listCoilByIds } from "@/api/wms/coil";

export default {
  name: "InspectionTask",
  props: {
    readonly: {
      type: Boolean,
      default: false
    }
  },
  components: {
    SchemeSelect,
    CoilSelector,
    CurrentCoilNo
  },
  data() {
    return {
      buttonLoading: false,
      showSearch: true,

      taskLoading: true,
      taskIds: [],
      taskSingle: true,
      taskMultiple: true,
      taskTotal: 0,
      inspectionTaskList: [],
      taskTitle: "",
      taskOpen: false,
      taskQueryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: undefined,
        taskType: undefined,
        belongCompany: undefined,
        schemeName: undefined,
        status: undefined,
        inspectUser: undefined,
        inspectTime: undefined,
        auditUser: undefined,
        auditTime: undefined,
        result: undefined,
      },
      taskForm: {},
      taskRules: {},

      itemLoading: false,
      itemIds: [],
      itemSingle: true,
      itemMultiple: true,
      itemTotal: 0,
      inspectionItemList: [],
      itemTitle: "",
      itemOpen: false,
      itemQueryParams: {
        pageNum: 1,
        pageSize: 10,
        itemName: undefined,
        standardValue: undefined,
        upperLimit: undefined,
        lowerLimit: undefined,
        unit: undefined,
        itemType: undefined,
        inspectValue: undefined,
        isQualified: undefined,
        judgeResult: undefined,
        inspectUser: undefined,
        inspectTime: undefined,
      },
      itemForm: {},
      itemRules: {},

      currentTask: null,
      schemeVisible: false,
      taskCoilList: [],
      resultOpen: false,
      resultLoading: false,
      resultTitle: "",
      resultForm: { result: undefined },
      resultAction: null,
      resultTaskRow: null,
      cascadeData: {},
      companyOptions: [],
      schemeOptions: [],
      selectedCompany: '',
      selectedScheme: '',
    };
  },
  computed: {
    itemReadonly() {
      if (!this.readonly) return false;
      const status = this.currentTask?.status;
      return !(status === 0 || status === '0');
    }
  },
  created() {
    this.getTaskList();
    this.loadCascadeData();
  },
  methods: {
    getTaskList() {
      this.taskLoading = true;
      listInspectionTask(this.taskQueryParams).then(response => {
        this.inspectionTaskList = response.rows;
        this.taskTotal = response.total;
        this.taskLoading = false;
      });
    },
    getItemList() {
      if (!this.currentTask) return;
      this.itemLoading = true;
      const params = { ...this.itemQueryParams, taskId: this.currentTask.taskId };
      listInspectionItem(params).then(response => {
        this.inspectionItemList = response.rows;
        this.itemTotal = response.total;
        this.itemLoading = false;
      });
    },

    handleRowClick(row) {
      this.currentTask = row;
      this.itemQueryParams.pageNum = 1;
      this.getItemList();
    },

    handleTaskQuery() {
      this.taskQueryParams.pageNum = 1;
      this.getTaskList();
    },
    resetTaskQuery() {
      this.resetForm("taskQueryForm");
      this.selectedCompany = '';
      this.selectedScheme = '';
      this.schemeOptions = [];
      this.handleTaskQuery();
    },
    handleTaskSelectionChange(selection) {
      this.taskIds = selection.map(item => item.taskId);
      this.taskSingle = selection.length !== 1;
      this.taskMultiple = !selection.length;
    },
    handleTaskAdd() {
      this.resetTaskForm();
      this.taskOpen = true;
      this.taskTitle = "添加检验任务";
    },
    handleTaskUpdate(row) {
      this.taskLoading = true;
      this.resetTaskForm();
      const taskId = row.taskId || this.taskIds;
      getInspectionTask(taskId).then(response => {
        this.taskForm = response.data;
        if (response.data.coilList && response.data.coilList.length > 0) {
          this.taskCoilList = response.data.coilList;
        } else if (response.data.coilIds) {
          listCoilByIds(response.data.coilIds).then(res => {
            this.taskCoilList = res.rows || [];
          });
        }
        this.taskLoading = false;
        this.taskOpen = true;
        this.taskTitle = "修改检验任务";
      });
    },
    submitTaskForm() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          const submitData = {
            ...this.taskForm,
            coilIds: this.taskCoilList.map(c => c.coilId).join(",") || undefined
          };
          if (this.taskForm.taskId != null) {
            updateInspectionTask(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.taskOpen = false;
              this.getTaskList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addInspectionTask(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.taskOpen = false;
              this.getTaskList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    handleTaskDelete(row) {
      const taskIds = row.taskId || this.taskIds;
      this.$modal.confirm('是否确认删除检验任务编号为"' + taskIds + '"的数据项？').then(() => {
        this.taskLoading = true;
        return delInspectionTask(taskIds);
      }).then(() => {
        this.taskLoading = false;
        this.getTaskList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.taskLoading = false;
      });
    },
    handleTaskExport() {
      this.download('qc/inspectionTask/export', {
        ...this.taskQueryParams
      }, `inspectionTask_${new Date().getTime()}.xlsx`);
    },
    handleQuickCreate() {
      this.schemeVisible = true;
    },
    handleSchemeConfirm({ template, taskCode, taskType, belongCompany, coilIds }) {
      this.taskLoading = true;
      addInspectionTaskWithItems({
        taskCode: taskCode,
        schemeId: template.templateId,
        schemeName: template.templateName,
        belongCompany: belongCompany,
        taskType: taskType,
        coilIds: coilIds
      }).then(() => {
        this.$modal.msgSuccess("快捷创建成功");
        this.getTaskList();
      }).finally(() => {
        this.taskLoading = false;
      });
    },
    handleTaskCoilConfirm(coils) {
      this.taskCoilList = [...coils];
    },
    handleInspect(row) {
      this.resultTaskRow = row;
      this.resultAction = 'inspect';
      this.resultForm = { result: row.result || undefined };
      this.resultTitle = "检验 - 填写最终结果";
      this.resultOpen = true;
    },
    handleAudit(row) {
      this.resultTaskRow = row;
      this.resultAction = 'audit';
      this.resultForm = { result: row.result || undefined };
      this.resultTitle = "审核 - 填写最终结果";
      this.resultOpen = true;
    },
    submitResult() {
      this.resultLoading = true;
      const now = this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
      const updateData = {
        taskId: this.resultTaskRow.taskId,
        result: this.resultForm.result
      };
      if (this.resultAction === 'inspect') {
        updateData.status = 1;
        updateData.inspectUser = this.$store.getters.name;
        updateData.inspectTime = now;
      } else {
        updateData.status = 2;
        updateData.auditUser = this.$store.getters.name;
        updateData.auditTime = now;
      }
      updateInspectionTask(updateData).then(() => {
        this.$modal.msgSuccess(this.resultAction === 'inspect' ? '检验成功' : '审核成功');
        this.resultOpen = false;
        this.getTaskList();
      }).finally(() => {
        this.resultLoading = false;
      });
    },
    loadCascadeData() {
      listInspectionItemTemplate({ pageNum: 1, pageSize: 9999 }).then(response => {
        const templates = response.rows || response.data || [];
        const cascade = {};
        templates.forEach(t => {
          const company = t.templateUnit || '未分类';
          if (!cascade[company]) {
            cascade[company] = [];
          }
          if (t.templateName && !cascade[company].includes(t.templateName)) {
            cascade[company].push(t.templateName);
          }
        });
        this.cascadeData = cascade;
        this.companyOptions = Object.keys(cascade).sort();
      });
    },
    handleCompanyChange() {
      this.selectedScheme = '';
      if (this.selectedCompany) {
        this.schemeOptions = this.cascadeData[this.selectedCompany] || [];
      } else {
        this.schemeOptions = [];
      }
      this.taskQueryParams.belongCompany = this.selectedCompany || undefined;
      this.taskQueryParams.schemeName = undefined;
      this.handleTaskQuery();
    },
    handleSchemeChange() {
      this.taskQueryParams.schemeName = this.selectedScheme || undefined;
      this.handleTaskQuery();
    },
    cancelTask() {
      this.taskOpen = false;
      this.resetTaskForm();
    },
    resetTaskForm() {
      this.taskForm = {
        taskId: undefined,
        taskCode: undefined,
        taskType: undefined,
        sourceType: undefined,
        sourceId: undefined,
        schemeId: undefined,
        schemeName: undefined,
        status: undefined,
        inspectUser: undefined,
        inspectTime: undefined,
        auditUser: undefined,
        auditTime: undefined,
        result: undefined,
        remark: undefined,
        coilIds: undefined,
        delFlag: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined
      };
      this.taskCoilList = [];
      this.resetForm("taskForm");
    },

    handleItemSelectionChange(selection) {
      this.itemIds = selection.map(item => item.itemId);
      this.itemSingle = selection.length !== 1;
      this.itemMultiple = !selection.length;
    },
    handleItemAdd() {
      if (!this.currentTask) return;
      this.resetItemForm();
      this.itemForm.taskId = this.currentTask.taskId;
      this.itemOpen = true;
      this.itemTitle = "添加检验任务项目+结果";
    },
    handleItemUpdate(row) {
      this.itemLoading = true;
      this.resetItemForm();
      const itemId = row.itemId || this.itemIds;
      getInspectionItem(itemId).then(response => {
        this.itemLoading = false;
        this.itemForm = response.data;
        this.itemOpen = true;
        this.itemTitle = "修改检验任务项目+结果";
      });
    },
    handleItemSave(row) {
      updateInspectionItem(row).then(() => {
        this.$modal.msgSuccess("保存成功");
        this.getItemList();
      });
    },
    submitItemForm() {
      this.$refs["itemForm"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.itemForm.itemId != null) {
            updateInspectionItem(this.itemForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.itemOpen = false;
              this.getItemList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addInspectionItem(this.itemForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.itemOpen = false;
              this.getItemList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    handleItemDelete(row) {
      const itemIds = row.itemId || this.itemIds;
      this.$modal.confirm('是否确认删除检验任务项目+结果编号为"' + itemIds + '"的数据项？').then(() => {
        this.itemLoading = true;
        return delInspectionItem(itemIds);
      }).then(() => {
        this.itemLoading = false;
        this.getItemList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.itemLoading = false;
      });
    },
    handleItemExport() {
      this.download('qc/inspectionItem/export', {
        ...this.itemQueryParams,
        taskId: this.currentTask ? this.currentTask.taskId : undefined
      }, `inspectionItem_${new Date().getTime()}.xlsx`);
    },
    cancelItem() {
      this.itemOpen = false;
      this.resetItemForm();
    },
    resetItemForm() {
      this.itemForm = {
        itemId: undefined,
        taskId: undefined,
        itemName: undefined,
        standardValue: undefined,
        upperLimit: undefined,
        lowerLimit: undefined,
        unit: undefined,
        itemType: undefined,
        inspectValue: undefined,
        isQualified: undefined,
        judgeResult: undefined,
        inspectUser: undefined,
        inspectTime: undefined,
        remark: undefined,
        delFlag: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined
      };
      this.resetForm("itemForm");
    },
  }
};
</script>
