<template>
  <div class="app-container">
    <!--筛选条件-->
    <div class="search-div">
      <el-form ref="selectForm" :inline="true" :model="listQuery" class="form-container">
        <el-row>
          <el-form-item class="selectForm-container-item" prop="keywords">
            <el-input v-model.trim="listQuery.keyword1" placeholder="厂家名称关键字" clearable />
          </el-form-item>
          <el-form-item class="selectForm-container-item" prop="keywords">
            <el-select v-model="listQuery.keyword2" filterable placeholder="在产设备" clearable value="">
              <el-option
                v-for="item in deviceList"
                :key="item.id"
                :label="item.productName"
                :value="item.productName"/>
            </el-select>
          </el-form-item>
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="add">新增厂家</el-button>
          <el-upload
            :limit="1"
            :show-file-list="false"
            :http-request="uploadFile"
            :file-list="fileList"
            class="upload-btn"
            action="string"
            accept=".xls,.xlsx">
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit">批量导入</el-button>
          </el-upload>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="batchExport">导出厂家列表</el-button>
        </el-row>
      </el-form>
    </div>
    <!--查询结果Table显示-->
    <div>
      <el-row class="table-title">
        <el-col :span="6"><div class="title-header"><i class="el-icon-menu"/>数据列表</div></el-col>
        <!--<download-template :filename="pricefilename" btnname="设备报价模板"/>-->
        <download-template :filename="factoryfilename" btnname="厂家导入模板"/>
      </el-row>
      <el-table v-loading="listLoading" :data="list" class="table" border @selection-change="handleSelectionChange">
        <el-table-column :index="indexMethod" align="center" type="index" label="序号" width="55"/>
        <el-table-column v-for="column in columns" :key="column.value" :label="column.text" :width="column.width" :align="column.align" show-overflow-tooltip>
          <template slot-scope="scope">
            <span :class="column.class">{{ scope.row[column.value] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备报价" align="center" width="160">
          <template slot-scope="scope">
            <el-button :disabled="checkhasFile(scope.row)" type="text" @click="batchExportPrice(scope.row)">下载</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="scope">
            <el-button type="text" @click="edit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页-->
    <div class="pagination-container">
      <el-pagination
        :current-page="listQuery.offset"
        :page-sizes="[5,10,20]"
        :page-size="listQuery.limit"
        :total="total"
        align="center"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>

    <edit-factory v-show="dialogFormVisible" ref="editfactory" @watchChild="fetchData"/>

  </div>
</template>

<script>

import editFactory from '@/views/factoryManager/editFactory'
import { getFactoryList, batchExportDevicePrice, batchImportFactory, batchExportFactory, getDeviceList } from '@/api/factory'
import DownloadTemplate from '@/components/DownloadTemplate/index'

export default {
  name: 'ListFactory',
  components: { editFactory, DownloadTemplate },
  data() {
    return {
      fileList: [], // 批量导入
      deviceList: null, // 在产设备列表
      factoryfilename: 'factoryImp.xlsx',
      // factoryfile: 'bbb.xlsx',
      listQuery: {
        keyword1: '',
        keyword2: '',
        offset: 1,
        limit: 5
      }, // 筛选条件
      columns: [
        {
          text: '厂家名称',
          value: 'name',
          align: 'center'
        },
        {
          text: '厂家联系人',
          value: 'personName',
          align: 'center'
        },
        {
          text: '地址',
          value: 'address',
          align: 'center'
        },
        {
          text: '电话',
          value: 'phone',
          align: 'center'
        },
        {
          text: '开户行',
          value: 'bank',
          align: 'center'
        },
        {
          text: '账号',
          value: 'taxNumber',
          align: 'center'
        }
      ], // 显示列
      list: [], // 列表数据
      total: 0, // 数据总数
      listLoading: true, // 加载动画
      fullscreenLoading: false, // 全屏加载动画
      editShow: false, // 是否显示编辑框
      dialogFormVisible: false // 是否显示编辑框
    }
  },
  computed: {
  },
  created() {
    this.fetchDeviceList() // 获取在产设备列表
    this.fetchData()// 获取数据
    var lett = this
    document.onkeydown = function(e) {
      var key = window.event.keyCode
      if (key === 13) {
        lett.fetchData()
      }
    }
  },
  activated() {
    this.fetchData()// 获取数据
  },
  methods: {
    // 获取在产设备列表
    fetchDeviceList() {
      getDeviceList().then(response => {
        this.deviceList = response.data
      })
    },
    // 批量导入
    uploadFile(param) {
      // 判断文件大小是否符合要求
      const _file = param.file
      const isLt5M = _file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('请上传5M以下的excel文件')
        return false
      }
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '导入中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 批量导入上传请求
      batchImportFactory(_file).then(res => {
        loading.close() // 关闭加载动画
        if (res.code === 200) {
          this.$alert('已导入成功' + res.message, '', {
            confirmButtonText: '确定',
            type: 'success'
          })
          // this.$message.success('导入成功')
          this.fileList = []
          this.fetchData()
        } else {
          this.$message.error(res.message)
        }
      }).catch(err => {
        loading.close()
        this.$message.error(err.message)
      })
      this.fileList = []
    },

    // 设备报价表下载
    batchExportPrice(row) {
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '下载中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      batchExportDevicePrice(row.equipmentQuotation).then(res => {
        loading.close() // 关闭加载动画
        console.log('download===', res)
        const blob = new Blob([res.data])
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = row.name + `设备报价表.xlsx` // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放blob对象
      }).catch((res) => {
        loading.close()
        this.$message.error(res.message)
      })
    },

    // 批量导出
    batchExport() {
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '下载中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      batchExportFactory(this.listQuery).then(res => {
        loading.close() // 关闭加载动画
        console.log('download===', res)
        const blob = new Blob([res.data])
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = `厂家列表.xlsx` // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放blob对象
      }).catch((res) => {
        loading.close()
        this.$message.error(res.message)
      })
    },
    // 新增厂家
    add() {
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.editfactory.initDialog('create', this.dialogFormVisible)
    },
    // 编辑字典信息
    edit(row) {
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.editfactory.initDialog('update', this.dialogFormVisible, row)
    },
    // 查询数据
    search() {
      this.fetchData(false)
    },
    // 判断是否存在文档信息
    checkhasFile(row) {
      if (row.equipmentQuotation !== '') {
        return false
      } else {
        return true
      }
    },
    // 获取字典数据
    fetchData(isNowPage = true) {
      this.listLoading = true
      if (!isNowPage) { // 是否显示当前页，否则跳转第一页
        this.listQuery.offset = 1
      }
      getFactoryList(this.listQuery).then(response => {
        this.list = response.data.rows
        console.log(this.list)
        this.total = parseInt(response.data.total)
        this.listLoading = false
      })
    },
    indexMethod(index) {
      return this.listQuery.limit * (this.listQuery.offset - 1) + index + 1
    },
    // 改变页容量
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    // 改变当前页
    handleCurrentChange(val) {
      this.listQuery.offset = val
      this.fetchData()
    },
    // 多选触发方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  $tableTitleHeight:46px;
  .table{
    margin-bottom: 20px;
  }
  .pagination-container{
    margin-bottom: 50px;
  }
  .table-title{
    background-color:rgba(243, 243, 243, 1);
    height: $tableTitleHeight;
    .title-header{
      line-height:$tableTitleHeight;
      color: #606266;
      font-size: 15px;
      i{
        margin-left: 5px;
        margin-right: 5px;
      }
    }
  }
  .edit_btns{
    .edit_btn{
      float:right;
      margin:7px 3px;//为了需要居中显示margin-top和bottom要用$tableTitleHeight减去按钮原高度除以2
    }
  }
  .upload-btn{
    display: inline;
  }
</style>
