<template>
  <div class="course-manage">
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" 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.courseName"
              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="part-box-action">
        <el-button
          v-if="checkPrivilege('button', 'Delete')"
          type="danger"
          :disabled="!filterHasQuery"
          @click="toBatchDelete"
          >批量删除</el-button
        >
        <el-button
          type="success"
          icon="el-icon-download"
          v-if="checkPrivilege('button', 'TempleteDownload')"
          ><a :href="downloadUrl" :download="dfilename">模板下载</a></el-button
        >
        <upload-button
          v-if="checkPrivilege('button', 'Import')"
          btn-icon="el-icon-circle-plus-outline"
          btn-content="批量导入"
          btn-type="success"
          :upload-url="uploadUrl"
          :format="['xls', 'xlsx']"
          accept=".xls,.xlsx"
          @valid-error="validError"
          @upload-success="uploadSuccess"
        >
        </upload-button>
        <el-button
          v-if="checkPrivilege('button', 'add')"
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="toAdd"
          >新增课程</el-button
        >
      </div>
    </div>
    <div class="part-box part-box-pad">
      <el-table ref="TableList" :data="courses">
        <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="clazzList" label="授课班级" min-width="120">
          <span slot-scope="scope">
            <more-text :data="scope.row.clazzNames" :show-count="3"></more-text>
          </span>
        </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="120"
          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,prev, pager, next"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
        >
        </el-pagination>
      </div>
    </div>

    <modify-course
      :instance="curCourse"
      @modified="getList"
      ref="ModifyCourse"
    ></modify-course>
  </div>
</template>

<script>
import { courseListPage, deleteCourse, batchDeleteCourse } from "../api";
import pickerOptions from "@/constants/datePickerOptions";
import ModifyCourse from "../components/ModifyCourse";
import UploadButton from "../../../components/UploadButton";
import { ABLE_TYPE } from "@/constants/enumerate";

export default {
  name: "course-manage",
  components: { ModifyCourse, UploadButton },
  data() {
    return {
      filter: {
        belongOrgId: "",
        courseName: "",
        startCreateTime: "",
        endCreateTime: "",
        enable: ""
      },
      queriedFilter: {},
      ABLE_TYPE,
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      courses: [],
      curCourse: {},
      // import
      uploadUrl: "/api/admin/basic/course/data_import",
      downloadUrl: "/temps/courseTemplate.xlsx",
      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);
        return item;
      });
      this.total = data.total;
      this.queriedFilter = { ...this.filter };
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    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(() => {});
    },
    toBatchDelete() {
      this.$confirm(`确定要删除当前查询的所有课程吗?`, "提示", {
        type: "warning"
      })
        .then(async () => {
          await batchDeleteCourse({ ...this.filter });
          this.$message.success("操作成功！");
          this.toPage(1);
        })
        .catch(() => {});
    },
    // import
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess() {
      this.$message.success("文件上传成功，后台正在导入！");
      this.getList();
    }
  }
};
</script>
