<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.itemNo" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="维保项目名称">
        <el-input v-model="searchData.itemDesc" clearable style="width: 200px"></el-input>
      </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" type="primary" @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>
<!--        <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
      v-loading="dataListLoading"
      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" v-if="scope.row.valueChooseFlag === 'Y' && !authChoose" @click="chooseModal(scope.row)">可选值</el-link>
          <el-link style="cursor: pointer" v-if="!authDelete" @click="deleteEamPropertiesItem(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="valueTypeDb" :rules="rules.valueTypeDbType">
          <el-select filterable v-model="modalData.valueTypeDb" style="width: 80px">
            <el-option label="文本" value="T"></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="itemNo" :rules="rules.itemNoType">
          <el-input v-model="modalData.itemNo" :disabled="modalDisableFlag" style="width: 130px"></el-input>
          <el-button type="primary" @click="itemNoChanged()">Next No</el-button>
        </el-form-item>
        <el-form-item label="维保项目名称" prop="itemDesc" :rules="rules.itemDescType">
          <el-input v-model="modalData.itemDesc" style="width: 416px"></el-input>
        </el-form-item>
      </el-form>
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;">
        <el-form-item label="参照值">
          <el-input v-model="modalData.defaultValue" style="width: 130px"></el-input>
        </el-form-item>
        <el-form-item label="最大值">
          <el-input v-model="modalData.maxValue" style="width: 130px"></el-input>
        </el-form-item>
        <el-form-item label="最小值">
          <el-input v-model="modalData.minValue" style="width: 129px"></el-input>
        </el-form-item>
      </el-form>
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;">
        <el-form-item label="维保方法说明">
          <el-input v-model="modalData.itemRemark" style="width: 255px"></el-input>
        </el-form-item>
        <el-form-item label="是否值可选" prop="valueChooseFlag" :rules="rules.valueChooseFlagType">
          <el-select filterable v-model="modalData.valueChooseFlag" style="width: 80px">
            <el-option label="是" value="Y"></el-option>
            <el-option label="否" value="N"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片必填">
          <input type="checkbox" value="Y" name="addWorkOrderRule" v-model="modalData.imageFlag"/>
        </el-form-item>
      </el-form>
      <el-footer style="height:40px;margin-top: 20px;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="chooseModalFlag" width="430px">
      <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-item :label="' '">
          <el-button  type="primary" @click="addChooseModal()">新增</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :height="300"
        :data="chooseTableData"
        border
        style="width: 100%">
        <el-table-column
          prop="availableValue"
          header-align="center"
          align="center"
          min-width="200"
          label="属性值">
        </el-table-column>
        <el-table-column
          prop=""
          header-align="center"
          align="center"
          min-width="100"
          label="操作">
          <template slot-scope="scope">
            <el-link style="cursor: pointer" @click="updateChooseModal(scope.row)">修改</el-link>
            <el-link style="cursor: pointer" @click="deleteItemAvailable(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="可选值维护" :close-on-click-modal="false" v-drag :visible.sync="itemModalFlag" width="215px" >
      <el-form :inline="true" label-position="top" style="margin-left: 22px;margin-top: -5px;" @submit.native.prevent>
        <el-form-item :label="'可选值'">
          <el-input v-model="itemData.availableValue" :type="itemFlag" style="width: 130px;"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="height:40px;margin-top: 20px;text-align:center">
        <el-button type="primary" @click="saveItemAvailable()">保存</el-button>
        <el-button type="primary" @click="itemModalFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>

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

        <!-- BU选择 -->
        <div style="margin-bottom: 15px;">
          <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"
            style="width: 100%;"
          >
            <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 {
    eamPropertiesItemSearch,
    eamPropertiesItemSave,
    eamPropertiesItemEdit,
    eamPropertiesItemDelete,
    searchItemAvailable,
    saveItemAvailable,
    deleteItemAvailable,
    getSiteAndBuByUserName,
    getRoleByUserName,
    uploadEamMaintenanceItemExcel, // 导入维保项目Excel
    downloadEamMaintenanceItemTemplate, // 下载维保项目导入模板
  } from "@/api/eam/eam.js"
  import {getTableDefaultListLanguage, getTableUserListLanguage} from "@/api/table.js"
  import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'
  import excel from "@/utils/excel-util.js";
  import {queryItemNo} from "../../../api/eam/eam";
  export default {
    watch: {
      searchData: {
        deep: true,
        handler: function (newV, oldV) {
          this.searchData.itemNo = this.searchData.itemNo.toUpperCase()
        }
      },
      itemData: {
        deep: true,
        handler: function (newV, oldV) {
          this.itemData.itemNo = this.itemData.itemNo.toUpperCase()
        }
      },
      modalData: {
        deep: true,
        handler: function (newV, oldV) {
          this.modalData.itemNo = this.modalData.itemNo.toUpperCase()
        }
      },
      chooseModalData: {
        deep: true,
        handler: function (newV, oldV) {
          this.chooseModalData.itemNo = this.chooseModalData.itemNo.toUpperCase()
        }
      }
    },
    data () {
      return {
        columnsProp:['createdBy','valueChooseFlag','updateBy'],
        // 是否收藏
        favorite: false,
        // 导出 start
        exportData: [],
        exportName: "维保项目" + this.dayjs().format('YYYYMMDDHHmmss'),
        exportHeader: ["维保项目"],
        exportFooter: [],
        exportList:[],
        // 导出 end
        searchData: {
          site: '',
          userName: this.$store.state.user.name,
          itemNo: '',
          itemDesc: '',
          buDesc: '',
          itemType: 'B',
          checkType: '',
          page: 1,
          limit: 10,
        },
        height: 200,
        pageIndex: 1,
        pageSize: 20,
        totalPage: 0,
        dataList: [],
        chooseTableData:[],
        dataListLoading: false,
        dataListSelections: [],
        modalFlag: false,
        modalDisableFlag: false,
        chooseModalFlag: false,
        itemModalFlag: false,
        itemFlag: 'text',
        itemData: {
          site: '',
          buNo: '',
          itemNo:'',
          valueNo:'',
          availableValue:'',
          itemType:'B',
          createdBy: this.$store.state.user.name
        },
        modalData: {
          flag:'',
          itemNo:'',
          itemDesc:'',
          valueTypeDb:'',
          defaultValue:'',
          valueChooseFlag:'',
          createdBy:this.$store.state.user.name,
          maxValue:'',
          minValue:'',
          itemRemark:'',
          itemType:'B',
          updateBy: this.$store.state.user.name,
          imageFlag: '',
          checkType: ''
        },
        departmentList: [],
        // 展示列集
        columnList: [
          {
            userId: this.$store.state.user.name,
            functionId: 101003001,
            serialNumber: '101003001Table1BuDesc',
            tableId: "101003001Table1",
            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: 101003001,
            serialNumber: '101003001Table1ItemNo',
            tableId: "101003001Table1",
            tableName: "维保项目表",
            columnProp: 'itemNo',
            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: 101003001,
            serialNumber: '101003001Table1ItemDesc',
            tableId: "101003001Table1",
            tableName: "维保项目表",
            columnProp: 'itemDesc',
            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: 101003001,
            serialNumber: '101003001Table1ItemRemark',
            tableId: "101003001Table1",
            tableName: "维保项目表",
            columnProp: 'itemRemark',
            headerAlign: "center",
            align: "left",
            columnLabel: '维保方法说明',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 450,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003001,
            serialNumber: '101003001Table1ValueType',
            tableId: "101003001Table1",
            tableName: "维保项目表",
            columnProp: 'valueType',
            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: 101003001,
            serialNumber: '101003001Table1DefaultValue',
            tableId: "101003001Table1",
            tableName: "维保项目表",
            columnProp: 'defaultValue',
            headerAlign: "center",
            align: "right",
            columnLabel: '参照值',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003001,
            serialNumber: '101003001Table1MaxValue',
            tableId: "101003001Table1",
            tableName: "维保项目表",
            columnProp: 'maxValue',
            headerAlign: "center",
            align: "right",
            columnLabel: '最大值',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003001,
            serialNumber: '101003001Table1MinValue',
            tableId: "101003001Table1",
            tableName: "维保项目表",
            columnProp: 'minValue',
            headerAlign: "center",
            align: "right",
            columnLabel: '最小值',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101003001,
            serialNumber: '101003001Table1ValueChooseFlag',
            tableId: "101003001Table1",
            tableName: "维保项目表",
            columnProp: 'valueChooseFlag',
            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: 101003001,
            serialNumber: '101003001Table1ImageFlag',
            tableId: "101003001Table1",
            tableName: "维保项目表",
            columnProp: 'imageFlag',
            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: 101003001,
            serialNumber: '101003001Table1CreatedDate',
            tableId: "101003001Table1",
            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: 101003001,
            serialNumber: '101003001Table1CreatedBy',
            tableId: "101003001Table1",
            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: 101003001,
            serialNumber: '101003001Table1UpdateDate',
            tableId: "101003001Table1",
            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: 101003001,
            serialNumber: '101003001Table1UpdateBy',
            tableId: "101003001Table1",
            tableName: "维保项目表",
            columnProp: 'updateBy',
            headerAlign: "center",
            align: "center",
            columnLabel: '更新人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
        ],
        levelList: [],
        chooseModalData: {
          site: '',
          buNo: '',
          itemNo: '',
          itemDesc: '',
          itemType:'B',
          valueTypeDb:'',
        },
        rules: {
          itemNoType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          itemDescType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          valueTypeDbType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          valueChooseFlagType:[
            {
              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,
        authChoose: 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)
      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
          }
        })
      },

      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },

      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },

      // 获取数据列表
      getDataList () {
        this.searchData.limit = this.pageSize
        this.searchData.page = this.pageIndex
        eamPropertiesItemSearch(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
        })
      },

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

      //导出excel
      // async createExportData () {
      //   await eamPropertiesItemSearch(this.searchData).then(({data}) => {
      //     this.exportList = data.rows
      //   })
      //   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
      // },

      addModal () {
        this.modalData = {
          bu: this.userBuList[0].buNo,
          site: '',
          flag: '1',
          itemNo: '',
          itemDesc: '',
          valueTypeDb: 'T',
          defaultValue: '',
          valueChooseFlag: 'N',
          createdBy: this.$store.state.user.name,
          maxValue: '',
          minValue: '',
          itemRemark: '',
          itemType: 'B',
          updateBy: this.$store.state.user.name,
          imageFlag: '',
          checkType: this.userRoleList.length > 0 ? this.userRoleList[0].roleNo : 'R022',
        }
        this.modalDisableFlag = false
        this.modalFlag = true
      },

      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
      },

      updateModal (row) {
        this.modalData = {
          site: row.site,
          bu: row.site + '_' + row.buNo,
          flag: '2',
          itemNo: row.itemNo,
          itemDesc: row.itemDesc,
          valueTypeDb: row.valueTypeDb,
          defaultValue: row.defaultValue,
          valueChooseFlag: row.valueChooseFlag,
          maxValue: row.maxValue,
          minValue: row.minValue,
          itemRemark: row.itemRemark,
          itemType: 'B',
          updateBy: this.$store.state.user.name,
          imageFlag: row.imageFlag,
          checkType: row.checkType
        }
        this.modalDisableFlag = true
        this.modalFlag = true
      },

      // 删除
      deleteEamPropertiesItem (row) {
        this.$confirm(`是否删除这个维保项目?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          eamPropertiesItemDelete(row).then(({data}) => {
            if (data && data.code === 0) {
              this.getDataList()
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {}
              })
            } else {
              this.$alert(data.msg, '错误', {
                confirmButtonText: '确定'
              })
            }
          })
        })
      },
      itemNoChanged(){
        let param = {
          site: this.modalData.bu.split('_')[0],
          buNo: this.modalData.bu.split('_')[1],
          itemNo: this.modalData.itemNo,
          itemType: this.modalData.itemType
        }
        queryItemNo(param).then(({data}) => {
          if (data && data.code == 0 && data.length==5) {
            this.modalData.itemNo = data.data
          } else {
            this.$message.error(data.data)
          }
        })
      },

      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.itemNo === '' || this.modalData.itemNo == null) {
          this.$message.warning('请输入维保项目编码！')
          return
        }
        if (this.modalData.itemDesc === '' || this.modalData.itemDesc == null) {
          this.$message.warning('请输入维保项目名称！')
          return
        }
        let obj = document.getElementsByName('addWorkOrderRule');
        let s = '';
        for (let i = 0; i < obj.length; i++) {
          if (obj[i].checked) {
            s += obj[i].value + ','
          }
        }
        s = s.substring(0,s.length-1)
        this.modalData.imageFlag = s
        if(this.modalData.flag === '1'){
          eamPropertiesItemSave(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 {
          eamPropertiesItemEdit(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: '确定'
              })
            }
          })
        }
      },

      addChooseModal () {
        this.itemFlag = this.chooseModalData.valueTypeDb === 'T'?'text':'number'
        this.itemData = {
          site: this.chooseModalData.site,
          buNo: this.chooseModalData.buNo,
          itemNo: this.chooseModalData.itemNo,
          valueNo: 0,
          availableValue: '',
          itemType: 'B',
          createdBy: this.$store.state.user.name
        }
        this.itemModalFlag = true
      },

      updateChooseModal (row) {
        this.itemFlag = this.chooseModalData.valueTypeDb === 'T'?'text':'number'
        this.itemData = {
          site: row.site,
          buNo: row.buNo,
          itemNo: this.chooseModalData.itemNo,
          valueNo: row.valueNo,
          availableValue: row.availableValue,
          itemType: 'B',
          createdBy: row.createdBy
        }
        this.itemModalFlag = true
      },

      saveItemAvailable () {
        if (this.itemData.availableValue === ''||this.itemData.availableValue == null) {
          this.$message.warning('请输入可选值！')
          return
        }
        saveItemAvailable(this.itemData).then(({data}) => {
          if (data && data.code === 0) {
            searchItemAvailable(this.chooseModalData).then(({data}) => {
              this.chooseTableData = data.rows
            })
            this.itemModalFlag = false
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {}
            })
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      },

      deleteItemAvailable (row) {
        this.$confirm(`是否删除这个可选值?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteItemAvailable(row).then(({data}) => {
            if (data && data.code === 0) {
              searchItemAvailable(this.chooseModalData).then(({data}) => {
                this.chooseTableData = data.rows
              })
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {}
              })
            } else {
              this.$alert(data.msg, '错误', {
                confirmButtonText: '确定'
              })
            }
          })
        })
      },

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

      // 动态列开始 获取 用户保存的 格式列
      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;
            }
          } 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;
            }
          }
        })
      },

      //获取按钮的权限数据
      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")
        let chooseFlag = this.isAuth(this.menuId+":choose")
        //处理页面的权限数据
        this.authSearch = !searchFlag
        this.authSave = !saveFlag
        this.authUpdate = !updateFlag
        this.authDelete = !deleteFlag
        this.authChoose = !chooseFlag
      },

      // 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

        // 调用后端导入接口
        uploadEamMaintenanceItemExcel(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)'
        })

        // 使用axios直接请求，设置responseType为arraybuffer
        this.$http({
          url: this.$http.adornUrl('/pms/eam/downloadEamMaintenanceItemTemplate'),
          method: 'get',
          responseType: 'arraybuffer'  // 使用arraybuffer避免乱码
        }).then(response => {
          loading.close()

          // 创建Blob对象，指定正确的MIME类型
          const blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
          })

          // 验证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('模板下载成功')
        }).catch(error => {
          loading.close()
          console.error('模板下载失败:', error)
          this.$message.error('模板下载失败：' + (error.message || '未知错误'))
        })
      },

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

.simple-dialog >>> .el-dialog__body {
  padding: 20px 30px;
  max-height: calc(70vh - 120px);
  overflow-y: auto;
}

/* 上传拖拽区域大小调整 */
.upload-demo .el-upload-dragger {
  width: 100%;
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-demo .el-upload-dragger .el-icon-upload {
  margin-bottom: 10px;
}
</style>
