
<template>
  <div class="div1">

    <div class="div2" style="padding-bottom: 10px">
      <el-form ref="form" :model="param" label-width="80px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="日期:">
              <el-date-picker style="width: 300px"
                              v-model="param.日期"
                              type="daterange"
                              align="right"
                              unlink-panels
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-button type="success" @click="find">查找</el-button>
        <el-button type="success" @click="down">导出</el-button>
        <el-button type="success" @click="rest">重置</el-button>&nbsp;&nbsp;
        <el-checkbox v-model="checked" @change="Allquesr">是否显示全部查询条件</el-checkbox>
      </el-form>
    </div>

    <el-table
        v-loading="this.tableloding"
        :height="MaxHeight"
        :header-cell-style="{background:'#000',color:'#fff'}"
        :span-method="objectSpanMethod"
        :data="tableData"
        id="educe-table"
        ref="tableData"
        style="width: 100%;">
      <el-table-column v-for="item in columns" :key="item.prop" :prop="item.prop" :label="item.label" :min-width="item.minWidth">
        <el-table-column v-if="item.label==='作业类型'"
            prop="出库"
            label="出库"
            width="120">
        </el-table-column>
        <el-table-column v-if="item.label==='作业类型'"
                         prop="入库"
                         label="入库"
                         width="120">
        </el-table-column>
        <el-table-column v-if="item.label==='作业类型'"
                         prop="盘点"
                         label="盘点"
                         width="120">
        </el-table-column>
        <el-table-column v-if="item.label==='作业类型'"
                         prop="整理"
                         label="整理"
                         width="120">
        </el-table-column>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[ 50, 100, 200,500]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>

</template>

<script>
import FileSaver from 'file-saver'
// eslint-disable-next-line no-unused-vars
import XLSX from "xlsx";
export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 表头配置
      columns: [
        {
          prop: '库区',
          minWidth: '150px',
          label: '库区'
        },
        {
          prop: '工作站',
          minWidth: '150px',
          label: '工作站'
        },
        {
          prop: '作业类型',
          minWidth: '150px',
          label: '作业类型'
        },
        {
          prop: '有效时效',
          minWidth: '150px',
          label: '有效时间'
        },
        {
          prop: '有效时间占比',
          minWidth: '150px',
          label: '有效时间占比'
        }
      ],
      /*columns:[
        prop: 'a1',
      ],*/
      tableloding: false,
      isShow:false,//是否展示全部搜索条件
      tableData: [],
      pageSize: 50
      ,spanArr: [], //每行合并数
      pos: 0, //角标索引
      pageNum: 1,
      total: 3,
      param: {
        日期:[]
      },
      loading: false,
      checked: false
    }
  },

  computed:{
    MaxHeight(){
      return  window.innerHeight - 240 +"px";
    }
  },
  mounted: function () {
    this.queryUser();
  },
  updated() {
    // 每次更新会重新对 Table 进行重新布局
    this.$nextTick(() => {
      if (this.$refs.mutipleTable !== undefined) {
        this.$refs.mutipleTable.doLayout()
      }
    })
  },
  methods: {
    // 合并单元格样式，主要是针对要合并列的第一个单元格（有其他需要的可自行更改）
    cellStyle({ row, column }) {
      // 找到数组中列>1那一个单元格，就是需要改变的样式
      if (row['mergeData'][column.property] && row['mergeData'][column.property][1] && row['mergeData'][column.property][1] > 1) {
        return { 'text-align': 'center' }
      } else {
        return {}
      }

    },
    objectSpanMethod({ row, column }) {
      // 直接返回后端给的对应字段的单元格数据
      return row['mergeData'][column.property]
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = 1;
      this.pageSize = val;
      this.queryUser();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.queryUser();
    },
    queryUser() {
      //列表数据加载
      this.$axios.post(this.$httpUrl + '/GGZXiaoLv/queryList', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        param: this.param,
      }).then(res => res.data)
          .then(res => {
            if (res.code == 200) {
              this.tableData = res.data
              this.total = res.total
            } else {
              this.$message.error('获取数据失败');
            }

            // eslint-disable-next-line no-unused-vars
          },err=>{
            this.tableloding=false;
          })

    },
    find(){
      this.pageNum=1;
      this.queryUser();
    },
    down(){
      this.exportToExcel();
    },

    // 表格数据写入excel，并导出为Excel文件
    exportToExcel(){
      /*const worksheet = XLSX.utils.json_to_sheet(this.tableData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
      XLSX.writeFile(workbook, 'table_data.xlsx');*/
      const XLSX = require('xlsx')
      console.log('XLSX',XLSX,FileSaver)
      // 使用 this.$nextTick 是在dom元素都渲染完成之后再执行
      this.$nextTick(function () {
        // 设置导出的内容是否只做解析，不进行格式转换     false：要解析， true:不解析
        const xlsxParam = { raw: true }
        const wb = XLSX.utils.table_to_book(document.querySelector('#educe-table'), xlsxParam)
        // 导出excel文件名
        let fileName = '工作效率分析_' + new Date().getTime() + '.xlsx'

        const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          // 下载保存文件
          FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), fileName)
        } catch (e) {
          if (typeof console !== 'undefined') {
            console.log(e, wbout)
          }
        }
        return wbout
      })
    },
    parseTime(time, cFormat) {
      //获取当前时间
      if (arguments.length === 0) {
        return null
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'undefined' || time === null || time === 'null') {
        return ''
      } else if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
      return time_str
    },
    Allquesr(){
      //查询按钮
      if(this.checked){
        this.isShow=true;
      }else {
        this.isShow=false;
      }
    },
    rest() {
      //条件查询重置
      this.checked=false;
      this.isShow=false;
      this.param={};
    }
  }
}
</script>
<style scoped>

</style>
