<template>
  <div class="content statistics-manage">
    <!-- 正文信息 -->
    <div class="part-box">
      <!-- <h1 class="part-box-title">统计管理</h1> -->
      <!-- 搜索 -->
      <el-form class="part-filter-form" inline :model="searchForm">
        <el-form-item label="课程">
          <el-select
            v-model="searchForm.courseId"
            :remote-method="getCoursesList"
            :loading="courseLoading4Search"
            remote
            filterable
            clearable
            placeholder="请选择"
            @clear="getCoursesList('')"
          >
            <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.name + ' - ' + item.code"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" style="width: 460px">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd"
            align="right"
            unlink-panels
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleCurrentChange(1)">
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <!-- <div class="part-box-action"></div> -->
    </div>
    <div class="part-box">
      <div class="icon-btn-group box-justify">
        <div>
          <svg-btn name="daochu" :loading="downloading" @click="exportHandle"
            >导出统计数据</svg-btn
          >
        </div>
        <div></div>
      </div>
      <el-table
        ref="table"
        :data="tableData"
        resizable
        @sort-change="sortChange"
      >
        <el-table-column label="序号" width="60">
          <template slot-scope="scope">
            {{ pageSize * (currentPage - 1) + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="courseName" label="课程名称"> </el-table-column>
        <el-table-column prop="courseCode" label="课程代码"> </el-table-column>
        <el-table-column
          prop="questionCount"
          label="试题数量"
          sortable
        ></el-table-column>
        <el-table-column prop="paperCount" label="试卷数量" sortable>
        </el-table-column>
        <el-table-column width="160" label="操作">
          <template slot-scope="scope">
            <el-button
              size="medium"
              type="text"
              class="normal"
              @click="toQuestion(scope.row)"
              >试题统计
            </el-button>
            <el-button
              size="medium"
              type="text"
              class="normal"
              @click="toPaper(scope.row)"
              >试卷统计
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :page-sizes="[10, 20, 50, 100, 200, 300]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- StatisticsQuestionDialog -->
    <StatisticsQuestionDialog
      ref="StatisticsQuestionDialog"
      :course-id="curRow.courseId"
    />
    <!-- StatisticsPaperDialog -->
    <StatisticsPaperDialog
      ref="StatisticsPaperDialog"
      :course-id="curRow.courseId"
    />
  </div>
</template>
<script>
import { courseQueryApi } from "../../card/api";
import { statisticsQueryApi, statisticsExportApi } from "../api";
import pickerOptions from "@/constants/datePickerOptions";
import { omit } from "lodash";
import { downloadByApi } from "@/plugins/download";
import { pick } from "lodash";

import StatisticsQuestionDialog from "../components/StatisticsQuestionDialog.vue";
import StatisticsPaperDialog from "../components/StatisticsPaperDialog.vue";

export default {
  name: "StatisticsManage",
  components: { StatisticsQuestionDialog, StatisticsPaperDialog },
  computed: {
    queryParams() {
      let startTime = this.searchForm.createTime?.[0] || "";
      let endTime = this.searchForm.createTime?.[1] || "";
      let obj = omit(this.searchForm, "createTime");
      return { ...obj, startTime, endTime };
    },
  },
  data() {
    return {
      courseList: [],
      searchForm: {
        courseId: "",
        createTime: [],
        orderField: "",
        orderType: "",
      },
      courseLoading4Search: false,
      tableData: [],
      curRow: {},
      currentPage: 1,
      pageSize: 10,
      total: 10,
      loading: false,
      pickerOptions,
      downloading: false,
    };
  },
  created() {
    this.getCoursesList();
    this.search();
  },
  methods: {
    async search() {
      if (this.loading) return;
      this.loading = true;

      const res = await statisticsQueryApi({
        ...this.queryParams,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
      }).catch(() => {});

      this.loading = false;
      if (!res) return;

      this.tableData = res.data.content;
      this.total = res.data.totalElements;
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.search();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.search();
    },
    sortChange({ prop, order }) {
      if (!order) {
        this.searchForm.orderField = undefined;
        this.searchForm.orderType = undefined;
      } else {
        this.searchForm.orderField = prop;
        this.searchForm.orderType = order === "ascending" ? "ASC" : "DESC";
      }
      this.search();
    },
    async getCoursesList(query) {
      this.courseLoading4Search = true;
      const res = await courseQueryApi(query);
      this.courseList = res.data || [];
      this.courseLoading4Search = false;
    },
    async exportHandle() {
      if (this.downloading) return;
      this.downloading = true;

      const res = await downloadByApi(() => {
        return statisticsExportApi({
          // ...this.queryParams,
          ...pick(this.queryParams, ["courseId", "startTime", "endTime"]),
        });
      }).catch((e) => {
        this.$message.error(e || "导出失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("导出成功！");
    },
    toQuestion(row) {
      this.curRow = row;
      this.$refs.StatisticsQuestionDialog.open();
    },
    toPaper(row) {
      this.curRow = row;
      this.$refs.StatisticsPaperDialog.open();
    },
  },
};
</script>
