<template>
  <div class="mod-config">
    <el-form :inline="true" label-position="top">
      <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.objectID" clearable style="width: 100px"></el-input>
      </el-form-item>
      <el-form-item label="设备名称">
        <el-input v-model="searchData.objectDesc" clearable style="width: 150px"></el-input>
      </el-form-item>
      <el-form-item label="资产编码">
        <el-input v-model="searchData.assetNo" clearable style="width: 100px"></el-input>
      </el-form-item>
      <el-form-item label="设备分类名称">
        <el-input v-model="searchData.familyDesc" clearable style="width: 100px"></el-input>
      </el-form-item>
      <el-form-item label="设备分组名称">
        <el-input v-model="searchData.groupDesc" clearable style="width: 100px"></el-input>
      </el-form-item>
    </el-form>
    <el-form :inline="true" label-position="top" :model="searchData">
      <el-form-item label="所属部门名称">
        <el-input v-model="searchData.deptName" clearable style="width: 100px"></el-input>
      </el-form-item>
      <el-form-item label="文件名称">
        <el-input v-model="searchData.fileName" clearable style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="文件类型">
        <el-select v-model="searchData.orderRef3" clearable style="width: 80px">
          <el-option label="SOP-SP" value="SOP-SP"></el-option>
          <el-option label="other" value="other"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="' '">
        <el-button v-if="!authSearch" @click="getDataList()">查询</el-button>
        <download-excel
          :fields="fields()"
          :data="exportData"
          type="xls"
          :name="exportName"
          :header="exportHeader"
          :footer="exportFooter"
          :fetch="createExportData"
          :before-generate="startDownload"
          :before-finish="finishDownload"
          worksheet="导出信息"
          class="el-button el-button--primary el-button--medium">
          {{ "导出" }}
        </download-excel>
      </el-form-item>
    </el-form>

    <el-table
      :height="height"
      :data="dataList"
      border
      style="width: 100%;">
      <el-table-column
        v-for="(item,index) in columnList" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden">{{ 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">
          <el-link v-if="!authDownload" style="cursor:pointer" @click="downloadFile(scope.row)">下载</el-link>
          <el-link v-if="!authPreview" style="cursor:pointer" @click="previewFile(scope.row)">预览</el-link>
          <el-link v-if="!authDelete" style="cursor:pointer" @click="deleteFile(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>
  </div>
</template>

<script>
  import {
    eamObjectSopListSearch,
    downLoadObjectFile
  } from "@/api/eam/eam_object_list.js"
  import {
    getSiteAndBuByUserName,
    deleteObjectFile,
  } from "@/api/eam/eam.js"
  import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'
  import {
    getTableDefaultListLanguage,
    getTableUserListLanguage,
  } from "@/api/table.js"

  export default {
    watch: {
      searchData: {
        deep: true,
        handler: function (newV, oldV) {
          this.searchData.objectID = this.searchData.objectID.toUpperCase()
        }
      },
    },
    data () {
      return {
        // 是否收藏
        favorite: false,
        // 导出 start
        exportData: [],
        exportName: "设备SOP清单" + this.dayjs().format('YYYYMMDDHHmmss'),
        exportHeader: ["设备SOP清单"],
        exportFooter: [],
        exportList: [],
        // 导出 end
        searchData: {
          site: '',
          buNo: '',
          buDesc: '',
          userName: this.$store.state.user.name,
          objectID: '',
          objectDesc: '',
          familyDesc: '',
          groupDesc: '',
          deptName: '',
          assetNo: '',
          orderRef3: '',
          page: 1,
          limit: 10
        },
        height: 200,
        pageIndex: 1,
        pageSize: 20,
        totalPage: 0,
        dataList: [],
        dataListSelections: [],
        // 展示列集
        columnList: [
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1Bu',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'buDesc',
            headerAlign: "center",
            align: 'left',
            columnLabel: 'BU',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 80,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1ObjectID',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'objectID',
            headerAlign: "center",
            align: 'left',
            columnLabel: '设备编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1ObjectDesc',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'objectDesc',
            headerAlign: "center",
            align: "left",
            columnLabel: '设备名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 150,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1AssetNo',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'assetNo',
            headerAlign: "center",
            align: "left",
            columnLabel: '资产编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1FamilyDesc',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'familyDesc',
            headerAlign: "center",
            align: "left",
            columnLabel: '设备分类',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1GroupDesc',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'groupDesc',
            headerAlign: "center",
            align: 'left',
            columnLabel: '设备分组',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1LocationName',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'locationName',
            headerAlign: "center",
            align: "left",
            columnLabel: '设备区域',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1DeptName',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'deptName',
            headerAlign: "center",
            align: 'left',
            columnLabel: '所属部门',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 150,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1FileName',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'fileName',
            headerAlign: "center",
            align: 'left',
            columnLabel: '文件名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 300,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1CreatedBy',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'createdBy',
            headerAlign: "center",
            align: 'left',
            columnLabel: '上传人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1CreateDate',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'createDate',
            headerAlign: "center",
            align: 'center',
            columnLabel: '上传时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 150,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 101001012,
            serialNumber: '101001012Table1OrderRef3',
            tableId: "101001012Table1",
            tableName: "设备SOP清单",
            columnProp: 'orderRef3',
            headerAlign: "center",
            align: 'left',
            columnLabel: '文件类型',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
        ],
        userBuList: [],
        authSearch: false,
        authDownload: false,
        authPreview: false,
        authDelete: false,
        menuId: this.$route.meta.menuId,
      }
    },

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

    created () {
      // 按钮控制
      this.getButtonAuthData()
      // 获取用户的 site 和 bu
      this.getSiteAndBuByUserName()
      // 校验用户是否收藏
      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
          }
        })
      },

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

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

      // 预览
      previewFile (row) {
        // 预览文件
        let image = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
        let type = ''
        if (image.includes(row.fileType.toLowerCase())) {
          type = 'image/' + row.fileType
        }
        let video = ['mp4', 'avi', 'mov', 'wmv', 'flv']
        if (video.includes(row.fileType.toLowerCase())) {
          type = 'video/' + row.fileType
        }
        let txt = ['txt']
        if (txt.includes(row.fileType.toLowerCase())) {
          type = 'text/plain'
        }
        let office = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']
        if (office.includes(row.fileType.toLowerCase())) {
          if (row.fileType.toLowerCase() === 'doc' || row.fileType.toLowerCase() === 'docx') {
            type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
          } else if (row.fileType.toLowerCase() === 'ppt' || row.fileType.toLowerCase() === 'pptx') {
            type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
          } else {
            type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          }
        }
        let pdf = ['pdf']
        if (pdf.includes(row.fileType.toLowerCase())) {
          type = 'application/pdf'
        }
        downLoadObjectFile(row).then(({data}) => {
          const blob = new Blob([data], { type: type });
          // 创建URL来生成预览
          const fileURL = URL.createObjectURL(blob);
          // 在新标签页中打开文件预览
          const newTab = window.open(fileURL, '_blank')
        })
      },

      // 下载
      downloadFile (row) {
        downLoadObjectFile(row)
          .then(({data}) => {
            // 不限制文件下载类型
            const blob = new Blob([data], {type:'application/octet-stream;charset=utf-8'})
            // 下载文件名称
            const fileName = row.fileName
            // a标签下载
            const linkNode = document.createElement('a')
            linkNode.download = fileName // a标签的download属性规定下载文件的名称
            linkNode.style.display = 'none'
            linkNode.href = URL.createObjectURL(blob) // 生成一个Blob URL
            document.body.appendChild(linkNode)
            linkNode.click() // 模拟在按钮上的一次鼠标单击
            URL.revokeObjectURL(linkNode.href) // 释放URL 对象
            document.body.removeChild(linkNode)
          })
      },

      deleteFile (row) {
        let tempData = {
          id: row.id
        }
        this.$confirm('确定要删除此文件?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteObjectFile(tempData).then(({data}) => {
            if (data && data.code === 0) {
              this.getDataList()
              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
          })
        }
      },

      //导出excel
      async createExportData () {
        this.searchData.limit = -1
        this.searchData.page = 1
        await eamObjectSopListSearch(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
      },

      // 动态列开始 获取 用户保存的 格式列
      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;
            }
          } 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 downloadFlag = this.isAuth(this.menuId + ":download")
        let previewFlag = this.isAuth(this.menuId + ":preview")
        let deleteFlag = this.isAuth(this.menuId + ":delete")
        //处理页面的权限数据
        this.authSearch = !searchFlag
        this.authDownload = !downloadFlag
        this.authPreview = !previewFlag
        this.authDelete = !deleteFlag
      },
    }
  }
</script>
<style scoped>
.el-table /deep/ .cell{
  height: auto;
  line-height: 1.5;
}
</style>
