<template>
  <div class="course-manage">
    <div class="part-box part-box-filter">
      <el-form
        ref="FilterForm"
        label-position="right"
        label-width="85px"
        inline
      >
        <template v-if="checkPrivilege('condition', 'condition')">
          <el-form-item label="开课部门：">
            <org-select
              v-model="filter.belongOrgId"
              placeholder="开课学院"
            ></org-select>
          </el-form-item>
          <el-form-item label="课程代码/名称：">
            <el-input
              style="width: 142px"
              v-model.trim="filter.courseCodeOrName"
              placeholder="课程代码/名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="创建时间：">
            <el-date-picker
              v-model="createTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="创建开始时间"
              end-placeholder="创建结束时间"
              value-format="timestamp"
              align="right"
              unlink-panels
            >
            </el-date-picker>
          </el-form-item>
        </template>
        <el-form-item>
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="box-justify">
        <div>
          <el-button
            v-if="checkPrivilege('button', 'Delete')"
            type="danger"
            icon="el-icon-delete"
            @click="toBatchDelete"
            >批量删除</el-button
          >
          <el-button
            v-if="checkPrivilege('button', 'export')"
            type="primary"
            icon="el-icon-download"
            :loading="loading"
            @click="toExportCourse"
            >导出</el-button
          >
        </div>
        <div>
          <el-button
            v-if="checkPrivilege('button', 'import')"
            type="success"
            icon="el-icon-upload2"
            @click="toImport"
            >导入</el-button
          >
          <el-button
            v-if="checkPrivilege('button', 'add')"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="toAdd"
            >新增</el-button
          >
        </div>
      </div>
    </div>
    <div class="part-box part-box-pad">
      <el-table
        ref="TableList"
        :data="courses"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          fixed="left"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="70"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column
          prop="courseName"
          label="课程名称"
          min-width="120"
        ></el-table-column>
        <el-table-column
          prop="courseCode"
          label="课程代码"
          min-width="120"
        ></el-table-column>
        <el-table-column
          prop="teachingRoomName"
          label="开课学院"
          min-width="120"
        ></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170">
          <span slot-scope="scope">{{
            scope.row.createTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="100"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'edit')"
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'delete')"
              class="btn-danger"
              type="text"
              @click="toDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="5"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
          @size-change="pageSizeChange"
        >
        </el-pagination>
      </div>
    </div>

    <modify-course
      :instance="curCourse"
      @modified="getList"
      ref="ModifyCourse"
    ></modify-course>
    <!-- ImportFile -->
    <import-file
      v-if="checkPrivilege('button', 'import')"
      ref="ImportFile"
      title="导入课程"
      :upload-url="uploadUrl"
      :format="['xls', 'xlsx']"
      :download-handle="() => downloadTemplate('course')"
      :download-filename="dfilename"
      :auto-upload="false"
      @upload-success="uploadSuccess"
    ></import-file>
  </div>
</template>

<script>
import { courseListPage, deleteCourse, exportCourse } from "../api";
import pickerOptions from "@/constants/datePickerOptions";
import ModifyCourse from "../components/ModifyCourse.vue";
import ImportFile from "../../../components/ImportFile.vue";
import { ABLE_TYPE } from "@/constants/enumerate";
import { downloadByApi } from "@/plugins/download";
import templateDownload from "@/mixins/templateDownload";

export default {
  name: "course-manage",
  components: { ModifyCourse, ImportFile },
  mixins: [templateDownload],
  data() {
    return {
      filter: {
        belongOrgId: "",
        courseCodeOrName: "",
        startCreateTime: "",
        endCreateTime: "",
        enable: "",
      },
      queriedFilter: {},
      ABLE_TYPE,
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      courses: [],
      multipleSelection: [],
      curCourse: {},
      loading: false,
      // import
      uploadUrl: "/api/admin/basic/course/data_import",
      dfilename: "课程导入模板.xlsx",
      // date-picker
      createTime: [],
      pickerOptions,
    };
  },
  computed: {
    filterHasQuery() {
      return !Object.keys(this.filter).some(
        (k) => this.filter[k] !== this.queriedFilter[k]
      );
    },
  },
  mounted() {
    this.getList();
  },
  methods: {
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      if (this.createTime) {
        datas.startCreateTime = this.createTime[0];
        datas.endCreateTime = this.createTime[1];
      }
      if (datas.enable !== null && datas.enable !== "")
        datas.enable = !!datas.enable;

      const data = await courseListPage(datas);
      this.courses = data.records.map((item) => {
        item.clazzNames = item.clazzList.map((org) => org.name);
        item.teachNames = item.teachList.map(
          (user) => `${user.name}(${user.orgName})`
        );
        return item;
      });
      this.total = data.total;
      this.queriedFilter = { ...this.filter };
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id);
    },
    toAdd() {
      this.curCourse = {};
      this.$refs.ModifyCourse.open();
    },
    toEdit(row) {
      this.curCourse = row;
      this.$refs.ModifyCourse.open();
    },
    toDelete(row) {
      this.$confirm(`确定要删除课程【${row.courseName}】吗?`, "提示", {
        type: "warning",
      })
        .then(async () => {
          await deleteCourse([row.id]);
          this.$message.success("删除成功！");
          this.deletePageLastItem();
        })
        .catch(() => {});
    },
    async toBatchDelete() {
      if (!this.multipleSelection.length) {
        this.$message.error("请选择要删除的课程");
        return;
      }
      const confirm = await this.$confirm(
        `确定要删除当前选择的所有课程吗?`,
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (confirm !== "confirm") return;

      await deleteCourse(this.multipleSelection);
      this.$message.success("操作成功！");
      this.deletePageLastItem();
    },
    async toExportCourse() {
      if (this.loading) return;

      this.loading = true;
      const res = await downloadByApi(() => {
        return exportCourse(this.filter);
      }, "").catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.loading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    // import
    toImport() {
      this.$refs.ImportFile.open();
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess() {
      this.$message.success("文件上传成功！");
      this.getList();
    },
  },
};
</script>
