<template>
  <div style="display: flex; flex-direction: column;flex-grow: 1; flex-shrink: 1;">
    <div class="log-main">
      <div class='condition'>
        <el-input v-model.trim='searchValue' class='margin-right' style='width: 300px;' placeholder='请输入操作人、动作、对象id等关键字搜索'
          @keyup.enter.native="searchChange">
        </el-input>
        <el-date-picker class='margin-right' v-model='dateValue' type='daterange' align='center' :clearable='false' unlink-panels range-separator='至'
          start-placeholder='开始日期' end-placeholder='结束日期' :picker-options='pickerOptions' @change='dateChange' value-format='yyyy-MM-dd'>
        </el-date-picker>
      </div>
      <div class="log-table">
        <p style="text-align: right; padding: 10px">
          <el-button style="width: 96px" @click='action'>动作说明</el-button>
          <el-button style="width: 96px" @click='refresh'>刷新</el-button>
          <el-button style="width: 96px" @click='downExcel(1)'>导出到Excel</el-button>
        </p>
        <div style="height: calc(100% - 52px)">
          <el-table :data='tableData' tooltip-effect='dark' style='width: 100%;' v-loading='loading' height="100%"
            :header-cell-style="{background:'#e1e4e5',color:'#2b2b2b'}">
            <el-table-column v-for="item in tableHeader" :prop='item.fieldName' :label='item.headerName' :width='item.width' :key="item.fieldName"
             show-overflow-tooltip></el-table-column>
          </el-table>
        </div>
      </div>
      <el-pagination class="right" v-show="tableData && tableData.length" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page.pageNumber" :page-sizes="page.pageSizes" :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>
    <saga-action ref='action'></saga-action>
  </div>
</template>

<script>
import { queryUserLog } from '@/api/scan/request' //获取日志/下载日志
import { mapGetters, mapActions } from 'vuex'
import axios from 'axios'
//component
import SagaAction from './Action'
import jsontoExcel from "@/utils/JOSNToExcel"

var date = new Date()
const nowDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
export default {
  name: 'data-log',
  data() {
    return {
      loading: false,
      searchValue: '',
      tableData: [],
      dateValue: [nowDate, nowDate],
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 0)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
              picker.$emit('pick', [start, end])
            }
          },
          {
            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])
            }
          }
        ]
      },
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0
      },
      tableHeader: [
        { fieldName: 'CreateTime', headerName: '时间', width: 150 },
        { fieldName: 'Comming', headerName: '来源', width: 120 },
        { fieldName: 'Name', headerName: '操作人', width: 120 },
        { fieldName: 'Phone', headerName: '手机', width: 150 },
        { fieldName: 'Action', headerName: '动作', width: 200 },
        { fieldName: 'UserId', headerName: '对象id', width: 300 },
        { fieldName: 'Note', headerName: '操作说明', width: 'auto' },
      ],
      exportData: []
    }
  },
  components: {
    SagaAction
  },
  computed: {
    ...mapGetters('layout', ['projectId', 'userId'])
  },
  methods: {
    searchChange(value) {
      this.page.pageNumber = 1
      this.getLogData()
    },
    refresh() {
      this.getLogData()
    },
    action() {
      this.$refs['action'].show()
    },
    // 导出
    downExcel(pageNum) {
      // let param = {
      //   startTime: this.dateValue[0] + ' 00:00:00',
      //   endTime: this.dateValue[1] + ' 23:59:59',
      //   filter: this.searchValue,
      //   ProjId: this.projectId,
      //   UserId: this.userId,
      //   Comming: 'revit'
      // }
      // axios({
      //   method: 'post',
      //   url: '/ScanBuilding/service/user_log/export',
      //   data: param,
      //   responseType: 'blob'
      // })
      //   .then(function (res) {
      //     var blob = new Blob([res.data], {
      //       type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
      //     })
      //     var fileName = res.headers['content-disposition']
      //     if (fileName) fileName = fileName.substring(fileName.indexOf('=') + 1)
      //     if ('download' in document.createElement('a')) {
      //       // 非IE下载
      //       const elink = document.createElement('a')
      //       elink.download = fileName
      //       elink.style.display = 'none'
      //       elink.href = URL.createObjectURL(blob)
      //       document.body.appendChild(elink)
      //       elink.click()
      //       URL.revokeObjectURL(elink.href) // 释放URL 对象
      //       document.body.removeChild(elink)
      //     } else {
      //       // IE10+下载
      //       navigator.msSaveBlob(blob, fileName)
      //     }
      //   })
      //   .catch(function (err) {
      //     console.dirxml(err)
      //   })
      let param = {
        filters: `createTime>='${this.dateValue[0]} 00:00:00';createTime<='${this.dateValue[1]} 23:59:59'`,
        pageNumber: pageNum,
        pageSize: 1000
      }
      if (this.searchValue) {
        param.filters += `;name contain '${this.searchValue}' or phone contain '${this.searchValue}' or action contain '${this.searchValue}' or note contain '${this.searchValue}' or userId contain '${this.searchValue}'`
      }
      queryUserLog(param, res => {
        this.exportData = this.exportData.concat(res.content);
        if (res.total / (res.pageSize * res.pageNumber) > 1) {
          this.downExcel(pageNum++)
        } else {
          let time = +new Date()
          jsontoExcel.downloadExl(this.tableHeader, this.exportData, `UserLog-${time}`)
        }
      })
    },
    //切换每页显示多少条数据
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getLogData()
    },
    //切换页数
    handleCurrentChange(val) {
      this.page.pageNumber = val
      this.getLogData()
    },
    dateChange(value) {
      this.page.pageNumber = 1
      this.getLogData()
    },
    getLogData() {
      let param = {
        filters: `createTime>='${this.dateValue[0]} 00:00:00';createTime<='${this.dateValue[1]} 23:59:59'`,
        pageNumber: this.page.pageNumber,
        pageSize: this.page.pageSize
      }
      if (this.searchValue) {
        param.filters += `;name contain '${this.searchValue}' or phone contain '${this.searchValue}' or action contain '${this.searchValue}' or note contain '${this.searchValue}' or userId contain '${this.searchValue}'`
      }
      queryUserLog(param, res => {
        this.loading = false
        this.page.total = res.total
        this.tableData = res.content
      })
    },
    init() {
      this.getLogData()
    }
  },
  created() {
    this.init()
  },
  watch: {
    projectId() {
      this.searchValue = '';
      this.getLogData();
    }
  }
}
</script>

<style lang='less' scoped>
.log-main {
  height: 100%;
  background: #fff;
  .condition {
    margin: 10px;
    display: flex;
    .margin-right {
      margin-right: 10px;
    }
  }
  .log-table {
    border-top: 2px solid #dfe6ec;
    height: calc(100% - 100px);
    .ellipsis {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
<style lang="less">
.el-table th {
  background-color: #d9d9d9;
  color: #000;
}
</style>
