<template>
  <div class="mod-config">
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" label-position="top" :model="queryForm" @keyup.enter.native="getDataList()">
          <el-form-item label="设备编码">
            <el-input v-model="queryForm.resourceId" clearable></el-input>
          </el-form-item>
          <el-form-item label="设备名称">
            <el-input v-model="queryForm.resourceDesc" clearable></el-input>
          </el-form-item>
          <el-form-item label="备品备件编码">
            <el-input v-model="queryForm.partNo" clearable></el-input>
          </el-form-item>
          <el-form-item label="备品备件名称">
            <el-input v-model="queryForm.partDescription" clearable></el-input>
          </el-form-item>
          <el-form-item label="BU">
            <el-select v-model="queryForm.buNo" placeholder="请选择"  style="width: 120px">
              <el-option label="全部" value=""> </el-option>
              <el-option
                v-for = "i in buList"
                :key = "i.buNo"
                :label = "i.buDesc"
                :value = "i.buNo">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click="getDataList()">查询</el-button>
            <el-button type="primary" @click="addOrUpdateHandle()">新增</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-col>
    </el-row>
    <el-table
      :data="dataList"
      border
      :height="height"
      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="120"
        label="操作">
        <template slot-scope="scope">
          <el-link type="text" size="small" @click="addOrUpdateHandle(scope.row)">修改</el-link>
          <el-link type="text" size="small" @click="deleteHandle(scope.row)">| 删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: -2px;"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[20, 100, 500, 1000]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>


    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from './resourcespare-add-or-update'
import {getTableDefaultListLanguage, getTableUserListLanguage} from "@/api/table.js"
import {
  getResourceSpareList,deleteResourceSpare
} from '@/api/partspare/resourcespare.js'
import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'
import {getAllBuList}from  '@/api/factory/site.js'
export default {
  data() {
    return {
      // 是否收藏
      favorite: false,
      // 导出 start
      exportData: [],
      exportName: "设备备品配件信息" + this.dayjs().format('YYYYMMDDHHmmss'),
      exportHeader: ["设备备品配件信息"],
      exportFooter: [],
      exportList:[],
      // 导出 end
      queryForm: {
        site :this.$store.state.user.site,
        partNo :'',
        partDescription : '',
        resourceId : '',
        resourceDesc : '',
        limit: 1,
        buNo: '',
        page: '',
      },
      buList: [],
      dataList: [],
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      height: 200,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      // 展示列集
      columnList: [
        {
          userId: this.$store.state.user.name,
          functionId: 200101102,
          serialNumber: '200101102TableSite',
          tableId: "200101102Table",
          tableName: "设备备品配件信息表",
          columnProp: 'site',
          headerAlign: "center",
          align: "left",
          columnLabel: '工厂编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 70,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101102,
          serialNumber: '200101102TableBuNo',
          tableId: "200101102Table",
          tableName: "设备备品配件信息表",
          columnProp: 'buNo',
          headerAlign: "center",
          align: "left",
          columnLabel: 'BU',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 60,
        },
        {
          userId: this.$store.state.user.name,
          functionId: 200101102,
          serialNumber: '200101102TableResourceId',
          tableId: "200101102Table",
          tableName: "设备备品配件信息表",
          columnProp: 'resourceId',
          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: 200101102,
          serialNumber: '200101102TableResourceDesc',
          tableId: "200101102Table",
          tableName: "设备备品配件信息表",
          columnProp: 'resourceDesc',
          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: 200101102,
          serialNumber: '200101102TablePartNo',
          tableId: "200101102Table",
          tableName: "设备备品配件信息表",
          columnProp: 'partNo',
          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: 200101102,
          serialNumber: '200101102TablePartDescription',
          tableId: "200101102Table",
          tableName: "设备备品配件信息表",
          columnProp: 'partDescription',
          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: 200101102,
          serialNumber: '200101102TableQtyUsable',
          tableId: "200101102Table",
          tableName: "设备备品配件信息表",
          columnProp: 'qtyUsable',
          headerAlign: "center",
          align: "right",
          columnLabel: '可用数量',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80,
        },
      ],
    }
  },

  components: {
    AddOrUpdate
  },

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

  created() {
    // 动态列
    this.getTableUserColumn(this.$route.meta.menuId+'table',1)
    this.getBu()
    this.favoriteIsOk()
    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) {
        // 取消收藏
        this.$confirm(`确定取消收藏`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          removeUserFavorite(userFavorite).then(({data}) => {
            this.$message.success(data.msg)
            this.favorite = false
          })
        })
      } else {
        // 收藏
        saveUserFavorite(userFavorite).then(({data}) => {
          this.$message.success(data.msg)
          this.favorite = true
        })
      }

    },


    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      this.queryForm.page = this.pageIndex
      this.queryForm.limit = this.pageSize
      getResourceSpareList(this.queryForm).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    //导出excel
    async createExportData() {
      this.queryForm.limit = -1
      this.queryForm.page = 1
      await getResourceSpareList(this.queryForm).then(({data}) => {
        this.exportList= data.page.list;
      })

      return this.exportList;
    },
    startDownload() {
      //  this.exportData = this.dataList

    },
    finishDownload() {

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

      return s
    },
    // 导出 end
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 新增 / 修改
    addOrUpdateHandle(row) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(row)
      })
    },
    // 删除
    deleteHandle(row) {
      this.$confirm(`确定进行删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteResourceSpare(row).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success(data.msg)
            this.getDataList()
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    // 动态列开始 获取 用户保存的 格式列
    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.columnDetailList = 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.columnDetailList = data.rows
            //   break;
            // case 3:
            //   this.columnList2 = data.rows
            //   break;
            // case 4:
            //   this.columnList3 = data.rows
            //   break;
          }
        } else {
          // this.showDefault = true.
        }
      })
    },
    getBu () {
      let tempData = {
        username: this.$store.state.user.name,
      }
      getAllBuList(tempData).then(({data}) => {
        if (data.code === 0) {
          this.buList = data.rows
        }
      })
    },
  }
}
</script>
