<template>
  <div>
    <el-card shadow="hover"
             class="mgb20">
      <div>
        <div class="flex-center mgb20">
          <p class="hr_tag"></p>
          <span>筛选</span>
        </div>
        <div>
          <el-form label-width="80px">
            <el-col :span="4">
              <el-form-item label="学科类别">
                <el-select v-model="form.categoryId"
                           clearable
                           @change="getProfessionalClass()"
                           @clear="clearClass()">
                  <el-option v-for="(item,index) in subjectList"
                             :key="index"
                             :label="item.disciplineName"
                             :value="item.disciplineId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="专业类">
                <el-select v-model="form.professionalCategoryId"
                           clearable
                           :disabled="form.categoryId ? false : true"
                           @change="getProfessional()"
                           @clear="clearProfess()">
                  <el-option v-for="(item,index) in ProfessionalClassList"
                             :key="index"
                             :label="item.professionalClassName"
                             :value="item.professionalClassId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="专业">
                <el-select v-model="form.professionalId"
                           clearable
                           :disabled="form.professionalCategoryId ? false : true"
                           @change="getData()">
                  <el-option v-for="(item,index) in ProfessionalList"
                             :key="index"
                             :label="item.professionalName"
                             :value="item.professionalId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="课程类别">
                <el-select v-model="form.curriculumType"
                           clearable
                           @change="getData()">
                  <el-option label="理论课程"
                             :value="0"></el-option>
                  <el-option label="实训课程"
                             :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-input placeholder="请输入课程名称"
                          prefix-icon="el-icon-search"
                          v-model="form.curriculumName"
                          clearable
                          @keyup.enter.native="onSearch"></el-input>
              </el-form-item>
            </el-col>
          </el-form>
        </div>
      </div>
    </el-card>

    <el-card shadow="hover"
             class="card">
      <div class="flex-between mgb20">
        <div class="flex-center">
          <p class="hr_tag"></p>
          <span>课程列表</span>
        </div>
        <div>
          <el-button type="primary"
                     round
                     @click="addcourse"
                     v-auth>新增课程</el-button>
          <el-button type="primary"
                     round
                     @click="delAllSelection"
                     v-auth>批量删除</el-button>
        </div>
      </div>
      <el-table v-loading="loading"
                :data="courseData"
                class="table"
                ref="table"
                stripe
                header-align="center"
                @selection-change="handleSelectionChange"
                :row-key="getRowKeys">
        <el-table-column type="selection"
                         width="55"
                         align="center"
                         :reserve-selection="true"></el-table-column>
        <el-table-column type="index"
                         width="100"
                         label="序号"
                         align="center"></el-table-column>
        <el-table-column prop="curriculumName"
                         label="课程名称"
                         align="center"></el-table-column>
        <el-table-column prop="curriculumType"
                         label="课程类型"
                         align="center">
          <template slot-scope="scope">
            <span class="ellipsis">{{ courseTypeStatus[scope.row.curriculumType] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="userName"
                         label="创建人"
                         align="center"></el-table-column>
        <el-table-column label="配置的实训应用"
                         align="center">
          <template slot-scope="scope">
            <span class="ellipsis">{{ scope.row.sysName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderVolume"
                         label="订单量"
                         align="center"></el-table-column>
        <el-table-column prop="expectedCourse"
                         label="预计课时"
                         align="center"></el-table-column>
        <el-table-column label="上架/下架"
                         align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isShelves"
                       :active-value="1"
                       :inactive-value="0"
                       @change="changeSwitch($event, scope.row)"
                       v-auth="'/curriculum:上下架'">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       @click="edit(scope.row)"
                       v-auth>编辑</el-button>
            <el-button type="text"
                       @click="config(scope.row)"
                       v-auth>内容设置</el-button>
            <el-button type="text"
                       @click="handleDelete(scope.row)"
                       v-auth>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background
                       @current-change="handleCurrentChange"
                       :current-page="page"
                       layout="total, prev, pager, next"
                       :total="totals"></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import qs from 'qs'
export default {
  data () {
    return {
      courseTypeStatus: {
        0: "理论课程",
        1: "实训课程"
      },
      name: localStorage.getItem("ms_username"),
      courseData: [],
      form: {
        categoryId: +this.$route.query.categoryId || '',
        professionalCategoryId: +this.$route.query.professionalCategoryId || '',
        professionalId: +this.$route.query.professionalId || '',
        curriculumType: this.$route.query.curriculumType ? +this.$route.query.curriculumType : '',
        curriculumName: this.$route.query.curriculumName || ''
      },
      page: +this.$route.query.page || 1,
      pageSize: 10,
      totals: 0,
      subjectList: [], // 学科类别
      ProfessionalClassList: [], // 专业类
      ProfessionalList: [], // 专业
      multipleSelection: [],
      loading: false,
      searchTimer: null
    };
  },
  watch: {
    "form.curriculumName": function (val) {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.initData();
      }, 500);
    }
  },
  mounted () {
    this.getSubject();
    this.getData();
  },
  methods: {
    getRowKeys (row) {
      return row.cid;
    },
    // 获取列表数据
    getData () {
      const sid = this.$store.state.dataPer.find(e => e.permissionName === '课程管理')
      let data = {
        ...this.form,
        pageNum: this.page,
        pageSize: this.pageSize,
        supplierId: sid ? sid.supplierId : ''
      };
      this.$post(this.api.curriculumList, data).then(res => {
        this.courseData = res.page.records;
        this.totals = res.page.total;
        this.loading = false;
      }).catch(err => { });
    },
    initData () {
      this.page = 1;
      this.getData();
    },
    // 获取学科类别
    async getSubject () {
      const { list } = await this.$get(this.api.courseDiscipline)
      this.subjectList = list
      this.form.professionalCategoryId && this.getProfessionalClassData()
    },
    // 清除学科类别
    clearClass () {
      this.form.professionalCategoryId = ''
      this.form.professionalId = ''
    },
    // 获取专业类
    getProfessionalClass () {
      this.clearClass();
      this.getProfessionalClassData();
      this.page = 1;
      this.getData();
    },
    async getProfessionalClassData () {
      const { list } = await this.$get(this.api.courseProfessionalClass, {
        disciplineId: this.form.categoryId
      })
      this.ProfessionalClassList = list
      this.form.professionalId && this.getProfessionalData()
    },
    // 清除专业类
    clearProfess () {
      this.form.professionalId = ''
    },
    // 获取专业
    getProfessional () {
      this.clearProfess();
      this.getProfessionalData();
      this.page = 1;
      this.getData();
    },
    async getProfessionalData () {
      const { list } = await this.$get(this.api.courseProfessional, {
        professionalClassId: this.form.professionalCategoryId
      })
      this.ProfessionalList = list
    },
    // 缓存当前页面和参数，详情页返回到列表的时候直接取该url
    setReferrer () {
      this.$store.commit('setReferrer', `${this.$route.path}?${qs.stringify(this.form)}&page=${this.page}`)
    },
    // 新建课程
    addcourse () {
      this.setReferrer()
      this.$router.push("/addcurriculum");
    },
    // 编辑
    edit (row) {
      this.setReferrer()
      this.$router.push(`/addcurriculum?cid=${row.cid}`);
    },
    // 内容设置
    config (row) {
      this.setReferrer()
      this.$router.push(`/contentSettings?cid=${row.cid}&name=${row.curriculumName}`);
    },
    // 删除
    handleDelete (row) {
      this.$post(`${this.api.deleteCoursePrompt}?cids=${row.cid}`).then(({ status }) => {
        if (status === 200) {
          this.$confirm("确定要删除吗？", "提示", {
            type: "warning"
          }).then(() => {
            this.$post(`${this.api.delCourse}?cids=${row.cid}`).then(res => {
              this.getData();
              this.$message.success("删除成功");
            }).catch(err => { })
          }).catch(() => {
          });
        }
      }).catch(err => { })
    },
    // 处理多选
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    // 批量删除
    delAllSelection () {
      if (this.multipleSelection.length) {
        let cids = []
        this.multipleSelection.forEach(i => {
          cids.push('cids=' + i.cid)
        });
        this.$post(`${this.api.deleteCoursePrompt}?${cids.join('&')}`).then(({ status }) => {
          if (status === 200) {
            this.$confirm("确定要删除吗？", "提示", {
              type: "warning"
            }).then(() => {
              let ids = this.multipleSelection.map(i => i.cid);
              this.$post(`${this.api.delCourse}?cids=${ids.toString()}`).then(res => {
                if (ids.length == this.courseData.length) {
                  if (this.page > 1) {
                    this.page = this.page - 1
                  }
                }
                this.getData();
                this.$message.success("删除成功");
                this.$refs.table.clearSelection()
              }).catch(err => { })
            }).catch(() => { })
          }
        }).catch(err => { })
      } else {
        this.$message.warning("请先选择课程 ！");
      }
    },
    // 处理页码切换
    handleCurrentChange (val) {
      this.page = val;
      this.$router.push(`/curriculum?page=${val}`)
      this.getData();
    },
    // 课程名称条件搜索
    onSearch () {
      this.page = 1;
      this.getData();
    },
    // 上下架
    changeSwitch (value, row) {
      this.$post(`${this.api.isShelves}?cid=${row.cid}&isShelves=${value}`).then((res) => {
        this.getData();
        this.$message.success("修改上下架状态成功！");
      }).catch((res) => {
      });
    }
  }
};
</script>

<style scoped>
.card {
    min-height: calc(100vh - 300px);
}
</style>

