<template>
  <div class="mod-config">
    <!-- 条件查询 -->
    <el-form :inline="true" label-position="top" :model="searchData">
      <el-form-item :label="'BU'">
        <el-select v-model="searchData.buDesc" placeholder="请选择" clearable style="width: 80px">
          <el-option
            v-for="i in userBuList"
            :key="i.buNo"
            :label="i.buDesc"
            :value="i.buDesc">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="'模板编码'">
        <el-input v-model="searchData.templateId" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'模板名称'">
        <el-input v-model="searchData.templateName" clearable style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="检验类型">
        <el-select v-model="searchData.inspectionTypeNo" placeholder="请选择" style="width: 100px">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="i in options"
            :key="i.inspectionTypeNo"
            :label="i.inspectionTypeName"
            :value="i.inspectionTypeNo">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="' '">
        <el-button v-if="!authSearch" type="primary" @click="getDataList()">查询</el-button>
        <el-button v-if="!authSave" type="primary" @click="addModal()">新增</el-button>
      </el-form-item>
      <el-form-item :label="' '">
        <el-button type="primary" icon="el-icon-upload" @click="qcUpload()">导入</el-button>
        <download-excel
          :fields="fields()"
          :data="exportData"
          type="xls"
          :name="exportName"
          :header="exportHeader"
          :footer="exportFooter"
          :fetch="createExportData"
          :before-generate="startDownload"
          :before-finish="finishDownload"
          worksheet="导出信息"
          class="el-button el-button--primary el-button--medium">
          {{ "导出" }}
        </download-excel>
      </el-form-item>
    </el-form>

    <!-- 展示列表 -->
    <el-table :height="height" :data="dataList" border style="width: 100%;">
      <el-table-column
        v-for="(item,index) in columnList" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed===''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden">
            <span v-if="columnsProp.includes(item.columnProp)">{{ scope.row[`${item.columnProp}Desc`] }}</span>
            <span v-else>
              {{ scope.row[item.columnProp] }}
            </span>
          </span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="160" label="操作">
        <template slot-scope="scope">
          <a v-if="!authUpdate" type="text" size="small" @click="updateModal(scope.row)">编辑</a>
          <a v-if="!authDetail" type="text" size="small" @click="detailModal(scope.row)">检验项目</a>
          <a v-if="!authDelete" type="text" size="small" @click="deleteModel(scope.row)">删除</a>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页栏 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[20, 50, 100, 200, 500]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 检验模板新增/修改 -->
    <el-dialog title="检验模板" :close-on-click-modal="false" v-drag :visible.sync="modalFlag" width="500px">
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item label="BU" prop="bu" :rules="rules.bu">
          <el-select v-model="modalData.bu" placeholder="请选择" :disabled="modalDisableFlag" style="width: 456px">
            <el-option
              v-for="i in userBuList"
              :key="i.buNo"
              :label="i.sitename"
              :value="i.buNo">
              <span style="float: left;width: 100px">{{ i.sitename }}</span>
              <span style="float: right; color: #8492a6;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; font-size: 11px;width: 60px">
                {{ i.buDesc }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item label="检验模板名称" prop="templateName" :rules="rules.templateNameType">
          <el-input v-model="modalData.templateName" style="width: 221px"></el-input>
        </el-form-item>
        <el-form-item label="检验类型" prop="inspectionTypeNo" :rules="rules.inspectionTypeNoType">
          <el-select v-model="modalData.inspectionTypeNo" placeholder="请选择" style="width: 221px">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="i in options"
              :key="i.inspectionTypeNo"
              :label="i.inspectionTypeName"
              :value="i.inspectionTypeNo">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- <el-form :inline="true" label-position="top" :model="modalData" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item>
          <span slot="label" @click="getBaseList(207)"><a herf="#">抽样方案编码</a></span>
          <el-input v-model="modalData.samplingProgrammeNo" style="width: 221px"></el-input>
        </el-form-item>
        <el-form-item label="抽样方案名称">
          <el-input v-model="modalData.samplingProgrammeDesc" disabled style="width: 221px"></el-input>
        </el-form-item>
      </el-form>
      <el-form :inline="true" label-position="top" :model="modalData" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item>
          <span slot="label" style="" @click="getBaseList(208)"><a herf="#">检验水平编码</a></span>
          <el-input v-model="modalData.samplingLevelNo" style="width: 221px"></el-input>
        </el-form-item>
        <el-form-item label="检验水平名称">
          <el-input v-model="modalData.samplingLevelDesc" disabled style="width: 221px"></el-input>
        </el-form-item>
      </el-form> -->
      <el-form :inline="true" label-position="top" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item label="检验周期(h)">
          <el-input v-model="modalData.inspectionCycle" type="number" style="width: 143px"></el-input>
        </el-form-item>
        <el-form-item label="默认抽样数量">
          <el-input v-model="modalData.defaultSamplingQuantity" type="number" style="width: 143px"></el-input>
        </el-form-item>
        <el-form-item label="默认抽样比例">
          <el-input v-model="modalData.defaultSamplingProportion" type="number" style="width: 143px"></el-input>
        </el-form-item>
      </el-form>
      <!-- <el-form :inline="true" label-position="top" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item label="AQL:">
          <el-input v-model="modalData.aql" type="number" style="width: 143px"></el-input>
        </el-form-item>
        <el-form-item label="AC:">
          <el-input v-model="modalData.ac" type="number" style="width: 143px"></el-input>
        </el-form-item>
        <el-form-item label="RE:">
          <el-input v-model="modalData.re" type="number" style="width: 143px"></el-input>
        </el-form-item>
      </el-form> -->
      <el-form :inline="true" label-position="top" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item label="版本号">
          <el-input v-model="modalData.templateVersion" :disabled="modalDisableFlag" style="width: 221px"></el-input>
        </el-form-item>
        <el-form-item label="检验模板备注">
          <el-input v-model="modalData.templateRemark" style="width: 221px"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="height:40px;margin-top: 10px;text-align:center">
        <el-button type="primary" @click="saveData()">保存</el-button>
        <el-button type="primary" @click="modalFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>

    <!-- 检验项目 -->
    <el-dialog title="检验项目清单" @close="closeDialog" :close-on-click-modal="false" v-drag :visible.sync="detailModelFlag" width="940px">
      <!-- 这里保留 QC 完整版结构（已能跑通 dmBasic 接口） -->
      <el-form :inline="true" label-position="top">
        <el-form-item :label="'检验模板编码'">
          <el-input v-model="detailData.templateId" readonly style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item :label="'检验模板名称'">
          <el-input v-model="detailData.templateName" readonly style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item :label="' '">
          <el-button type="primary" @click="addFastModal()">新增</el-button>
          <el-button type="primary" @click="goUp()">上移</el-button>
          <el-button type="primary" @click="goDown()">下移</el-button>
        </el-form-item>
      </el-form>
      <div class="rq ">
        <el-table
          :height="400"
          :data="detailList"
          @row-click="itemClickRow"
          ref="detailTable"
          highlight-current-row
          border
          style="width: 100%;">
          <el-table-column
            v-for="(item,index) in columnDetailList" :key="index"
            :sortable="item.columnSortable"
            :prop="item.columnProp"
            :header-align="item.headerAlign"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :align="item.align"
            :fixed="item.fixed===''?false:item.fixed"
            :min-width="item.columnWidth"
            :label="item.columnLabel">
            <template slot-scope="scope">
              <span v-if="!item.columnHidden"> {{ scope.row[item.columnProp] }}</span>
              <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
            </template>
          </el-table-column>
          <el-table-column prop="" header-align="center" align="right" min-width="60" label="标准值">
            <template slot-scope="scope">
              <el-input v-model="scope.row.defaultValue" style="height: 11px;width:98%"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="" header-align="center" align="right" min-width="60" label="最大值">
            <template slot-scope="scope">
              <el-input v-if="scope.row.valueTypeDb === 'T'" v-model="scope.row.maxValue" disabled style="height: 11px;width:98%"></el-input>
              <el-input v-else v-model="scope.row.maxValue" style="height: 11px;width:98%"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="" header-align="center" align="right" min-width="60" label="最小值">
            <template slot-scope="scope">
              <el-input v-if="scope.row.valueTypeDb === 'T'" v-model="scope.row.minValue" disabled style="height: 11px;width:98%"></el-input>
              <el-input v-else v-model="scope.row.minValue" style="height: 11px;width:98%"></el-input>
            </template>
          </el-table-column>
          <el-table-column fixed="right" header-align="center" align="center" width="130" label="操作">
            <template slot-scope="scope">
              <a v-if="scope.row.valueTypeDb === 'N'" type="text" size="small" @click="inspectionStandardModal(scope.row)">判定标准</a>
              <a type="text" size="small" @click="delItemDetails(scope.row)">删除项目</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer style="height:40px;margin-top: 20px;text-align:center">
        <el-button type="primary" @click="saveDetail()">保存</el-button>
        <el-button type="primary" @click="detailModelFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>

    <!-- 检验项目->快速新增 -->
    <el-dialog title="新增" @close="refreshDetailList" :close-on-click-modal="false" v-drag :visible.sync="fastAddFlag" width="1100px">
      <div style="font-size: 12px">
        <el-form :inline="true" label-position="top" :model="detailData">
          <el-form-item :label="'项目编码'">
            <el-input v-model="detailData.itemNo" clearable style="width: 120px"></el-input>
          </el-form-item>
          <el-form-item :label="'项目名称'">
            <el-input v-model="detailData.itemDesc" clearable style="width: 200px"></el-input>
          </el-form-item>
          <el-form-item :label="' '">
            <el-button type="primary" @click="getItem()">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-container style="margin-top: 0px;">
        <el-main style="width: 720px; padding: 1px">
          <span style="font-size: 12px">可选项目：</span>
          <el-table
            height="400px"
            :data="itemList1"
            border
            ref="itemTable1"
            @row-click="itemClickRow1"
            @selection-change="selectionItem1"
            highlight-current-row
            style="width: 100%">
            <el-table-column type="selection" header-align="center" align="center" :selectable="selectFlag" width="50"></el-table-column>
            <el-table-column prop="itemNo" header-align="center" align="center" min-width="80" label="项目编码"></el-table-column>
            <el-table-column prop="itemDesc" header-align="center" align="center" min-width="120" label="项目名称"></el-table-column>
            <el-table-column prop="defaultValue" header-align="center" align="center" min-width="100" label="标准值"></el-table-column>
            <el-table-column prop="maxValue" header-align="center" align="center" min-width="60" label="最大值"></el-table-column>
            <el-table-column prop="minValue" header-align="center" align="center" min-width="60" label="最小值"></el-table-column>
          </el-table>
        </el-main>
        <el-main style="width: 111px; padding: 1px">
          <div style="margin-top: 182px; margin-left: 18px">
            <el-button type="primary" @click="addItem()">添加>></el-button>
          </div>
          <div style="margin-top: 15px; margin-left: 18px">
            <el-button type="primary" @click="deleteItem()">删除<<</el-button>
          </div>
        </el-main>
        <el-main style="width: 400px; padding: 1px">
          <span style="font-size: 12px">已有项目：</span>
          <el-table
            height="400px"
            :data="itemList2"
            border
            ref="itemTable2"
            @row-click="itemClickRow2"
            @selection-change="selectionItem2"
            highlight-current-row
            style="width: 100%">
            <el-table-column type="selection" header-align="center" align="center" :selectable="selectFlag" width="50"></el-table-column>
            <el-table-column prop="itemNo" header-align="center" align="center" min-width="80" label="项目编码"></el-table-column>
            <el-table-column prop="itemDesc" header-align="center" align="center" min-width="200" label="项目名称"></el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <el-footer style="height: 40px; margin-top: 20px; text-align: center">
        <el-button type="primary" @click="fastAddFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>

    <Chooselist ref="baseList" @getBaseData="getBaseData"></Chooselist>
    <dmUpload ref="qcUpload" @refreshPageTables="getDataList()" v-drag></dmUpload>
  </div>
</template>

<script>
import {
  templateSearch,
  templateSave,
  templateUpdate,
  templateDelete,
  inspectionTypeSearch,
  templateDetailsSearch,
  addItemDetails,
  getItemList,
  delItemDetails,
  saveItemDetailed,
  getItem,
  getSiteAndBuByUserName,
  getInspectionStandards,
  saveInspectionStandard,
  goUpItemQC,
  goDownItemQC,
} from "@/api/qc/dmBasic.js";
import { getTableDefaultListLanguage, getTableUserListLanguage } from "@/api/table.js";
import Chooselist from "@/views/modules/common/Chooselist_eam";
import { userFavoriteList, saveUserFavorite, removeUserFavorite } from "@/api/userFavorite.js";
import dmUpload from "./dm_upload.vue";

export default {
  name: "DMQcTemplate",
  components: { Chooselist, dmUpload },
  data() {
    return {
      columnsProp: ["createBy", "updateBy"],
      favorite: false,
      exportData: [],
      exportName: "刀模检验模板" + this.dayjs().format("YYYYMMDDHHmmss"),
      exportHeader: ["刀模检验模板"],
      exportFooter: [],
      exportList: [],
      tagNo: "",
      searchData: {
        site: "",
        userName: this.$store.state.user.name,
        templateId: "",
        templateName: "",
        inspectionTypeNo: "",
        buDesc: "RFID",
        page: 1,
        limit: 10
      },
      options: [],
      height: 200,
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      modalFlag: false,
      modalDisableFlag: false,
      modalData: {
        flag: "",
        site: "",
        bu: "",
        templateId: "",
        templateName: "",
        templateRemark: "",
        templateType: "",
        templateVersion: "",
        samplingProgrammeNo: "",
        samplingProgrammeDesc: "",
        inspectionTypeNo: "822",
        inspectionCycle: "",
        samplingLevelNo: "",
        samplingLevelDesc: "",
        aql: "",
        ac: "",
        re: "",
        defaultSamplingQuantity: "",
        defaultSamplingProportion: "",
        createTime: "",
        createBy: this.$store.state.user.name,
        updateBy: this.$store.state.user.name,
      },
      detailData: {
        site: "",
        buNo: "",
        templateId: "",
        templateName: "",
        inspectionTypeNo: "822",
        inspectionTypeName: "",
        createBy: this.$store.state.user.name,
        itemType: "D",
        itemNo: "",
        itemDesc: "",
      },
       columnList:[
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableBuDesc',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'buDesc',
            headerAlign: "center",
            align: "center",
            columnLabel: 'BU',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'templateId',
            headerAlign: "center",
            align: "center",
            columnLabel: '检验模板编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'templateName',
            headerAlign: "center",
            align: "left",
            columnLabel: '检验模板名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 200,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'inspectionCycle',
            headerAlign: "center",
            align: "right",
            columnLabel: '检验周期(h)',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'defaultSamplingQuantity',
            headerAlign: "center",
            align: "right",
            columnLabel: '默认抽样数量',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'defaultSamplingProportion',
            headerAlign: "center",
            align: "right",
            columnLabel: '默认抽样比例',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          /* {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'aql',
            headerAlign: "center",
            align: "right",
            columnLabel: 'AQL',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'ac',
            headerAlign: "center",
            align: "right",
            columnLabel: 'AC',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 're',
            headerAlign: "center",
            align: "right",
            columnLabel: 'RE',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          }, */
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'inspectionTypeName',
            headerAlign: "center",
            align: "center",
            columnLabel: '检验类型',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'templateRemark',
            headerAlign: "center",
            align: "left",
            columnLabel: '检验模板备注',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 200,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'templateVersion',
            headerAlign: "center",
            align: "center",
            columnLabel: '版本号',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'createTime',
            headerAlign: "center",
            align: "center",
            columnLabel: '创建时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 170,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'createBy',
            headerAlign: "center",
            align: "center",
            columnLabel: '创建人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'updateDate',
            headerAlign: 'center',
            align: 'center',
            columnLabel: '更新时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 170,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 301008,
            serialNumber: '301008TableItemNo',
            tableId: "301008Table",
            tableName: "检验模板维护表",
            columnProp: 'updateBy',
            headerAlign: 'center',
            align: 'center',
            columnLabel: '更新人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
        ],
      detailModelFlag: false,
      detailList: [],
      dataList: [],
      columnDetailList: [
        { columnProp: "itemNo", headerAlign: "center", align: "center", columnLabel: "检验项目编码", columnHidden: false, columnImage: false, columnSortable: false, sortLv: 0, status: true, fixed: "", columnWidth: 60 },
        { columnProp: "itemDesc", headerAlign: "center", align: "left", columnLabel: "检验项目名称", columnHidden: false, columnImage: false, columnSortable: false, sortLv: 0, status: true, fixed: "", columnWidth: 250 },
        { columnProp: "valueType", headerAlign: "center", align: "center", columnLabel: "检测值类型", columnHidden: false, columnImage: false, columnSortable: false, sortLv: 0, status: true, fixed: "", columnWidth: 60 },
      ],
      fastAddFlag: false,
      itemList1: [],
      itemList2: [],
      itemSelections1: [],
      itemSelections2: [],
      currentRow: {},
      rules: {
        templateNameType: [{ required: true, message: " ", trigger: ["blur", "change"] }],
        inspectionTypeNoType: [{ required: true, message: " ", trigger: ["blur", "change"] }],
        bu: [{ required: true, message: " ", trigger: ["blur", "change"] }]
      },
      userBuList: [],
      authSearch: false,
      authSave: false,
      authUpdate: false,
      authDelete: false,
      authDetail: false,
      menuId: this.$route.meta.menuId,
      inspectionStandardModalFlag: false,
      standardData: { site: "", buNo: "", templateId: "", itemNo: "", standardList: [] },
      tableData: [],
      checkedDetail: [],
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.height = window.innerHeight - 180;
    });
  },
  created() {
    this.getButtonAuthData();
    this.getSiteAndBuByUserName();
    this.favoriteIsOk();
    this.inspectionTypeSearch();
    this.getTableUserColumn(this.$route.meta.menuId + "table", 1);
    if (!this.authSearch) {
      this.getDataList();
    }
  },
  methods: {
    getSiteAndBuByUserName() {
      const tempData = { username: this.$store.state.user.name };
      getSiteAndBuByUserName(tempData).then(({ data }) => {
        if (data.code === 0) this.userBuList = data.rows;
      });
    },
    inspectionTypeSearch() {
      const tempData = { site: this.$store.state.user.site };
      inspectionTypeSearch(tempData).then(({ data }) => {
        console.log(data.rows);
        
        if (data.code === 0) this.options = data.rows;
      });
    },
    getDataList() {
      this.searchData.limit = this.pageSize;
      this.searchData.page = this.pageIndex;
      templateSearch(this.searchData).then(({ data }) => {
        if (data.code === 0) {
          this.dataList = data.page.list;
          this.pageIndex = data.page.currPage;
          this.pageSize = data.page.pageSize;
          this.totalPage = data.page.totalCount;
        }
      });
    },
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    addModal() {
      this.modalData = {
        flag: "1",
        site: "",
        bu: '2_03-RFID',
        templateId: "",
        templateName: "",
        templateRemark: "",
        templateType: "",
        templateVersion: "",
        samplingProgrammeNo: "",
        samplingProgrammeDesc: "",
        inspectionTypeNo: "823",
        inspectionCycle: "",
        samplingLevelNo: "",
        samplingLevelDesc: "",
        defaultSamplingQuantity: "",
        defaultSamplingProportion: "",
        aql: "",
        ac: "",
        re: "",
        createBy: this.$store.state.user.name,
        updateBy: this.$store.state.user.name,
      };
      this.modalDisableFlag = false;
      this.modalFlag = true;
    },
    updateModal(row) {
      this.modalData = {
        flag: "2",
        bu: row.site + "_" + row.buNo,
        site: row.site,
        templateId: row.templateId,
        templateName: row.templateName,
        templateRemark: row.templateRemark,
        templateType: row.templateType,
        templateVersion: row.templateVersion,
        samplingProgrammeNo: row.samplingProgrammeNo,
        samplingProgrammeDesc: row.samplingProgrammeDesc,
        inspectionTypeNo: "822",
        samplingLevelNo: row.samplingLevelNo,
        samplingLevelDesc: row.samplingLevelDesc,
        inspectionCycle: row.inspectionCycle,
        defaultSamplingQuantity: row.defaultSamplingQuantity,
        defaultSamplingProportion: row.defaultSamplingProportion,
        aql: row.aql,
        ac: row.ac,
        re: row.re,
        createBy: this.$store.state.user.name,
        updateBy: this.$store.state.user.name,
      };
      this.modalDisableFlag = true;
      this.modalFlag = true;
    },
    deleteModel(row) {
      this.$confirm(`是否删除这个检验模板?`, "提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" })
        .then(() => {
          templateDelete(row).then(({ data }) => {
            if (data && data.code === 0) {
              this.getDataList();
              this.$message({ message: "操作成功", type: "success", duration: 1500, onClose: () => {} });
            } else {
              this.$alert(data.msg, "错误", { confirmButtonText: "确定" });
            }
          });
        })
        .catch(() => {});
    },
    saveData() {
      if (this.modalData.bu === "" || this.modalData.bu == null) {
        this.$message.warning("请选择BU！");
        return;
      }
      if (this.modalData.templateName === "" || this.modalData.templateName == null) {
        this.$message.warning("请输入检验模板名称！");
        return;
      }
      if (this.modalData.inspectionTypeNo === "" || this.modalData.inspectionTypeNo == null) {
        this.$message.warning("请选择检验类型！");
        return;
      }

      if (this.modalData.flag === "1") {
        templateSave(this.modalData).then(({ data }) => {
          if (data && data.code === 0) {
            this.getDataList();
            this.modalFlag = false;
            this.$message({ message: "操作成功", type: "success", duration: 1500, onClose: () => {} });
          } else {
            this.$alert(data.msg, "错误", { confirmButtonText: "确定" });
          }
        });
      } else {
        templateUpdate(this.modalData).then(({ data }) => {
          if (data && data.code === 0) {
            this.getDataList();
            this.modalFlag = false;
            this.$message({ message: "操作成功", type: "success", duration: 1500, onClose: () => {} });
          } else {
            this.$alert(data.msg, "错误", { confirmButtonText: "确定" });
          }
        });
      }
    },
    detailModal(row) {
      this.detailData.site = row.site;
      this.detailData.buNo = row.buNo;
      this.detailData.templateId = row.templateId;
      this.detailData.templateName = row.templateName;
      this.detailData.inspectionTypeNo = "822";
      this.detailData.inspectionTypeName = row.inspectionTypeName;
      templateDetailsSearch(this.detailData).then(({ data }) => {
        this.detailList = data.rows;
      });
      this.detailModelFlag = true;
    },
    saveDetail() {
      const tempData = { site: this.detailData.site, buNo: this.detailData.buNo, templateId: this.detailData.templateId, itemList: this.detailList };
      saveItemDetailed(tempData).then(({ data }) => {
        if (data && data.code === 0) {
          this.getDataList();
          this.detailModelFlag = false;
          this.$message({ message: "操作成功", type: "success", duration: 1500, onClose: () => {} });
        } else {
          this.$alert(data.msg, "错误", { confirmButtonText: "确定" });
        }
      });
    },
    addFastModal() {
      this.itemSelections1 = [];
      this.itemSelections2 = [];
      getItemList(this.detailData).then(({ data }) => {
        // dmBasic 保持同样返回结构 row1/row2
        this.itemList1 = data.row1;
        this.itemList2 = data.row2;
      });
      this.fastAddFlag = true;
    },
    getItem() {
      getItem(this.detailData).then(({ data }) => {
        if (data.code === 0) {
          this.itemList1 = data.rows;
        }
      });
    },
    itemClickRow1(row) {
      this.$refs.itemTable1.toggleRowSelection(row);
    },
    itemClickRow2(row) {
      this.$refs.itemTable2.toggleRowSelection(row);
    },
    selectFlag() {
      return true;
    },
    selectionItem1(val) {
      this.itemSelections1 = val;
    },
    selectionItem2(val) {
      this.itemSelections2 = val;
    },
    addItem() {
      if (this.itemSelections1 == null || this.itemSelections1.length === 0) {
        this.$message.warning("请选择可选项目！");
        return;
      }
      const inData = {
        site: this.detailData.site,
        buNo: this.detailData.buNo,
        templateId: this.detailData.templateId,
        templateName: this.detailData.templateName,
        itemList: this.itemSelections1,
        itemType: this.detailData.itemType,
      };
      addItemDetails(inData).then(({ data }) => {
        if (data && data.code === 0) {
          getItemList(this.detailData).then(({ data: rowsData }) => {
            this.itemList1 = rowsData.row1;
            this.itemList2 = rowsData.row2;
          });
          this.itemSelections1 = [];
        } else {
          this.$alert(data.msg, "错误", { confirmButtonText: "确定" });
        }
      });
    },
    deleteItem() {
      if (this.itemSelections2 == null || this.itemSelections2.length === 0) {
        this.$message.warning("请选择已有项目！");
        return;
      }
      const inData = {
        site: this.detailData.site,
        buNo: this.detailData.buNo,
        templateId: this.detailData.templateId,
        templateName: this.detailData.templateName,
        itemList: this.itemSelections2,
        itemType: this.detailData.itemType,
      };
      delItemDetails(inData).then(({ data }) => {
        if (data && data.code === 0) {
          getItemList(this.detailData).then(({ data: rowsData }) => {
            this.itemList1 = rowsData.row1;
            this.itemList2 = rowsData.row2;
          });
          this.itemSelections2 = [];
        } else {
          this.$alert(data.msg, "错误", { confirmButtonText: "确定" });
        }
      });
    },
    refreshDetailList() {
      templateDetailsSearch(this.detailData).then(({ data }) => {
        this.detailList = data.rows;
      });
    },
    delItemDetails(row) {
      this.$confirm(`是否删除这个检验明细?`, "提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" })
        .then(() => {
          delItemDetails(row).then(({ data }) => {
            if (data && data.code === 0) {
              templateDetailsSearch(this.detailData).then(({ data }) => {
                this.detailList = data.rows;
              });
              this.$message({ message: "操作成功", type: "success", duration: 1500, onClose: () => {} });
            } else {
              this.$alert(data.msg, "错误", { confirmButtonText: "确定" });
            }
          });
        })
        .catch(() => {});
    },
    itemClickRow(row) {
      this.currentRow = JSON.parse(JSON.stringify(row));
    },
    goUp() {
      goUpItemQC(this.currentRow).then(({ data }) => {
        if (data && data.code === 0) {
          templateDetailsSearch(this.detailData).then(({ data }) => {
            this.detailList = data.rows;
            this.$message.success("操作成功");
          });
        }
      });
    },
    goDown() {
      goDownItemQC(this.currentRow).then(({ data }) => {
        if (data && data.code === 0) {
          templateDetailsSearch(this.detailData).then(({ data }) => {
            this.detailList = data.rows;
            this.$message.success("操作成功");
          });
        }
      });
    },
    closeDialog() {
      this.detailList = [];
      this.itemList1 = [];
      this.itemList2 = [];
    },
    qcUpload() {
      const currentData = { flag: "template", createBy: this.$store.state.user.name, site: this.$store.state.user.site };
      this.$nextTick(() => {
        this.$refs.qcUpload.init(currentData);
      });
    },
    favoriteIsOk() {
      const userFavorite = { userId: this.$store.state.user.id, languageCode: this.$i18n.locale };
      userFavoriteList(userFavorite).then(({ data }) => {
        for (let i = 0; i < data.list.length; i++) {
          if (this.$route.meta.menuId === data.list[i].menuId) this.favorite = true;
        }
      });
    },
    favoriteFunction() {
      const userFavorite = { userId: this.$store.state.user.id, functionId: this.$route.meta.menuId };
      if (this.favorite) {
        removeUserFavorite(userFavorite).then(({ data }) => {
          this.$message.success(data.msg);
          this.favorite = false;
        });
      } else {
        saveUserFavorite(userFavorite).then(({ data }) => {
          this.$message.success(data.msg);
          this.favorite = true;
        });
      }
    },
    async createExportData() {
      this.searchData.limit = -1;
      this.searchData.page = 1;
      this.searchData.inspectionTypeNo = "822";
      await templateSearch(this.searchData).then(({ data }) => {
        this.exportList = data.page.list;
      });
      return this.exportList;
    },
    startDownload() {},
    finishDownload() {},
    fields() {
      let json = "{";
      this.columnList.forEach((item, index) => {
        json += `"${item.columnLabel}":"${item.columnProp}"${index === this.columnList.length - 1 ? "" : ","}`;
      });
      json += "}";
      // eslint-disable-next-line no-eval
      return eval("(" + json + ")");
    },
    async getTableUserColumn(tableId, columnId) {
      const queryTableUser = { userId: this.$store.state.user.name, functionId: this.$route.meta.menuId, tableId, status: true, languageCode: this.$i18n.locale };
      await getTableUserListLanguage(queryTableUser).then(({ data }) => {
        if (data.rows.length > 0) {
          if (columnId === 1) this.columnList = data.rows;
        } else {
          this.getColumnList(tableId, columnId);
        }
      });
    },
    async getColumnList(tableId, columnId) {
      const queryTable = { functionId: this.$route.meta.menuId, tableId, languageCode: this.$i18n.locale };
      await getTableDefaultListLanguage(queryTable).then(({ data }) => {
        if (!data.rows.length === 0) {
          if (columnId === 1) this.columnList = data.rows;
        }
      });
    },
    getButtonAuthData() {
      const searchFlag = this.isAuth(this.menuId + ":search");
      const saveFlag = this.isAuth(this.menuId + ":save");
      const updateFlag = this.isAuth(this.menuId + ":update");
      const deleteFlag = this.isAuth(this.menuId + ":delete");
      const detailFlag = this.isAuth(this.menuId + ":detail");
      this.authSearch = !searchFlag;
      this.authSave = !saveFlag;
      this.authUpdate = !updateFlag;
      this.authDelete = !deleteFlag;
      this.authDetail = !detailFlag;
    },
    // 判定标准弹窗/表格逻辑（与 QC 一致）
    inspectionStandardModal(row) {
      this.standardData = { site: row.site, buNo: row.buNo, templateId: row.templateId, itemNo: row.itemNo, standardList: [] };
      getInspectionStandards(this.standardData).then(({ data }) => {
        this.tableData = data.code === 0 ? data.rows : [];
      });
      this.inspectionStandardModalFlag = true;
    },
    saveInspectionStandard() {
      this.standardData.standardList = this.tableData;
      saveInspectionStandard(this.standardData).then(({ data }) => {
        if (data && data.code === 0) {
          this.inspectionStandardModalFlag = false;
          this.tableData = [];
          this.$message({ message: "操作成功", type: "success", duration: 1500, onClose: () => {} });
        } else {
          this.$alert(data.msg, "错误", { confirmButtonText: "确定" });
        }
      });
    },
    // 获取基础数据列表（抽样方案/检验水平）
    getBaseList(val) {
      this.tagNo = val;
      this.$nextTick(() => {
        let strVal = "";
        let conSql = "";
        if (this.modalData.bu === null || this.modalData.bu === "") {
          this.$message.warning("请选择BU！");
          return;
        } else {
          conSql = " and site = '" + this.modalData.bu.split("_")[0] + "'" + " and bu_no = '" + this.modalData.bu.split("_")[1] + "'";
        }
        if (val === 207) strVal = this.modalData.samplingProgrammeNo;
        if (val === 208) strVal = this.modalData.samplingLevelNo;
        this.$refs.baseList.init(val, strVal, conSql);
      });
    },
    // 列表方法的回调
    getBaseData(val) {
      if (this.tagNo === 207) {
        this.modalData.samplingProgrammeNo = val.sampling_programme_no;
        this.modalData.samplingProgrammeDesc = val.sampling_programme_desc;
      }
      if (this.tagNo === 208) {
        this.modalData.samplingLevelNo = val.sampling_level_no;
        this.modalData.samplingLevelDesc = val.sampling_level_desc;
      }
    },
  }
};
</script>