<template>
  <div class="app-container">
    <el-row type="flex" justify="space-between" ref="listQueryContainer" class="query-container">
      <el-col>
        <el-form :inline="true" style="flex-wrap: wrap" :model="listQuery" ref="listQuery" @submit.native.prevent @keyup.enter.native="onSubmit">
          <el-form-item label-width="0">
            <el-button @click="onExport" plain type="primary">导出</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-table :data="list" border stripe highlight-current-row ref="table" class="mt10" @row-click="onRowClick">
      <el-table-column type="index" :index="indexCompute" label="序号" align="center" width="60px"/>
      <el-table-column prop="lastScore" label="上次分值" align="center" min-width="80px"/>
      <el-table-column prop="changeScore" label="变动分值" align="center" min-width="100px"/>
      <el-table-column prop="currentScore" label="当前分值" align="center" min-width="80px"/>
      <el-table-column prop="event" label="事件" align="center" min-width="160px"/>
      <el-table-column prop="createTime" label="时间" align="center" min-width="160px">
         <template v-slot="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="listQuery.page" :size.sync="listQuery.size" @change="onPageChange"/>

    <el-dialog title="导出" :visible.sync="exportVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="600px">
      <el-progress :text-inside="true" :stroke-width="24" :percentage="exportProgress" status="success"></el-progress>
      <el-button slot="footer" @click="onCancelExport">取 消</el-button>
    </el-dialog>
  </div>
</template>

<script>

import {dateFormat} from "@/utils/dateUtil";

export default {
  name: "SystemAttendanceRecord",
  components: {},

  data() {
    return {
      list: [], // 结果列表
      total: 0, // 总结果数量

      listQuery: {
        userId: undefined, // 用户id
        month: "", // 考勤月份 yyyy-MM
        page: 1,
        size: 10
      },

      exportVisible: false, // 是否显示导出对话框
      exportData: [], // 导出数据
      exportPagination: { // 导出分页
        page: 1,
        size: 500,
      },
      exportProgress: 0, // 导出进度
      exportCancel: false, // 是否取消导出
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {},

  // 页面创建
  created() {
    this.initData();
  },

  // 页面挂载
  mounted() {
    this.listQuery.userId = this.$route.query.userId;
    this.listQuery.month = this.$route.query.month;
    this.initQuery();
    this.getList();
    this.initView();
  },

  // keep-alive 显示界面时调用
  activated() {
  },

  // keep-alive 页面隐藏
  deactivated() {
  },

  methods: {
    // 表格索引
    indexCompute(index) {
      return index + 1 + (this.listQuery.page - 1) * this.listQuery.size;
    },

    // 初始化查询条件
    initQuery() {
      if (this.$store.state.app.paramCache) {
        let query = this.$storage.getData(this.$options.name);
        if (Object.keys(query).length > 0) {
          this.listQuery = query;
          if (query.order) {
            this.$refs.table.sort(query.order.substring(1), query.order.substring(0, 1) === "+" ? "ascending" : "descending");
          } else {
            this.$refs.table.clearSort();
          }
        }
      }
    },

    // 初始化数据
    initData() {
    },

    // 初始化视图
    initView() {
      this.$nextTick(() => {
        this.shrinkable = this.$store.state.app.filterShrink && this.$refs['listQuery'].$el.offsetHeight > 51;
      })
    },

    // 展开/收起查询条件
    onExpansion(show) {
      this.$refs['listQueryContainer'].$el.style.height = show ? "auto" : "51px";
    },

    // 表单提交
    onSubmit() {
      this.onFilterChange();
    },

    // 表单清除
    resetFields() {
      this.$refs['listQuery'].resetFields();
      this.listQuery.order = undefined;
      this.$refs.table.clearSort();
      this.onFilterChange();
    },

    // 行点击
    onRowClick(row, column, event) {
      this.$refs["table"].setCurrentRow(row);
      if (this.editing) {
        this.$refs["table"].toggleRowSelection(row);
      }
    },

    // 条件改变
    onFilterChange() {
      this.listQuery.page = 1;
      this.$nextTick(this.getList);
    },

    // 页码改变
    onPageChange() {
      this.getList();
    },

    // 加载列表
    getList() {
      // 缓存参数
      if (this.$store.state.app.paramCache) {
        this.$storage.setData(this.$options.name, this.listQuery);
      }

      this.$axios.get("/v1/system/attendance/list", {params: this.listQuery}).then(data => {
        this.list = data.list;
        this.total = data.total;
        this.$refs["table"].doLayout();
      });
    },

    // 导出数据
    onExport() {
      if (this.total > 0) {
        this.exportPagination.page = 1;
        this.exportData = [];
        this.exportVisible = true;
        this.getExportData();
      }
    },

    // 取消导出
    onCancelExport() {
      this.exportVisible = false;
      this.exportCancel = true;
    },

    // 获取数据并导出
    getExportData() {
      if (!this.exportCancel) {
        this.$axios.get("/v1/system/attendance/list", {params: {...this.listQuery, ...this.exportPagination}}).then(data => {
          this.exportPagination.page++;
          this.exportData = this.exportData.concat(data.list);
          this.exportProgress = Math.round(this.exportData.length * 100 / this.total);
          if (this.exportData.length < this.total && data.list.length > 0) {
            this.getExportData();
          } else {
            this.exportVisible = false;
            let tHeader = ["序号", "上次分值", "变动分值", "当前分值", "事件", "时间"];
            let filterVal = ["index", "lastScore", "changeScore", "currentScore", "event", "createTime"];
            let data = this.exportData.map((value, index) => filterVal.map((key) => {
              if (key === "index") {
                return index + 1;
              } else if (key === "createTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", new Date(value[key]));
              } else {
                return value[key];
              }
            }));
            import('@/utils/Export2Excel').then(excel => {
              excel.export_json_to_excel({
                header: tHeader, // 表头 必填
                data, // 具体数据 必填
                filename: '考勤详情列表', // 非必填
                autoWidth: true, // 非必填
                bookType: 'xlsx' // 非必填
              })
            })
          }
        });
      }
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {

}
</style>
