<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.codeNo" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="点检模板名称">
        <el-input v-model="searchData.codeDesc" clearable style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="在用">
        <el-select v-model="searchData.active" style="width: 80px">
          <el-option label="全部" value=""></el-option>
          <el-option label="是" value="Y"></el-option>
          <el-option label="否" value="N"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否被用">
        <el-select v-model="searchData.isUse" style="width: 80px">
          <el-option label="全部" value=""></el-option>
          <el-option label="是" value="Y"></el-option>
          <el-option label="否" value="N"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门">
        <el-select v-model="searchData.checkType" clearable style="width: 80px">
          <el-option label="生产" value="R022"></el-option>
          <el-option label="设备" value="R023"></el-option>
          <el-option label="质量" value="R024"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=" ">
        <el-button v-if="!authSearch" @click="getDataList()">查询</el-button>
        <el-button v-if="!authSave" type="primary" @click="addModal()">新增</el-button>
        <el-button type="primary" icon="el-icon-upload" @click="importExcel" style="margin-left: 2px">导入</el-button>
        <el-button @click="exportExcel()" type="primary" style="margin-left: 2px">{{'导出'}}</el-button>
        <el-button @click="exportDetailExcel()" type="primary" style="margin-left: 2px">{{'导出明细'}}</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&#45;&#45;primary el-button&#45;&#45;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">
          <el-link style="cursor: pointer" v-if="!authUpdate" @click="updateModal(scope.row)">修改</el-link>
          <el-link style="cursor: pointer" @click="detailModal(scope.row)">点检项目</el-link>
          <el-link style="cursor: pointer" v-if="!authDelete" @click="deletePropertiesModel(scope.row)">删除</el-link>
        </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="460px">
      <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: 230px">
            <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-item label="部门" prop="checkType">
          <el-select v-model="modalData.checkType" :disabled="modalDisableFlag" style="width: 80px">
            <el-option label="生产" value="R022"></el-option>
            <el-option label="设备" value="R023"></el-option>
            <el-option label="质量" value="R024"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否在用" prop="active" :rules="rules.activeType">
          <el-select filterable v-model="modalData.active" style="width: 80px">
            <el-option label="是" value="Y"></el-option>
            <el-option label="否" value="N"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;">
        <el-form-item label="点检模板编码" prop="codeNo" :rules="rules.codeNoType">
          <el-input v-model="modalData.codeNo" :disabled="modalDisableFlag" style="width: 140px"></el-input>
        </el-form-item>
        <el-form-item label="点检模板名称" prop="codeDesc" :rules="rules.codeDescType">
        <el-input v-model="modalData.codeDesc" style="width: 264px"></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="1155px">
      <el-form :inline="true" label-position="top">
        <el-form-item label="点检模板编码">
          <el-input v-model="detailData.codeNo" readonly style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item label="点检模板名称">
          <el-input v-model="detailData.codeDesc" readonly style="width: 173px"></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>
      <el-table
        :height="300"
        :data="detailList"
        border
        @row-click="itemClickRow"
        ref="detailTable"
        highlight-current-row
        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
          fixed="right"
          header-align="center"
          align="center"
          width="130"
          label="操作">
          <template slot-scope="scope">
            <a type="text" size="small" v-if="scope.row.valueChooseFlag === 'Y'" @click="chooseModal(scope.row)">可选值</a>
            <a type="text" size="small" @click="deleteModalDetails(scope.row)">删除项目</a>
          </template>
        </el-table-column>
      </el-table>
        <el-footer style="height:40px;margin-top: 20px;text-align:center">
          <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="1200px">
      <div style="font-size: 12px">
        <el-form :inline="true" label-position="top" :model="detailData">
          <el-form-item :label="'项目编码'">
            <el-input v-model="detailData.itemNo" style="width: 120px"></el-input>
          </el-form-item>
          <el-form-item :label="'项目名称'">
            <el-input v-model="detailData.itemDesc" style="width: 145px"></el-input>
          </el-form-item>
          <el-form-item :label="' '">
            <el-button type="primary" @click="queryTemplateItem()">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-container style="margin-top: 0px;">
        <el-main style="width: 450px;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"
              width="50">
            </el-table-column>
            <el-table-column
              prop="itemNo"
              header-align="center"
              align="left"
              min-width="80"
              label="项目编码">
            </el-table-column>
            <el-table-column
              prop="itemDesc"
              header-align="center"
              align="left"
              min-width="200"
              label="项目名称">
            </el-table-column>
            <el-table-column
              prop="itemRemark"
              header-align="center"
              align="left"
              min-width="200"
              label="方法说明">
            </el-table-column>
          </el-table>
        </el-main>
        <el-main style="width: 10px;padding: 1px">
          <div style="margin-top: 200px;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: 450px;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"
              width="50">
            </el-table-column>
            <el-table-column
              prop="itemNo"
              header-align="center"
              align="left"
              min-width="80"
              label="项目编码">
            </el-table-column>
            <el-table-column
              prop="itemDesc"
              header-align="center"
              align="left"
              min-width="200"
              label="项目名称">
            </el-table-column>
            <el-table-column
              prop="itemRemark"
              header-align="center"
              align="left"
              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>

    <el-dialog title="可选值" :close-on-click-modal="false" v-drag :visible.sync="chooseModalFlag" width="350px">
      <el-form :inline="true" label-position="top" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item label="点检项目名称:">
          <el-input v-model="chooseModalData.itemDesc" disabled style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item :label="'检测值类型'">
          <el-select filterable v-model="chooseModalData.valueTypeDb" disabled style="width: 120px">
            <el-option label="文本" value="T"></el-option>
            <el-option label="数字" value="N"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table
        :height="300"
        :data="chooseTableData"
        border
        style="width: 100%">
        <el-table-column
          prop="availableValue"
          header-align="center"
          align="left"
          min-width="200"
          label="属性值">
        </el-table-column>
      </el-table>
      <el-footer style="height:40px;margin-top: 10px;text-align:center">
        <el-button type="primary" @click="chooseModalFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>

    <Chooselist ref="baseList"  @getBaseData="getBaseData"></Chooselist>

    <!-- 导入对话框 -->
    <template>
      <el-dialog
        title="点检模板数据导入"
        :close-on-click-modal="false"
        :visible.sync="uploadDialogVisible"
        width="400px"
        top="12vh"
        class="simple-dialog"
        @close="handleUploadDialogClose"
      >
        <div class="download-area">
          <el-button type="primary" @click="downloadTemplate" size="medium" style="width: 40%;">
            <i class="el-icon-download"></i> 下载文件模板
          </el-button>
        </div>

        <!-- BU选择 -->
        <div class="bu-area">
          <el-form :inline="true" label-position="top" label-width="80px">
            <el-form-item label="BU">
              <el-select v-model="uploadBu" placeholder="请选择" style="width: 295px">
                <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;">
                {{ i.buDesc }}
              </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <!-- 文件上传 -->
        <div>
          <el-upload
            class="upload-demo"
            drag
            action="javascript:void(0);"
            ref="uploadFile"
            :on-change="handleFileChange"
            :auto-upload="false"
            :limit="1"
            accept=".xlsx,.xls"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </div>

        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="confirmUpload" size="medium">保存</el-button>
      <el-button @click="uploadDialogVisible = false" size="medium">关闭</el-button>
    </span>
      </el-dialog>
    </template>

  </div>
</template>

<script>
  import {
    eamPropertiesModelSearch,
    eamPropertiesModelSave,
    eamPropertiesModelEdit,
    eamPropertiesModelDelete,
    searchItemAvailable,
    searchModalDetails,
    saveModalDetails,
    deleteModalDetails, // 多选删除
    eamPropertiesItemSearch,
    getItemLists,
    deleteModalDetail, // 单删
    getSiteAndBuByUserName,
    getRoleByUserName,
    goUpItemEam,
    goDownItemEam,
    uploadEamPropertiesModelExcel, // 导入点检模板Excel
    downloadEamPropertiesModelTemplate, // 下载点检模板导入模板
  } from "@/api/eam/eam.js"
  import {getTableDefaultListLanguage, getTableUserListLanguage} from "@/api/table.js"
  import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'
  import Chooselist from '@/views/modules/common/Chooselist_eam'
  import excel from "@/utils/excel-util.js";
  export default {
    components: {
      Chooselist
    },
    watch: {
      searchData: {
        deep: true,
        handler: function (newV, oldV) {
          this.searchData.codeNo = this.searchData.codeNo.toUpperCase()
        }
      },
      itemData: {
        deep: true,
        handler: function (newV, oldV) {
          this.itemData.itemNo = this.itemData.itemNo.toUpperCase()
        }
      },
      modalData: {
        deep: true,
        handler: function (newV, oldV) {
          this.modalData.codeNo = this.modalData.codeNo.toUpperCase()
        }
      },
      detailData: {
        deep: true,
        handler: function (newV, oldV) {
          this.detailData.codeNo = this.detailData.codeNo.toUpperCase()
          this.detailData.itemNo = this.detailData.itemNo.toUpperCase()
        }
      }
    },
    data () {
      return {
        columnsProp:['createdBy','active','updateBy'],
        // 是否收藏
        favorite: false,
        // 导出 start
        exportData: [],
        exportName: "点检模板" + this.dayjs().format('YYYYMMDDHHmmss'),
        exportHeader: ["点检模板"],
        exportFooter: [],
        exportList:[],
        // 导出 end
        tagNo:'',
        searchData: {
          site: '',
          userName: this.$store.state.user.name,
          codeNo: '',
          codeDesc: '',
          buDesc: '',
          active:'Y',
          functionType:'A',
          isUse: '',
          checkType: '',
          page: 1,
          limit: 10,
        },
        height: 200,
        pageIndex: 1,
        pageSize: 20,
        totalPage: 0,
        modalFlag: false,
        modalDisableFlag: false,
        modalData: {
          flag: '',
          bu: '',
          codeNo: '',
          codeDesc: '',
          active: '',
          functionType: 'A',
          userId: this.$store.state.user.name,
          createdBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
          checkType: ''
        },
        detailData: {
          site: '',
          buNo: '',
          codeNo: '',
          codeDesc: '',
          functionType: 'A',
          itemNo: '',
          itemDesc: '',
          itemType: 'A',
          userId: this.$store.state.user.name,
          checkType: ''
        },
        columnList: [
          {
            userId: this.$store.state.user.name,
            functionId: 101002002,
            serialNumber: '101002002Table1BuDesc',
            tableId: "101002002Table1",
            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: 101002002,
            serialNumber: '101002002Table1CodeNo',
            tableId: "101002002Table1",
            tableName: "点检模板表",
            columnProp: 'codeNo',
            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: 101002002,
            serialNumber: '101002002Table1CodeDesc',
            tableId: "101002002Table1",
            tableName: "点检模板表",
            columnProp: 'codeDesc',
            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: 101002002,
            serialNumber: '101002002Table1Active',
            tableId: "101002002Table1",
            tableName: "点检模板表",
            columnProp: 'active',
            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: 101002002,
            serialNumber: '101002002Table1IsUse',
            tableId: "101002002Table1",
            tableName: "点检模板表",
            columnProp: 'isUse',
            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: 101002002,
            serialNumber: '101002002Table1CreatedDate',
            tableId: "101002002Table1",
            tableName: "点检模板表",
            columnProp: 'createdDate',
            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: 101002002,
            serialNumber: '101002002Table1CreatedBy',
            tableId: "101002002Table1",
            tableName: "点检模板表",
            columnProp: 'createdBy',
            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: 101002002,
            serialNumber: '101002002Table1UpdateDate',
            tableId: "101002002Table1",
            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: 101002002,
            serialNumber: '101002002Table1UpdateBy',
            tableId: "101002002Table1",
            tableName: "点检模板表",
            columnProp: 'updateBy',
            headerAlign: "center",
            align: "center",
            columnLabel: '更新人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
        ],
        detailModelFlag: false,
        detailList: [],
        chooseTableData: [],
        dataListSelections: [],
        chooseModalFlag: false,
        itemFlag: 'text',
        itemData: {
          itemNo:'',
          valueNo:'',
          availableValue:'',
          itemType:'A',
          createdBy: this.$store.state.user.name
        },
        dataList: [],
        departmentList: [],
        // 展示列集
        columnDetailList: [
          {
            userId: this.$store.state.user.name,
            functionId: 101002002,
            serialNumber: '101002002Table2ItemNo',
            tableId: "101002002Table2",
            tableName: "点检项目表",
            columnProp: 'itemNo',
            headerAlign: "center",
            align: "left",
            columnLabel: '点检项目编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 80,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101002002,
            serialNumber: '101002002Table2ItemDesc',
            tableId: "101002002Table2",
            tableName: "点检项目表",
            columnProp: 'itemDesc',
            headerAlign: "center",
            align: "left",
            columnLabel: '点检项目名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 107,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101002002,
            serialNumber: '101002002Table2ItemRemark',
            tableId: "101002002Table2",
            tableName: "点检项目表",
            columnProp: 'itemRemark',
            headerAlign: "center",
            align: "left",
            columnLabel: '点检方法说明',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 417,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101002002,
            serialNumber: '101002002Table2ValueType',
            tableId: "101002002Table2",
            tableName: "点检项目表",
            columnProp: 'valueType',
            headerAlign: "center",
            align: "center",
            columnLabel: '检测值类型',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 80,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101002002,
            serialNumber: '101002002Table2DefaultValue',
            tableId: "101002002Table2",
            tableName: "点检项目表",
            columnProp: 'defaultValue',
            headerAlign: "center",
            align: "right",
            columnLabel: '参照值',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 80,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101002002,
            serialNumber: '101002002Table2MaxValue',
            tableId: "101002002Table2",
            tableName: "点检项目表",
            columnProp: 'maxValue',
            headerAlign: "center",
            align: "right",
            columnLabel: '最大值',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 80,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101002002,
            serialNumber: '101002002Table2MinValue',
            tableId: "101002002Table2",
            tableName: "点检项目表",
            columnProp: 'minValue',
            headerAlign: "center",
            align: "right",
            columnLabel: '最小值',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 80,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101002002,
            serialNumber: '101002002TableValueChooseFlag',
            tableId: "101002002Table",
            tableName: "common",
            columnProp: 'valueChooseFlag',
            headerAlign: "center",
            align: "center",
            columnLabel: '是否值可选',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 80,
          },
        ],
        columnExport: [
          {
            userId: this.$store.state.user.name,
            functionId: 101003002,
            serialNumber: '101003002Table1BuDesc',
            tableId: "101003002Table1",
            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: 101003002,
            serialNumber: '101003002Table1CodeNo',
            tableId: "101003002Table1",
            tableName: "维保模板表",
            columnProp: 'codeNo',
            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: 101003002,
            serialNumber: '101003002Table1CodeDesc',
            tableId: "101003002Table1",
            tableName: "维保模板表",
            columnProp: 'codeDesc',
            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: 101003002,
            serialNumber: '101003002Table1Active',
            tableId: "101003002Table1",
            tableName: "维保模板表",
            columnProp: 'active',
            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: 101003002,
            serialNumber: '101003002Table1IsUse',
            tableId: "101003002Table1",
            tableName: "维保模板表",
            columnProp: 'isUse',
            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: 101003002,
            serialNumber: '101003002Table1CreatedDate',
            tableId: "101003002Table1",
            tableName: "维保模板表",
            columnProp: 'createdDate',
            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: 101003002,
            serialNumber: '101003002Table1CreatedBy',
            tableId: "101003002Table1",
            tableName: "维保模板表",
            columnProp: 'createdBy',
            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: 101003002,
            serialNumber: '101003002Table1UpdateDate',
            tableId: "101003002Table1",
            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: 101003002,
            serialNumber: '101003002Table1UpdateBy',
            tableId: "101003002Table1",
            tableName: "维保模板表",
            columnProp: 'updateBy',
            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: 101003002,
            serialNumber: '101003002Table2ItemNo',
            tableId: "101003002Table2",
            tableName: "维保项目表",
            columnProp: 'itemNo',
            headerAlign: "center",
            align: "left",
            columnLabel: '维保项目编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 82,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003002,
            serialNumber: '101003002Table2ItemDesc',
            tableId: "101003002Table2",
            tableName: "维保项目表",
            columnProp: 'itemDesc',
            headerAlign: "center",
            align: "left",
            columnLabel: '维保项目名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth:106,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003002,
            serialNumber: '101003002Table2ItemRemark',
            tableId: "101003002Table2",
            tableName: "维保项目表",
            columnProp: 'itemRemark',
            headerAlign: "center",
            align: "left",
            columnLabel: '维保方法说明',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 298,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003002,
            serialNumber: '101003002Table2ValueType',
            tableId: "101003002Table2",
            tableName: "维保项目表",
            columnProp: 'valueType',
            headerAlign: "center",
            align: "center",
            columnLabel: '检测值类型',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 70,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003002,
            serialNumber: '101003002Table2DefaultValue',
            tableId: "101003002Table2",
            tableName: "维保项目表",
            columnProp: 'defaultValue',
            headerAlign: "center",
            align: "right",
            columnLabel: '参照值',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 65,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003002,
            serialNumber: '101003002Table2MaxValue',
            tableId: "101003002Table2",
            tableName: "维保项目表",
            columnProp: 'maxValue',
            headerAlign: "center",
            align: "right",
            columnLabel: '最大值',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 65,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003002,
            serialNumber: '101003002Table2MinValue',
            tableId: "101003002Table2",
            tableName: "维保项目表",
            columnProp: 'minValue',
            headerAlign: "center",
            align: "right",
            columnLabel: '最小值',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 65,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003002,
            serialNumber: '101003002Table2ValueChooseFlag',
            tableId: "101003002Table2",
            tableName: "维保项目表",
            columnProp: 'valueChooseFlag',
            headerAlign: "center",
            align: "center",
            columnLabel: '是否值可选',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 70,
          }
        ],
        levelList: [],
        chooseModalData: {
          site: '',
          buNo: '',
          itemNo: '',
          itemDesc: '',
          itemType:'A',
          valueTypeDb:'',
        },
        currentRow:{

        },
        //---------快速添加----------
        fastAddFlag: false,
        itemList1: [],
        itemList2: [],
        itemListRow1: {},
        itemListRow2: {},
        itemSelections1: [],
        itemSelections2: [],
        rules: {
          codeNoType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          codeDescType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          activeType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          bu:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          checkType: [
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ]
        },
        userBuList: [],
        userRoleList: [],
        authSearch: false,
        authSave: false,
        authUpdate: false,
        authDelete: false,
        menuId: this.$route.meta.menuId,
        // 上传相关
        uploadDialogVisible: false,
        uploadFileName: '',
        uploadFile: null,
        uploadBu: '', // 上传时选择的BU
      }
    },

    mounted () {
      this.$nextTick(() => {
        this.height = window.innerHeight - 180
      })
    },

    created () {
      // 按钮控制
      this.getButtonAuthData()
      // 获取用户的 site 和 bu
      this.getSiteAndBuByUserName()
      // 获取用户的 role
      this.getRoleByUserName()
      // 校验用户是否收藏
      this.favoriteIsOk()
      // 动态列
      this.getTableUserColumn(this.$route.meta.menuId+'table1',1)
      this.getTableUserColumn(this.$route.meta.menuId+'table2',2)
      if (!this.authSearch) {
        // 获取数据列表
        this.getDataList()
      }
    },

    methods: {
      // 获取用户的bu
      getSiteAndBuByUserName () {
        let tempData = {
          username: this.$store.state.user.name,
        }
        getSiteAndBuByUserName(tempData).then(({data}) => {
          if (data.code === 0) {
            this.userBuList = data.rows
          }
        })
      },

      // 获取用户的 role
      getRoleByUserName () {
        let tempData = {
          username: this.$store.state.user.name,
        }
        getRoleByUserName(tempData).then(({data}) => {
          if (data.code === 0) {
            this.userRoleList = data.rows
          }
        })
      },

      // 校验用户是否收藏
      favoriteIsOk () {
        let 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
            }
          }
        })
      },

      // 收藏 OR 取消收藏
      favoriteFunction () {
        let 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
          })
        }
      },

      // 获取基础数据列表S
      getBaseList (val,type) {
        this.tagNo = val
        this.$nextTick(() => {
          let strVal = ''
          if (val === 1024) {
            strVal = this.detailData.itemNo
          }
          this.$refs.baseList.init(val, strVal)
        })
      },

      // 列表方法的回调
      getBaseData (val) {
        if (this.tagNo === 1024) {
          this.detailData.itemNo = val.ItemNo
          this.detailData.itemDesc = val.ItemDesc
        }
      },

      async exportExcel() {
        this.searchData.limit = -1
        this.searchData.page = 1
        excel.exportTable({
          url: "/pms/eam/eamPropertiesModelSearch",
          columnMapping:  this.columnList,//可以直接用table，不需要的列就剔除
          mergeSetting: [],//需要合并的列
          params: this.searchData,
          fileName: this.exportName+".xlsx",
          rowFetcher: res => res.data,
          columnFormatter: [],
          dropColumns: [],//需要剔除的列，例如dropColumns: ["netWeight"]，即剔除净重列
        });
      },
      async exportDetailExcel() {
        this.searchData.limit = -1
        this.searchData.page = 1
        excel.exportTable({
          url: "/pms/eam/exportEamPropertiesTemplateAndItem",
          columnMapping:  this.columnExport,//可以直接用table，不需要的列就剔除
          mergeSetting: [],//需要合并的列
          params: this.searchData,
          fileName: this.exportName+".xlsx",
          rowFetcher: res => res.data,
          columnFormatter: [],
          dropColumns: [],//需要剔除的列，例如dropColumns: ["netWeight"]，即剔除净重列
        });
      },

      //导出excel
      // async createExportData () {
      //   this.searchData.limit = -1
      //   this.searchData.page = 1
      //   await eamPropertiesModelSearch(this.searchData).then(({data}) => {
      //     this.exportList = data.page.list
      //   })
      //   return this.exportList
      // },
      // startDownload() {},
      // 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
      // },

      // 获取数据列表
      getDataList () {
        this.searchData.limit = this.pageSize
        this.searchData.page = this.pageIndex
        eamPropertiesModelSearch(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 = {
          site: '',
          bu: this.userBuList[0].buNo,
          flag: '1',
          codeNo: '',
          codeDesc: '',
          active: 'Y',
          functionType: 'A',
          userId: this.$store.state.user.name,
          createdBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
          checkType: this.userRoleList.length > 0 ? this.userRoleList[0].roleNo : 'R022',
        }
        this.modalDisableFlag = false
        this.modalFlag = true
      },

      updateModal (row) {
        this.modalData = {
          site: this.$store.state.user.site,
          flag: '2',
          bu: row.site + '_' + row.buNo,
          codeNo: row.codeNo,
          codeDesc: row.codeDesc,
          active: row.active,
          functionType: 'A',
          userId: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
          checkType: row.checkType
        }
        this.modalDisableFlag = true
        this.modalFlag = true
      },

      // 删除
      deletePropertiesModel (row) {
        this.$confirm(`是否删除这个点检模板?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          eamPropertiesModelDelete(row).then(({data}) => {
            if (data && data.code === 0) {
              this.getDataList()
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {}
              })
            } else {
              this.$alert(data.msg, '错误', {
                confirmButtonText: '确定'
              })
            }
          })
        })
      },

      saveData () {
        if (this.modalData.bu === '' || this.modalData.bu == null) {
          this.$message.warning('请选择BU！')
          return
        }
        if (this.modalData.checkType === '' || this.modalData.checkType == null) {
          this.$message.warning('请选择部门！')
          return
        }
        if (this.modalData.codeNo === '' || this.modalData.codeNo == null) {
          this.$message.warning('请输入点检模板编码！')
          return
        }
        if (this.modalData.codeDesc === '' || this.modalData.codeDesc == null) {
          this.$message.warning('请输入点检模板名称！')
          return
        }
        if (this.modalData.active === '' || this.modalData.active == null) {
          this.$message.warning('选择是否在用！')
          return
        }
        if (this.modalData.flag === '1') {
          eamPropertiesModelSave(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 {
          eamPropertiesModelEdit(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.codeNo = row.codeNo
        this.detailData.codeDesc = row.codeDesc
        this.detailData.checkType = row.checkType
        searchModalDetails(this.detailData).then(({data}) => {
          this.detailList = data.rows
        })
        this.detailModelFlag = true
      },

      itemNoBlur () {
        let inData = {
          site: this.$store.state.user.site,
          itemType: 'A',
          itemNo: this.detailData.itemNo
        }
        eamPropertiesItemSearch(inData).then(({data}) => {
         if (data.rows.length > 0) {
           this.detailData.itemDesc = data.rows[0].itemDesc
         }else {
           this.detailData.itemDesc = ''
         }
        })
      },

      deleteModalDetails (row) {
        this.$confirm(`是否删除这个点检项目?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteModalDetail(row).then(({data}) => {
            if (data && data.code === 0) {
              searchModalDetails(this.detailData).then(({data}) => {
                this.detailList = data.rows
              })
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {}
              })
            } else {
              this.$alert(data.msg, '错误', {
                confirmButtonText: '确定'
              })
            }
          })
        })
      },

      chooseModal (row) {
        this.chooseModalData.site = row.site
        this.chooseModalData.buNo = row.buNo
        this.chooseModalData.itemNo = row.itemNo
        this.chooseModalData.itemDesc = row.itemDesc
        this.chooseModalData.valueTypeDb = row.valueTypeDb
        searchItemAvailable(this.chooseModalData).then(({data}) => {
          this.chooseTableData = data.rows
        })
        this.chooseModalFlag = true
      },

      queryTemplateItem () {
        getItemLists(this.detailData).then(({data}) => {
          this.itemList1 = data.row1
          this.itemList2 = data.row2
        })
      },

      addFastModal () {
        this.itemSelections1 = null
        this.itemSelections2 = null
        getItemLists(this.detailData).then(({data}) => {
          this.itemList1 = data.row1
          this.itemList2 = data.row2
        })
        this.fastAddFlag = true
      },

      // 可选项目
      itemClickRow1 (row) {
        this.$refs.itemTable1.toggleRowSelection(row);
      },

      itemClickRow(row){
        this.currentRow= JSON.parse(JSON.stringify(row))
      },

      // 已有项目
      itemClickRow2 (row) {
        this.$refs.itemTable2.toggleRowSelection(row);
      },

      selectionItem1 (val) {
        this.itemSelections1 = val
      },

      selectionItem2 (val) {
        this.itemSelections2 = val
      },

      addItem () {
        if (this.itemSelections1 == null || this.itemSelections1.length === 0) {
          this.$message.warning('请选择可选项目！')
          return
        }
        let inData = {
          site: this.detailData.site,
          buNo: this.detailData.buNo,
          codeNo: this.detailData.codeNo,
          codeDesc: this.detailData.codeDesc,
          functionType: this.detailData.functionType,
          itemList: this.itemSelections1,
          itemType: this.detailData.itemType,
          userId: this.$store.state.user.name,
          checkType: this.detailData.checkType,
        }
        saveModalDetails(inData).then(({data}) => {
          if (data && data.code === 0) {
            getItemLists(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.$message.warning('请选择已有项目！')
          return
        }
        let inData = {
          site: this.detailData.site,
          buNo: this.detailData.buNo,
          codeNo: this.detailData.codeNo,
          codeDesc: this.detailData.codeDesc,
          functionType: this.detailData.functionType,
          itemList: this.itemSelections2,
          itemType: this.detailData.itemType,
          userId: this.$store.state.user.name
        }
        deleteModalDetails(inData).then(({data}) => {
          if (data && data.code === 0) {
            getItemLists(this.detailData).then(({data}) => {
              this.itemList1 = data.row1
              this.itemList2 = data.row2
            })
            this.itemSelections2 = []
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      },

      refreshDetailList () {
        searchModalDetails(this.detailData).then(({data}) => {
          this.detailList = data.rows
        })
      },

      goUp() {
        goUpItemEam(this.currentRow).then(({data}) => {
          if (data && data.code === 0) {
            searchModalDetails(this.detailData).then(({data}) => {
              this.detailList = data.rows
              for (let i = 0; i <this.detailList.length ; i++) {
                if(this.detailList[i].itemNo===this.currentRow.itemNo){
                  this.$refs.detailTable.setCurrentRow(this.detailList[i]);
                  this.currentRow=JSON.parse(JSON.stringify(this.detailList[i]))
                  this.$message.success('操作成功')
                }
              }
              //this.objectSearch()
            })
          }
        })

      },
      goDown() {
        goDownItemEam(this.currentRow).then(({data}) => {
          if (data && data.code === 0) {
            searchModalDetails(this.detailData).then(({data}) => {
              this.detailList = data.rows
              for (let i = 0; i <this.detailList.length ; i++) {
                if(this.detailList[i].itemNo===this.currentRow.itemNo){
                  this.$refs.detailTable.setCurrentRow(this.detailList[i]);
                  this.currentRow=JSON.parse(JSON.stringify(this.detailList[i]))
                  this.$message.success('操作成功')
                }
              }
            })
          }
        })

      },

      // 动态列开始 获取 用户保存的 格式列
      async getTableUserColumn (tableId, columnId) {
        let queryTableUser = {
          userId: this.$store.state.user.name,
          functionId: this.$route.meta.menuId,
          tableId: tableId,
          status: true,
          languageCode: this.$i18n.locale
        }
        await getTableUserListLanguage(queryTableUser).then(({data}) => {
          if (data.rows.length > 0) {
            switch (columnId) {
              case 1:
                this.columnList = data.rows
                break;
              case 2:
                this.columnDetailList = data.rows
                break;
            }
          } else {
            this.getColumnList(tableId, columnId)
          }
        })
      },

      // 获取 tableDefault 列
      async getColumnList (tableId, columnId) {
        let queryTable = {
          functionId: this.$route.meta.menuId,
          tableId: tableId,
          languageCode: this.$i18n.locale
        }
        await getTableDefaultListLanguage(queryTable).then(({data}) => {
          if (!data.rows.length == 0) {
            switch (columnId) {
              case 1:
                this.columnList = data.rows
                break;
              case 2:
                this.columnDetailList = data.rows
                break;
            }
          }
        })
      },

      //获取按钮的权限数据
      getButtonAuthData () {
        let searchFlag = this.isAuth(this.menuId+":search")
        let saveFlag = this.isAuth(this.menuId+":save")
        let updateFlag = this.isAuth(this.menuId+":update")
        let deleteFlag = this.isAuth(this.menuId+":delete")
        //处理页面的权限数据
        this.authSearch = !searchFlag
        this.authSave = !saveFlag
        this.authUpdate = !updateFlag
        this.authDelete = !deleteFlag
      },

      // Excel导入
      importExcel () {
        this.uploadDialogVisible = true
        this.uploadFileName = ''
        this.uploadFile = null
        this.uploadBu = '' // 清空BU选择
        // 清空el-upload组件的文件列表
        if (this.$refs.uploadFile) {
          this.$refs.uploadFile.clearFiles()
        }
      },

      // 文件选择变化
      handleFileChange (file) {
        this.uploadFile = file.raw
        this.uploadFileName = file.name
      },

      // 确认上传
      confirmUpload () {
        // 验证BU是否选择
        if (!this.uploadBu || this.uploadBu === '') {
          this.$message.warning('请先选择BU')
          return
        }

        if (!this.uploadFile) {
          this.$message.warning('请先选择文件')
          return
        }

        const formData = new FormData()
        formData.append('file', this.uploadFile)
        formData.append('createBy', this.$store.state.user.name)
        formData.append('site', this.uploadBu.split('_')[0]) // 从BU中提取site
        formData.append('buNo', this.uploadBu.split('_')[1]) // 从BU中提取buNo

        // 调用后端导入接口
        uploadEamPropertiesModelExcel(formData).then(({data}) => {
          if (data.code === 0) {
            this.$message.success(data.msg || '导入成功')
            this.uploadDialogVisible = false
            // 清空文件信息
            this.uploadFileName = ''
            this.uploadFile = null
            this.uploadBu = ''
            if (this.$refs.uploadFile) {
              this.$refs.uploadFile.clearFiles()
            }
            this.getDataList()
          } else {
            this.$message.error(data.msg || '导入失败')
          }
        }).catch((error) => {
          console.error('导入失败:', error)
          const errorMsg = (error.response && error.response.data && error.response.data.msg) || error.message || '未知错误'
          this.$message.error('导入失败: ' + errorMsg)
        })
      },

      // 下载模板
      downloadTemplate () {
        const loading = this.$loading({
          lock: true,
          text: '正在下载模板...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        // 使用原生XMLHttpRequest处理文件下载,避免axios拦截器干扰
        const xhr = new XMLHttpRequest()
        xhr.open('GET', this.$http.adornUrl('/pms/eam/downloadEamPropertiesModelTemplate'), true)
        xhr.responseType = 'blob'
        
        // 添加token
        const token = this.$cookie.get('token')
        if (token) {
          xhr.setRequestHeader('token', token)
        }
        
        xhr.onload = () => {
          loading.close()
          
          if (xhr.status === 200) {
            const blob = xhr.response
            
            // 验证Blob大小
            if (blob.size === 0) {
              this.$message.error('模板文件为空，请联系管理员')
              return
            }
            
            // 创建下载链接
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = '点检模板导入模板.xlsx'
            link.style.display = 'none'
            
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            
            // 释放URL对象
            setTimeout(() => {
              window.URL.revokeObjectURL(url)
            }, 100)
            
            this.$message.success('模板下载成功')
          } else {
            console.error('模板下载失败,状态码:', xhr.status)
            this.$message.error('模板下载失败：服务器错误')
          }
        }
        
        xhr.onerror = () => {
          loading.close()
          console.error('网络错误')
          this.$message.error('模板下载失败：网络错误')
        }
        
        xhr.send()
      },

      // 关闭上传对话框时清空文件
      handleUploadDialogClose () {
        this.uploadFileName = ''
        this.uploadFile = null
        this.uploadBu = '' // 清空BU选择
        if (this.$refs.uploadFile) {
          this.$refs.uploadFile.clearFiles()
        }
      },
    }
  }
</script>
<style scoped>
.el-table /deep/ .cell{
  height: auto;
  line-height: 1.5;
}
.simple-dialog >>> .el-dialog {
  border-radius: 8px;
}


/* body顶格 */
.simple-dialog >>> .el-dialog__body {
  padding: 0px 20px 10px 20px !important;
}


/* 内容不要额外缩进 */
.simple-dialog >>> .el-dialog__body > div {
  margin-left: 0 !important;
}


/* 下载区域 */
.download-area {
  margin-top: 0;
  margin-bottom: 0;
}


/* 下载按钮 */
.download-btn {
  width: 40%;
}


/* BU区域 */
.bu-area {
  margin-top: 0;
  margin-bottom: 5px;
}


/* BU label */
.simple-dialog >>> .el-form-item__label {
  padding-bottom: 0;
  line-height: 22px;
}


/* 去掉form自带间距 */
.simple-dialog >>> .el-form-item {
  margin-bottom: 0;
}


/* 上传区域 */
.upload-demo {
  margin-top: 0;
}


/* 上传框 */
.upload-demo .el-upload-dragger {
  width: 100%;
  height: 150px;
}

.simple-dialog >>> .el-dialog__body {
  padding-left: 10px !important;
  padding-right: 0 !important;
}
</style>
