<template>
  <div class="app-container">
    <el-row ref="listQueryContainer" class="query-container" justify="space-between" type="flex">
      <el-col>
        <el-form ref="listQuery" :inline="true" :model="listQuery" style="flex-wrap: wrap" @submit.native.prevent @keyup.enter.native="onSubmit">
          <el-form-item label="统计口径" prop="type">
            <el-select v-model="listQuery.type" placeholder="请选择统计口径" @change="onFilterChange">
              <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围" prop="dateRange">
            <el-date-picker
                v-model="listQuery.dateRange"
                :default-time="['00:00:00', '23:59:59']"
                end-placeholder="结束日期"
                range-separator="-"
                start-placeholder="开始日期"
                type="daterange"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="onFilterChange">
            </el-date-picker>
          </el-form-item>
          <el-form-item label-width="0">
            <el-button type="primary" @click="onFilterChange">查询</el-button>
            <el-button plain type="primary" @click="resetFields">重置</el-button>
            <el-button plain type="primary" @click="onExport">导出</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <form-clear :shrinkable="shrinkable" @change="onExpansion" @clear="resetFields"/>
    </el-row>
    <el-table ref="table" :data="list" border class="mt10" highlight-current-row show-summary stripe @sort-change="onSortChange">
      <el-table-column :index="indexCompute" align="center" label="序号" type="index" width="60px"/>
      <el-table-column :label="typeList.find(item => item.id === listQuery.type).label" align="center" min-width="120px" prop="name" sortable="custom"/>
      <el-table-column align="center" label="正在处理" min-width="80px" prop="processing">
         <template v-slot="scope">
        <text-label type="primary">{{ scope.row.processing }}</text-label>
        </template>
      </el-table-column>
      <el-table-column align="center" label="已经完成" min-width="80px" prop="completed">
         <template v-slot="scope">
        <text-label  type="success">{{ scope.row.completed }}</text-label>
        </template>
      </el-table-column>
      <el-table-column align="center" label="已经取消" min-width="80px" prop="cancelled">
         <template v-slot="scope">
        <text-label  type="warning">{{ scope.row.cancelled }}</text-label>
        </template>
      </el-table-column>
      <el-table-column align="center" label="超时任务" min-width="80px" prop="timeout">
         <template v-slot="scope">
        <text-label  type="danger">{{ scope.row.timeout }}</text-label>
        </template>
      </el-table-column>
    </el-table>
    <pagination :page.sync="listQuery.page" :size.sync="listQuery.size" :total="total" @change="onPageChange"/>

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

<script>
import FormClear from "@/components/FormClear";

export default {
  name: "TemporaryTaskStatistics",
  components: {FormClear},
  data() {
    return {
      shrinkable: false, // 查询条件是否可以展开
      listQuery: { // 查询对象
        type: 1, // 统计口径 1:执行人 2:任务类型 3:任务日期 4:任务月份
        dateRange: [], // 时间范围
        startTime: undefined,
        endTime: undefined,
        order: undefined, // 排序方式
        page: 1,
        size: 10
      },

      typeList: [{id: 1, label: "执行人"}, {id: 2, label: "任务类型"}, {id: 3, label: "任务日期"}, {id: 4, label: "任务月份"}], // 统计口径列表

      list: [], // 结果列表
      total: 0, // 总结果数量

      exportVisible: false, // 是否显示导出对话框
      exportData: [], // 导出数据
      exportPagination: { // 导出分页
        page: 1,
        size: 500,
      },
      exportProgress: 0, // 导出进度
      exportCancel: false, // 是否取消导出
    }
  },

  watch: {
    // 监听日期范围变化
    'listQuery.dateRange'(value) {
      if (value) {
        this.listQuery.startTime = value[0];
        this.listQuery.endTime = value[1];
      } else {
        this.listQuery.startTime = undefined;
        this.listQuery.endTime = undefined;
      }
    }
  },

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

  // 页面挂载
  mounted() {
    this.initQuery();
    this.getList();
    this.initView();
  },

  // keep-alive 显示界面时调用
  activated() {
    this.$refs["table"].doLayout();
  },

  // 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, query.order === "asc" ? "ascending" : "descending");
          } else {
            this.$refs.table.clearSort();
          }
        }
      }
    },

    // 初始化事件
    initEvent() {
    },

    // 初始化数据
    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();
    },

    // 排序改变
    onSortChange({prop, order}) {
      if (order === "ascending") {
        this.listQuery.order = "+" + prop;
      } else if (order === "descending") {
        this.listQuery.order = "-" + prop;
      } else {
        this.listQuery.order = undefined;
      }
      this.onFilterChange();
    },

    // 条件改变
    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/temporary/task/list/statistical", {params: this.listQuery}).then(data => {
        this.list = data.list.map(item => {
          item.processing = item.statusList.find(item => item.status === 1)?.count ?? 0;
          item.completed = item.statusList.find(item => item.status === 2)?.count ?? 0;
          item.cancelled = item.statusList.find(item => item.status === 3)?.count ?? 0;
          item.timeout = item.statusList.find(item => item.status === 4)?.count ?? 0;
          return item;
        });
        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/temporary/task/list/statistical", {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 = ["序号", this.typeList.find(item => item.id === this.listQuery.type).label, "正在处理", "已经完成", "已经取消", "超时任务"];
            let filterVal = ["index", "name", "processing", "completed", "cancelled", "timeout"];
            let data = this.exportData.map((value, index) => filterVal.map((key) => {
              if (key === "index") {
                return index + 1;
              } else if (key === "processing") {
                return value.statusList.find(item => item.status === 1)?.count ?? 0;
              } else if (key === "completed") {
                return value.statusList.find(item => item.status === 2)?.count ?? 0;
              } else if (key === "cancelled") {
                return value.statusList.find(item => item.status === 3)?.count ?? 0;
              } else if (key === "timeout") {
                return value.statusList.find(item => item.status === 4)?.count ?? 0;
              } else {
                return value[key];
              }
            }));
            import('@/utils/Export2Excel').then(excel => {
              excel.export_json_to_excel({
                header: tHeader, // 表头 必填
                data, // 具体数据 必填
                filename: '任务统计列表', // 非必填
                autoWidth: true, // 非必填
                bookType: 'xlsx' // 非必填
              })
            })
          }
        });
      }
    }
  }
}
</script>

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

}
</style>
