<template>
  <div class="mod-config">
 <!--    <div>-->
<!--        <span @click="favoriteFunction()">-->
<!--         <icon-svg :name="favorite?'xiangqufill':'xiangqu'" class="sl-svg"></icon-svg>-->
<!--        </span>-->
<!--    </div>-->
    <el-form :inline="true" label-position="top" :model="searchData" @keyup.enter.native="getDataList()">
      <el-form-item :label="'故障编码'">
        <el-input v-model="searchData.objectID" style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'故障名称'">
        <el-input v-model="searchData.objectDesc" style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'故障编码'">
        <el-input v-model="searchData.defectID" style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'故障名称'">
        <el-input v-model="searchData.defectDesc" style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'在用'">
        <el-select filterable v-model="searchData.active" style="width: 130px">
          <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-button v-if="!authSearch" @click="getDataList()">查询</el-button>
        <el-button v-if="!authSave" type="primary" @click="addModal()">新增</el-button>
        <download-excel
          :fields="fields()"
          :data="exportData"
          type="xls"
          :name="exportName"
          :header="exportHeader"
          :footer="exportFooter"
          :fetch="createExportData"
          :before-generate="startDownload"
          :before-finish="finishDownload"
          worksheet="导出信息"
          class="el-button el-button--primary el-button--medium">
          {{ "导出" }}
        </download-excel>
      </el-form-item>
    </el-form>
    <el-table
      :height="height"
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%;">
      <el-table-column
        v-for="(item,index) in columnList" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden"> {{ scope.row[item.columnProp] }}</span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="100"
        label="操作">
        <template slot-scope="scope">
          <a v-if="!authUpdate" type="text" size="small" @click="updateModal(scope.row)">修改</a>
          <a v-if="!authDelete" type="text" size="small" @click="deleteDefect(scope.row)">删除</a>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[20, 50, 100, 200, 500]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <el-dialog title="故障" :close-on-click-modal="false" v-drag :visible.sync="modalFlag" width="430px">
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item prop="objectID" :rules="rules.objectIdType">
          <span slot="label" style="" @click="getBaseList(200)"><a herf="#">设备编码</a></span>
          <el-input v-model="modalData.objectID" style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item label="设备名称:" prop="objectDesc" :rules="rules.objectDescType">
          <el-input v-model="modalData.objectDesc" disabled style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item label="是否在用:" prop="active" :rules="rules.activeType">
          <el-select filterable v-model="modalData.active" style="width: 120px">
            <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;margin-top: -5px;">
        <el-form-item prop="defectID" :rules="rules.defectIdType">
          <span slot="label" style="" @click="getBaseList(1033)"><a herf="#">故障编码</a></span>
          <el-input v-model="modalData.defectID" style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item label="故障名称:" prop="defectDesc" :rules="rules.defectDescType">
          <el-input v-model="modalData.defectDesc" disabled style="width: 150px"></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>

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

<script>
  import {
    eamObjectDefectSearch,
    eamObjectDefectSave,
    eamObjectDefectEdit,
    eamObjectDefectDelete,
  } from "@/api/eam/eam.js"
  import Chooselist from '@/views/modules/common/Chooselist_eam'
  import {
    getTableDefaultListLanguage,
    getTableUserListLanguage,
  } from "@/api/table.js"
  import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'

  export default {
    components: {
      Chooselist
    },
    watch: {
      searchData: {
        deep: true,
        handler: function (newV, oldV) {
          this.searchData.defectID = this.searchData.defectID.toUpperCase()
          this.searchData.objectID = this.searchData.objectID.toUpperCase()
        }
      },

      modalData: {
        deep: true,
        handler: function (newV, oldV) {
          this.modalData.defectID = this.modalData.defectID.toUpperCase()
          this.modalData.objectID = this.modalData.objectID.toUpperCase()
        }
      }
    },
    data () {
      return {
        // 是否收藏
        favorite: false,
        // 导出 start
        exportData: [],
        exportName: "设备故障原因" + this.dayjs().format('YYYYMMDDHHmmss'),
        exportHeader: ["设备故障原因"],
        exportFooter: [],
        exportList:[],
        // 导出 end
        tagNo:'',
        searchData: {
          site: this.$store.state.user.site,
          defectID: '',
          objectID: '',
          defectDesc:'',
          objectDesc:'',
          active: 'Y',
          page: 1,
          limit: 10,
        },
        height: 200,
        pageIndex: 1,
        pageSize: 50,
        totalPage: 0,
        dataList: [],
        dataListLoading: false,
        dataListSelections: [],
        modalFlag: false,
        modalDisableFlag: false,
        modalData: {
          flag: '',
          site: this.$store.state.user.site,
          defectID: '',
          objectID: '',
          active: '',
          id: '',
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
        },
        departmentList: [],
        // 展示列集
        columnList: [
          {
            userId: this.$store.state.user.name,
            functionId: 101001010,
            serialNumber: '101001010Table1ObjectID',
            tableId: "101001010Table1",
            tableName: "设备故障原因表",
            columnProp: 'objectID',
            headerAlign: "center",
            align: "left",
            columnLabel: '设备编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 168,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001010,
            serialNumber: '101001010Table1ObjectDesc',
            tableId: "101001010Table1",
            tableName: "设备故障原因表",
            columnProp: 'objectDesc',
            headerAlign: "center",
            align: "left",
            columnLabel: '设备名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 168,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001010,
            serialNumber: '101001010Table1DefectID',
            tableId: "101001010Table1",
            tableName: "设备故障原因表",
            columnProp: 'defectID',
            headerAlign: "center",
            align: "left",
            columnLabel: '故障编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 168,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001010,
            serialNumber: '101001010Table1DefectDesc',
            tableId: "101001010Table1",
            tableName: "设备故障原因表",
            columnProp: 'defectDesc',
            headerAlign: "center",
            align: "left",
            columnLabel: '故障名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 168,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001010,
            serialNumber: '101001010Table1Active',
            tableId: "101001010Table1",
            tableName: "设备故障原因表",
            columnProp: 'active',
            headerAlign: "center",
            align: "center",
            columnLabel: '在用',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 168,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001010,
            serialNumber: '101001010Table1CreateDate',
            tableId: "101001010Table1",
            tableName: "设备故障原因表",
            columnProp: 'createDate',
            headerAlign: "center",
            align: "center",
            columnLabel: '创建时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 168,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001010,
            serialNumber: '101001010Table1CreateBy',
            tableId: "101001010Table1",
            tableName: "设备故障原因表",
            columnProp: 'createBy',
            headerAlign: "center",
            align: "left",
            columnLabel: '创建人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 168,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001010,
            serialNumber: '101001010Table1UpdateDate',
            tableId: "101001010Table1",
            tableName: "设备故障原因表",
            columnProp: 'updateDate',
            headerAlign: "center",
            align: "center",
            columnLabel: '更新时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 168,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001010,
            serialNumber: '101001010Table1UpdateBy',
            tableId: "101001010Table1",
            tableName: "设备故障原因表",
            columnProp: 'updateBy',
            headerAlign: "center",
            align: "left",
            columnLabel: '更新人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 168,
          },
        ],
        levelList: [],
        rules: {
          objectIdType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          objectDescType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          defectIdType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          defectDescType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          activeType:[
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
        },
        authSearch: false,
        authSave: false,
        authUpdate: false,
        authDelete: false,
        menuId: this.$route.meta.menuId,
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.height = window.innerHeight - 210
      })
    },
    created () {
      // 按钮控制
      this.getButtonAuthData()
      this.favoriteIsOk()
      // 动态列
      this.getTableUserColumn(this.$route.meta.menuId+'table1',1)
      if (!this.authSearch) {
        // 获取数据列表
        this.getDataList()
      }
    },
    methods: {
      // 校验用户是否收藏
      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 === 200 ) {
            strVal = this.modalData.objectID
            this.$refs.baseList.init(val, strVal)
          }
          if (val === 1033) {
            strVal = this.modalData.defectID
            this.$refs.baseList.init(val, strVal)
          }
        })
      },

      /* 列表方法的回调 */
      getBaseData (val) {
        if (this.tagNo === 200) {
          this.modalData.objectID = val.ObjectID
          this.modalData.objectDesc = val.ObjectDesc
        }
        if (this.tagNo === 1033) {
          this.modalData.defectID = val.DefectID
          this.modalData.defectDesc = val.DefectDesc
        }
      },

      //导出excel
      async createExportData() {
        this.searchData.limit = -1
        this.searchData.page = 1
        await eamObjectDefectSearch(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
        eamObjectDefectSearch(this.searchData).then(({data}) => {
          if (data.code == 0) {
            this.dataList = data.page.list
            this.pageIndex = data.page.currPage
            this.pageSize = data.page.pageSize
            this.totalPage = data.page.totalCount
          }
          this.dataListLoading = false
        })
      },

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

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

      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },

      addModal () {
        this.modalData = {
          flag:'1',
          site: this.$store.state.user.site,
          defectID:'',
          defectDesc:'',
          objectID:'',
          objectDesc:'',
          active:'Y',
          id:0,
          createBy: this.$store.state.user.name,
          updateBy: this.$store.state.user.name,
        }
        this.modalDisableFlag = false
        this.modalFlag = true
      },
      updateModal (row) {
        this.modalData = {
          flag:'2',
          site: row.site,
          defectID:row.defectID,
          defectDesc:row.defectDesc,
          objectID:row.objectID,
          objectDesc:row.objectDesc,
          active:row.active,
          id:row.id,
          updateBy: this.$store.state.user.name,
        }
        this.modalDisableFlag = true
        this.modalFlag = true
      },

      // 删除
      deleteDefect (row) {
        this.$confirm(`是否删除这个设备故障?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'

        }).then(() => {
          eamObjectDefectDelete(row).then(({data}) => {
            if (data && data.code == '0') {
              this.getDataList()
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                }
              })
            } else {
              this.$alert(data.msg, '错误', {
                confirmButtonText: '确定'
              })
            }
          })
        }).catch(() => {
        })
      },

      saveData () {
        if (this.modalData.objectID == '' || this.modalData.objectID == null) {
          this.$alert('请选择设备编码！', '错误', {
            confirmButtonText: '确定'
          })
          return false
        }
        if (this.modalData.defectID == '' || this.modalData.defectID == null) {
          this.$alert('请选择故障编码！', '错误', {
            confirmButtonText: '确定'
          })
          return false
        }
        if (this.modalData.active == '' || this.modalData.active == null) {
          this.$alert('选择是否在用！', '错误', {
            confirmButtonText: '确定'
          })
          return false
        }
        if (this.modalData.flag=='1') {
          eamObjectDefectSave(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 {
          eamObjectDefectEdit(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: '确定'
              })
            }
          })
        }
      },

      // 动态列开始 获取 用户保存的 格式列
      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) {
            //this.columnList1 = []
            switch (columnId) {
              case 1:
                this.columnList = data.rows
                break;
              // case 2:
              //   this.detailColumnList = data.rows
              //   break;
              // case 3:
              //   this.columnList2 = data.rows
              //   break;
              // case 4:
              //   this.columnList3 = 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.detailColumnList = data.rows
              //   break;
              // case 3:
              //   this.columnList2 = data.rows
              //   break;
              // case 4:
              //   this.columnList3 = data.rows
              //   break;
            }
          } else {
            // this.showDefault = true.
          }
        })
      },

      //获取按钮的权限数据
      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
      },
    }
  }
</script>
<style scoped>
.el-table /deep/ .cell{
  height: auto;
  line-height: 1.5;
}
</style>
