<template>
  <div class="mod-config">
    <!-- 收藏 -->
    <div>
        <span @click="favoriteFunction()">
         <icon-svg :name="favorite?'xiangqufill':'xiangqu'" class="sl-svg"></icon-svg>
        </span>
    </div>
    <!-- 条件查询 -->
    <el-form :inline="true" label-position="top" :model="searchData" @keyup.enter.native="getDataList()">
      <el-form-item :label="'模板编码'">
        <el-input v-model="searchData.templateId" style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'模板名称'">
        <el-input v-model="searchData.templateName" style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="检验类型">
        <el-select v-model="searchData.inspectionTypeNo" placeholder="请选择">
          <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 @click="doEmpty()">清空</el-button>
        <el-button type="primary" @click="getDataList()">查询</el-button>
        <el-button 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
      v-loading="dataListLoading"
      style="width: 100%;">
<!--      <el-table-column-->
<!--        prop="templateId"-->
<!--        header-align="center"-->
<!--        align="center"-->
<!--        label="检验模板编码"-->
<!--        width="100">-->
<!--      </el-table-column>-->
<!--      <el-table-column-->
<!--        prop="templateName"-->
<!--        header-align="center"-->
<!--        align="left"-->
<!--        label="检验模板名称"-->
<!--        :width="flexColumnWidth('检验模板名称','templateName')">-->
<!--      </el-table-column>-->
<!--      <el-table-column-->
<!--        prop="samplingProgrammeNo"-->
<!--        header-align="center"-->
<!--        align="center"-->
<!--        label="抽样方案"-->
<!--        :width="flexColumnWidth('抽样方案','samplingProgrammeNo')">-->
<!--      </el-table-column>-->
<!--      <el-table-column-->
<!--        prop="samplingLevelDesc"-->
<!--        header-align="center"-->
<!--        align="left"-->
<!--        label="检验水平"-->
<!--        :width="flexColumnWidth('检验水平','samplingLevelDesc')">-->
<!--      </el-table-column>-->
      <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">{{ 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
        fixed="right"
        header-align="center"
        align="center"
        width="160"
        label="操作">
        <template slot-scope="scope">
          <a type="text" size="small" @click="updateModal(scope.row)">编辑</a>
          <a type="text" size="small" @click="detailModal(scope.row)">检验项目</a>
          <a 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, 1000]"
      :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="430px">
      <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: 120px"></el-input>
        </el-form-item>
        <el-form-item label="检验类型" prop="inspectionTypeNo" :rules="rules.inspectionTypeNoType">
          <el-select v-model="modalData.inspectionTypeNo" placeholder="请选择" style="width: 120px">
            <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" :rules="rules" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item prop="samplingProgrammeNo" :rules="rules.samplingProgrammeNoType">
          <span slot="label" style="" @click="getBaseList(1051)"><a herf="#">抽样方案编码</a></span>
          <el-input v-model="modalData.samplingProgrammeNo" style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item label="抽样方案名称:" prop="samplingProgrammeDesc" :rules="rules.samplingProgrammeDescType">
          <el-input v-model="modalData.samplingProgrammeDesc" disabled style="width: 120px"></el-input>
        </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 prop="samplingLevelNo" :rules="rules.samplingLevelNoType">
          <span slot="label" style="" @click="getBaseList(1048)"><a herf="#">检验水平编码</a></span>
          <el-input v-model="modalData.samplingLevelNo" style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item label="检验水平名称:" prop="samplingLevelDesc" :rules="rules.samplingLevelDescType">
          <el-input v-model="modalData.samplingLevelDesc" disabled style="width: 120px"></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: 120px"></el-input>
        </el-form-item>
        <el-form-item label="默认抽样数量:">
          <el-input v-model="modalData.defaultSamplingQuantity" type="number" style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item label="默认抽样比例:">
          <el-input v-model="modalData.defaultSamplingProportion" type="number" style="width: 120px"></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" style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item label="AC:">
          <el-input v-model="modalData.ac" type="number" style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item label="RE:">
          <el-input v-model="modalData.re" type="number" style="width: 120px"></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: 120px"></el-input>
        </el-form-item>
        <el-form-item label="检验模板备注:">
          <el-input v-model="modalData.templateRemark"  style="width: 255px"></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-on-click-modal="false" v-drag :visible.sync="detailModelFlag" width="820px">
      <el-form :inline="true" label-position="top" @keyup.enter.native="getDataList()">
        <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-form-item>
      </el-form>
      <!-- 检验项目展示列表 -->
      <div class="rq ">
      <el-table
        :height="400"
        :data="detailList"
        border
        v-loading="dataListLoading"
        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;padding: 0px " allow-create>;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;padding: 0px " allow-create>;width:98%"></el-input>
            <el-input v-if="scope.row.valueTypeDb != 'T'" v-model="scope.row.maxValue" style="height: 11px;padding: 0px " allow-create>;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;padding: 0px " allow-create>;width:98%"></el-input>
            <el-input v-if="scope.row.valueTypeDb != 'T'" v-model="scope.row.minValue" style="height: 11px;padding: 0px " allow-create>;width:98%"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          header-align="center"
          align="right"
          min-width="100"
          label="检验设备">
          <template slot-scope="scope">
<!--            <el-select v-model="scope.row.objectID" placeholder="请选择" >-->
<!--              <el-option-->
<!--                v-for = "i in objects"-->
<!--                :key = "i.objectID"-->
<!--                :label = "i.objectDesc"-->
<!--                :value = "i.objectID">-->
<!--              </el-option>-->
<!--            </el-select>-->
            <el-autocomplete
              clearable
              class="inline-input"
              popper-class="el-autocomplete-suggestion"
              v-model="scope.row.objectID"
              value-key="idAndDesc"
              :fetch-suggestions="FilterEntityName"
              :trigger-on-focus="true"
              placeholder="请选择设备"
              @clear="blurForBug()"
              @select="handleSelect"
              :popper-append-to-body="false"
            ></el-autocomplete>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="80"
          label="操作">
          <template slot-scope="scope">
            <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="900px">
      <div style="font-size: 12px">
        <el-form :inline="true"  label-position="top" :model="detailData">
          <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: 200px"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <el-container style="margin-top: 0px;">
        <el-main style="width: 400px; 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
            v-loading="dataListLoading"
            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="230"
              label="项目名称">
            </el-table-column>
          </el-table>
        </el-main>
        <el-main style="width: 100px;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
            v-loading="dataListLoading"
            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="230"
              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>
    <!-- 导入 -->
    <qcUpload ref="qcUpload" @refreshPageTables="getDataList()" v-drag></qcUpload>
  </div>
</template>

<script>
  import {
    templateSearch, // 查询模板
    templateSave, // 新增模板
    templateUpdate, // 修改模板
    templateDelete, // 删除模板
    InspectionTypeSearch, // 搜索所有检验类型
    objectSearch, // 搜索所有设备
    templateDetailsSearch, // 查询明细列表
    addItemDetails, // 新增项目的检验明细
    getItemList, // 获取明细列表
    delItemDetails, // 删除项目的检验明细
    saveItemDetailed, // 新增项目明细的最大最小值
  } from "@/api/qc/qc.js"
  import Chooselist from '@/views/modules/common/Chooselist_eam'
  import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'
  import qcUpload from "./qc_upload";
  export default {
    components: {
      Chooselist,
      qcUpload
    },
    watch: {

    },
    data () {
      return {
        // 是否收藏
        favorite: false,
        // 导出 start
        exportData: [],
        exportName: "根据物料设置检验模板" + this.dayjs().format('YYYYMMDDHHmmss'),
        exportHeader: ["根据物料设置检验模板"],
        exportFooter: [],
        exportList:[],
        // 导出 end
        tagNo:'',
        searchData: {
          site: this.$store.state.user.site,
          templateId: '',
          templateName: '',
          inspectionTypeNo: '',
          page: 1,
          limit: 10,
        },
        options: [],
        objects: [],
        height: 200,
        pageIndex: 1,
        pageSize: 100,
        totalPage: 0,
        modalFlag:false,
        modalDisableFlag:false,
        modalData:{
          flag:'',
          site: this.$store.state.user.site,
          templateId:'',
          templateName:'',
          templateRemark: '',
          templateType: '',
          templateVersion: '',
          samplingProgrammeNo: '',
          samplingProgrammeDesc: '',
          inspectionTypeNo: '',
          inspectionCycle: '',
          createTime: '',
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
          samplingLevelNo: '',
          samplingLevelDesc: '',
          aql: '',
          ac: '',
          re: '',
          defaultSamplingQuantity: '',
          defaultSamplingProportion: '',
        },
        detailData:{
          site: this.$store.state.user.site,
          templateId:'',
          templateName:'',
          templateRemark: '',
          templateType: '',
          templateVersion: '',
          samplingProgrammeNo: '',
          samplingProgrammeDesc: '',
          inspectionTypeNo: '',
          inspectionCycle: '',
          createTime: '',
          createBy: this.$store.state.user.name,
          samplingLevelNo: '',
          samplingLevelDesc: '',
          aql: '',
          ac: '',
          re: '',
          itemNo:'',
          itemDesc:'',
          itemType:'D',
        },
        columnList: [
          {
            columnProp: 'templateId',
            headerAlign: "center",
            align: "center",
            columnLabel: '检验模板编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'templateName',
            headerAlign: "center",
            align: "center",
            columnLabel: '检验模板名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'samplingProgrammeNo',
            headerAlign: "center",
            align: "center",
            columnLabel: '抽样方案',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'samplingLevelDesc',
            headerAlign: "center",
            align: "center",
            columnLabel: '检验水平',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'inspectionCycle',
            headerAlign: "center",
            align: "center",
            columnLabel: '检验周期(h)',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'defaultSamplingQuantity',
            headerAlign: "center",
            align: "center",
            columnLabel: '默认抽样数量',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'defaultSamplingProportion',
            headerAlign: "center",
            align: "center",
            columnLabel: '默认抽样比例',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'aql',
            headerAlign: "center",
            align: "center",
            columnLabel: 'AQL',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'ac',
            headerAlign: "center",
            align: "center",
            columnLabel: 'AC',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 're',
            headerAlign: "center",
            align: "center",
            columnLabel: 'RE',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'inspectionTypeName',
            headerAlign: "center",
            align: "center",
            columnLabel: '检验类型',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'templateRemark',
            headerAlign: "center",
            align: "center",
            columnLabel: '检验模板备注',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'templateVersion',
            headerAlign: "center",
            align: "center",
            columnLabel: '版本号',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'createTime',
            headerAlign: "center",
            align: "center",
            columnLabel: '创建时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'createBy',
            headerAlign: "center",
            align: "center",
            columnLabel: '创建人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'updateDate',
            headerAlign: 'center',
            align: 'center',
            columnLabel: '更新时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
          {
            columnProp: 'updateBy',
            headerAlign: 'center',
            align: 'center',
            columnLabel: '更新人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
          },
        ],
        detailModelFlag:false,
        detailList: [],
        dataListLoading: false,
        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: "center",
            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:[],
        itemListRow1:{},
        itemListRow2:{},
        itemSelections1: [],
        itemSelections2: [],
        searchForm: {
          objectID: '',
          objectDesc: ''
        },
        rules:{
          templateNameType:[
            {
              required: true,
              message: ' ',
              trigger: 'change'
            }
          ],
          inspectionTypeNoType:[
            {
              required: true,
              message: ' ',
              trigger: 'change'
            }
          ],
          samplingProgrammeNoType:[
            {
              required: true,
              message: ' ',
              trigger: 'change'
            }
          ],
          samplingProgrammeDescType:[
            {
              required: true,
              message: ' ',
              trigger: 'change'
            }
          ],
          samplingLevelNoType:[
            {
              required: true,
              message: ' ',
              trigger: 'change'
            }
          ],
          samplingLevelDescType:[
            {
              required: true,
              message: ' ',
              trigger: 'change'
            }
          ],
        }
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.height = window.innerHeight - 210
      })
    },
    created () {
      this.getDataList()
      this.InspectionTypeSearch()
      this.favoriteIsOk()
    },
    methods: {
      /**
       *  自适应
       * @param label
       * @param prop
       * @returns {string}
       */
      flexColumnWidth (label, prop) {
        // 1.获取该列的所有数据
        const arr = this.dataList.map(x => x[prop])
        arr.push(label) // 把每列的表头也加进去算
        // 2.计算每列内容最大的宽度 + 表格的内间距（依据实际情况而定）
        return (this.getMaxLength(arr) + 25) + 'px'
      },
      getTextWidth (str) {
        let width = 0
        const html = document.createElement('span')
        html.innerText = str
        html.className = 'getTextWidth'
        document.querySelector('body').appendChild(html)
        width = document.querySelector('.getTextWidth').offsetWidth
        document.querySelector('.getTextWidth').remove()
        return width
      },
      getMaxLength (arr) {
        return arr.reduce((acc, item) => {
          if (item) {
            const calcLen = this.getTextWidth(item)
            if (acc < calcLen) {
              acc = calcLen
            }
          }
          return acc
        }, 0)
      },

      // 查询检验类型
      InspectionTypeSearch(){
        InspectionTypeSearch().then(({data}) => {
          if (data.code === 0) {
            this.options = data.rows
          }
        })
      },
      // 查询设备
      objectSearch(){
        objectSearch().then(({data}) => {
          if (data.code === 0) {
            this.objects = data.rows
          }
        })
      },

      // 客户
      FilterEntityName(queryString, cb) {
        let objects2 = this.objects;
        let results = queryString ? objects2.filter(this.createFilter(queryString)) : objects2;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      // 只要该输入内容的都匹配
      createFilter(queryString) {
        return (res) => {
          return (res.idAndDesc.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
        };
      },
      // 最终选择的数据
      handleSelect(val){
        console.log(val)
        // this.searchForm.objectID = val.objectID
      },
      // 点击clearable清空小图标按钮以后，继续重新在输入框中输入数据，querySearch会触发，但是cb函数不会触发
      // 这样的话就会出现发请求了，也获取数据了，但是input框的输入建议下拉框不呈现在页面上的问题，所以解决方法就是
      // 只要用户点击了clearable清空按钮以后，就让当前获取焦点的输入框失去焦点，回到最初状态，一切重新开始
      blurForBug(){
        document.activeElement.blur()
      },

      // 清空搜索栏
      doEmpty(){
        this.searchData = {
          site: this.$store.state.user.site,
          templateId: '',
          templateName: '',
          inspectionTypeNo: '',
          page: 1,
          limit: 10,
        }
      },
      // 获取基础数据列表S
      getBaseList (val,type) {
        this.tagNo = val
        this.$nextTick(() => {
          let strVal = ''
          if (val === 1051) {
            strVal = this.modalData.samplingProgrammeNo
            this.$refs.baseList.init(val, strVal)
          }
          if (val === 1048) {
            strVal = this.detailData.samplingLevelNo
            this.$refs.baseList.init(val, strVal)
          }
        })
      },
      /* 列表方法的回调 */
      getBaseData (val) {
        if (this.tagNo === 1051) {
          this.modalData.samplingProgrammeNo = val.sampling_programme_no
          this.modalData.samplingProgrammeDesc = val.sampling_programme_desc
        }
        if (this.tagNo === 1048) {
          this.modalData.samplingLevelNo = val.sampling_level_no
          this.modalData.samplingLevelDesc = val.sampling_level_desc
        }
      },
      // 获取数据列表
      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
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      addModal(){
        this.modalData = {
          flag: '1',
          site: this.$store.state.user.site,
          templateId: '',
          templateName: '',
          templateRemark: '',
          templateType: '',
          templateVersion: '',
          samplingProgrammeNo: '',
          samplingProgrammeDesc: '',
          inspectionTypeNo: '',
          inspectionCycle: '',
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
          samplingLevelNo: '',
          samplingLevelDesc: '',
          aql: '',
          ac: '',
          re: ''
        };
        this.modalDisableFlag = false;
        this.modalFlag = true;
      },
      updateModal(row){
        this.modalData = {
          flag:'2',
          site: this.$store.state.user.site,
          templateId: row.templateId,
          templateName: row.templateName,
          templateRemark: row.templateRemark,
          templateType: row.templateType,
          templateVersion: row.templateVersion,
          samplingProgrammeNo: row.samplingProgrammeNo,
          samplingProgrammeDesc: row.samplingProgrammeDesc,
          inspectionTypeNo: row.inspectionTypeNo,
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
          samplingLevelNo: row.samplingLevelNo,
          samplingLevelDesc: row.samplingLevelDesc,
          inspectionCycle: row.inspectionCycle,
          aql: row.aql,
          ac: row.ac,
          re: row.re,
          defaultSamplingQuantity: row.defaultSamplingQuantity,
          defaultSamplingProportion: row.defaultSamplingProportion
        };
        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.templateName == '' || this.modalData.templateName == null) {
          this.$alert('请输入检验模板名称！', '错误', {
            confirmButtonText: '确定'
          })
          return false
        }
        if (this.modalData.samplingProgrammeNo == '' || this.modalData.samplingProgrammeNo == null) {
          this.$alert('请选择抽检方案！', '错误', {
            confirmButtonText: '确定'
          })
          return false
        }
        if (this.modalData.inspectionTypeNo == '' || this.modalData.inspectionTypeNo == null) {
          this.$alert('请选择检验类型！', '错误', {
            confirmButtonText: '确定'
          })
          return false
        }
        if (this.modalData.samplingLevelNo == '' || this.modalData.samplingLevelNo == null) {
          this.$alert('请选择检验水平！', '错误', {
            confirmButtonText: '确定'
          })
          return false
        }
        if ((this.modalData.defaultSamplingQuantity == '' || this.modalData.defaultSamplingQuantity == null) && (this.modalData.defaultSamplingProportion == '' || this.modalData.defaultSamplingProportion == null)) {
          this.$alert('请输入 默认抽样数量 或者 默认抽样比例！', '错误', {
            confirmButtonText: '确定'
          })
          return false
        }
        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.templateId = row.templateId
        this.detailData.templateName = row.templateName
        templateDetailsSearch(this.detailData).then(({data}) => {
          this.detailList = data.rows
          this.objectSearch()
        })
        this.detailModelFlag = true;
      },
      // 保存模板项目
      saveDetail(){
        for (let i = 0; i < this.detailList.length; i++) {
          if (this.detailList[i].objectID != null){
            this.detailList[i].objectID = this.detailList[i].objectID.split('_')[0];
          }
          saveItemDetailed(this.detailList[i]).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: '确定'
              }).then(() => {
                return false
              })
            }
          })
        }
      },
      // 快速新增
      addFastModal(){
        this.itemSelections1 = null
        this.itemSelections2 = null
        getItemList(this.detailData).then(({data}) => {
          this.itemList1 = data.row1;
          this.itemList2 = data.row2;
        })
        this.fastAddFlag = true;
      },
      // clickItem1(row){
      //   this.itemListRow1 = JSON.parse(JSON.stringify(row));
      // },
      // clickItem2(row){
      //   this.itemListRow2 = JSON.parse(JSON.stringify(row));
      // },
      // 可选项目
      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.$alert("请选择可选项目！", '提示', {
            confirmButtonText: '确定'
          })
          return false;
        }
        let inData = {
          templateId: this.detailData.templateId,
          templateName: this.detailData.templateName,
          // itemNo: this.itemListRow1.itemNo,
          // itemDesc: this.itemListRow1.itemDesc,
          itemList: this.itemSelections1,
          itemType: this.detailData.itemType,
        }
        addItemDetails(inData).then(({data}) => {
          if (data && data.code == 0) {
            getItemList(this.detailData).then(({data}) => {
              this.itemList1 = data.row1;
              this.itemList2 = data.row2;
            })
            this.itemSelections1 = []
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      },
      // 删除明细
      deleteItem(){
        if(this.itemSelections2 == null || this.itemSelections2.length == 0){
          this.$alert("请选择已有项目！", '提示', {
            confirmButtonText: '确定'
          })
          return false;
        }
        let inData = {
          templateId: this.detailData.templateId,
          templateName: this.detailData.templateName,
          // itemNo: this.itemListRow2.itemNo,
          // itemDesc:this.itemListRow2.itemDesc,
          itemList: this.itemSelections2,
          itemType:this.detailData.itemType,
        }
        delItemDetails(inData).then(({data}) => {
          if (data && data.code === 0) {
            getItemList(this.detailData).then(({data}) => {
              this.itemList1 = data.row1;
              this.itemList2 = data.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(() => {
        })
      },

      // 校验用户是否收藏
      favoriteIsOk() {
        let userFavorite = {
          userId: this.$store.state.user.id,
          languageCode: this.$i18n.locale
        }
        console.log(this.$route.meta.menuId)
        userFavoriteList(userFavorite).then(({data}) => {
          for (let i = 0; i < data.list.length; i++) {
            // let flag=false;
            if(this.$route.meta.menuId==data.list[i].menuId){
              this.favorite = true
              // flag=true;
            }
          }
        })
      },
      // 收藏 OR 取消收藏
      favoriteFunction() {
        let userFavorite = {
          userId: this.$store.state.user.id,
          functionId: this.$route.meta.menuId,
        }
        if (this.favorite) {
          // 取消收藏
          // this.$confirm(`确定取消收藏`, '提示', {
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // }).then(() => {
            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
          })
        }
      },

      //导出excel
      async createExportData() {
        this.searchData.limit = -1
        this.searchData.page = 1
        await templateSearch(this.searchData).then(({data}) => {
          this.exportList= data.page.list;
        })
        return this.exportList;
      },
      startDownload() {
        //  this.exportData = this.dataList
      },
      finishDownload() {

      },
      fields() {
        let json = "{"
        this.columnList.forEach((item, index) => {
          if (index == this.columnList.length - 1) {
            json += "\"" + item.columnLabel + "\"" + ":" + "\"" + item.columnProp + "\""
          } else {
            json += "\"" + item.columnLabel + "\"" + ":" + "\"" + item.columnProp + "\"" + ","
          }
        })
        json += "}"
        let s = eval("(" + json + ")")
        return s
      },
      // 导出 end

      // 导入
      qcUpload(){
        let currentData = {
          flag: 'template',
          createBy: this.$store.state.user.name,
          site: this.$store.state.user.site,
        };
        //打开组件 去做新增业务
        this.$nextTick(() => {
          this.$refs.qcUpload.init(currentData);
        })
      },

    }
  }
</script>
<style scoped>
/deep/ .el-autocomplete-suggestion {
  width: auto!important;
}
</style>
