<template>
  <div :class="{'course-manage':true,'v-page':showButton}" v-loading="loading">
    <SearchTreeMenu
      v-if="showButton"
      title="课程分类列表"
      :tree-data="classifyList_tree"
      @onCreate="createClassify"
      @onDelete="deleteClassify"
      @current-change="classifyChange"
      @onEdit="onEditClassify"
    />
    <div class="v-ctx block">
      <div class="search-bar">
        <SearchInput v-model="searchValue" />
        <div>
          <el-button
            type="danger"
            v-if="showButton"
            round
            @click="deleteCourse()"
          >删除选中</el-button>
          <el-button type="primary" v-if="showButton" round @click="toAddCourse">添加课程</el-button>
        </div>
      </div>

      <TableLayout
        :column="column"
        :data="courseList"
        :pageInfo="pageInfo"
        :selection="showButton"
        @current-change="pageChange"
        @size-change="pageSizeChange"
        @selection-change="selectionChange"
      >
        <template v-slot:action="props">
          <el-button
            type="text"
            icon="el-icon-star-off"
            @click="$router.push({path:'/online-course/course-manage/course-evaluate/'+props.row.id})"
            >评价</el-button
          >
          <el-button
            type="text"
            icon="el-icon-chat-line-round"
            @click="$router.push({path:'/online-course/course-manage/course-comment/'+props.row.id})"
            >讨论</el-button
          >
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="editorCourse(props.row)"
            >编辑</el-button
          >
          <el-button
            style="color: red"
            type="text"
            icon="i-j-ksap-shanchu"
            @click="deleteCourse(props.row)"
            >删除</el-button
          >
        </template>
        <template v-slot:createTime="props">
          {{ new Date(props.row.createTime).format("yyyy-MM-dd") }}
        </template>
        <template v-slot:difficulty="props">
          {{ difficulty[props.row.difficulty].name }}
        </template>
        <template v-slot:status="props">
          <el-switch
            v-model="props.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            @change="setCourseStatus(props.row)"
          >
          </el-switch>
        </template>
      </TableLayout>
    </div>
  </div>
</template>

<script>
import { SearchTreeMenu, TableLayout } from '@/components/layout'
import SearchInput from '@/components/widget/QueryInput.vue'
import {
  getCourseClassfiyApi,
  addCourseClassfiyApi,
  deleteCourseClassfiyApi,
  getCourseListApi,
  setCourseStatusApi,
  searchCourseListApi,
  deleteCourseApi,
  editorCourseClassfiyApi
} from '@/api/online-course/online-course'
import { dataReportMixin } from '@/utils/data-report'
export default {
  components: { TableLayout, SearchTreeMenu, SearchInput },

  props: {
    showButton: { type: Boolean, default: true }
  },

  data () {
    return {
      classifyList_tree: [],
      classifyList_map: [],
      nowCheckClassify: undefined,
      courseList: [],
      loading: false,
      checkedCourseList: [],
      difficulty: {
        1: { name: '初级', id: 1 },
        2: { name: '中级', id: 1 },
        3: { name: '高级', id: 1 }
      },
      column: [
        { prop: 'name', label: '课程名称', align: 'center', 'show-overflow-tooltip': true, width: 300 },
        { prop: 'classifyName', label: '课程分类', align: 'center' },
        { prop: 'sectionCount', label: '章节数', align: 'center' },
        { prop: 'difficulty', label: '课程难度', align: 'center' },
        { prop: 'status', label: '课程状态', align: 'center' },
        { prop: 'createTime', label: '创建时间', align: 'center' },
        { prop: 'creator_name', label: '创建人', align: 'center' },
        { prop: 'action', label: '操作', align: 'center', width: '240' }
      ],
      pageInfo: { page: 1, pageSize: 10, total: 0 },
      // 搜索内容
      searchValue: '',
      // 搜索间隔时间
      searhTimeout: null
    }
  },
  created () {
    this.getClassifyList()
  },
  methods: {
    /**
     * 新建分类
     */
    async createClassify (node) {
      this.$prompt('请输入分类名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.{1,}/,
        inputErrorMessage: '分类名称不可为空'
      })
        .then(async ({ value }) => {
          const newClassify = {
            name: value,
            pid: node ? node.id : 0,
            level: node ? node.level + 1 : 0
          }
          await addCourseClassfiyApi(newClassify)
          this.$message.success(`添加分类 ${value} 成功`)
          this.getClassifyList()
        })
    },
    // 编辑分类
    onEditClassify (e) {
      if (!e.id) {
        this.$message.warning('顶级分类不支持编辑')
        return
      }
      this.$prompt('请输入修改的分类名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.{1,}/,
        inputErrorMessage: '分类名称不可为空'
      })
        .then(async ({ value }) => {
          const newClassify = {
            id: e.id,
            name: value
          }
          await editorCourseClassfiyApi(newClassify)
          this.$message({ type: 'success', message: '分类编辑成功' })
          this.getClassifyList()
        })
    },
    /**
     * 获取分类列表
     */
    async getClassifyList () {
      const { data } = await getCourseClassfiyApi()
      const tree = data.toTree()
      this.classifyList_tree = tree.tree
      this.nowCheckClassify = this.classifyList_tree[0]

      this.classifyList_map = []
      for (const k in tree.map) {
        tree.map[k].label = tree.map[k].name
        tree.map[k].value = tree.map[k].id
        this.classifyList_map.push(tree.map[k])
      }
    },

    async classifyChange (e) {
      this.nowCheckClassify = e
      this.getCourseList()
    },
    /**
     * 获取课程列表
     */
    async getCourseList () {
      const sendData = {
        ...this.pageInfo,
        classify: this.nowCheckClassify ? this.nowCheckClassify.id : 0
      }
      const { data } = await getCourseListApi(sendData)
      this.formatCourseList(true, data)
    },
    /**
     * 处理课程数据至需要的格式
     */
    formatCourseList (type, data) {
      if (type) {
        this.pageInfo.total = data.total
        // 处理分类信息
        data.data.forEach((course) => {
          course.creator_name = course.creator_info
            ? course.creator_info.name
            : ''
          const index = this.classifyList_map.findIndex((item) => {
            if (item.id === course.classify) {
              return true
            }
            return false
          })
          if (index !== -1) {
            course.classifyName = this.classifyList_map[index].name
          }
        })
        this.courseList = data.data
      }
    },
    /**
     * 课程列表页面变化
     */
    pageChange (e) {
      if (typeof e === 'number') {
        this.pageInfo.page = e
        this.getCourseList()
      }
    },
    /**
     * 删除课程  可批量删除
     */
    deleteCourse (data) {
      if (data || (!data && this.checkedCourseList.length > 0)) {
        let res = {}
        this.$confirm('当前选中的课程删除后将不可恢复,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            if (data) {
              res = await deleteCourseApi({ id: data.id })
            } else {
              const id = this.checkedCourseList.map((course) => course.id)
              res = await deleteCourseApi({ id })
            }
            if (res.code === 0) {
              this.$message.success('删除成功！')
              this.getCourseList()
            } else {
              throw res
            }
          })
          .catch((err) => {
            if (err && err !== 'cancel') {
              this.$message.error(err.toString())
            } else {
              // this.$message('取消删除')
            }
          })
      } else {
        this.$message.warning('请选择需要删除的项目')
      }
    },
    /**
     * 课程列表页面每页显示数量变化
     */
    pageSizeChange (e) {
      this.pageInfo.page = 1
      this.pageInfo.pageSize = e
      this.getCourseList()
    },
    selectionChange (e) {
      this.checkedCourseList = e
    },
    // 编辑课程
    async editorCourse (course) {
      this.$router.push('/online-course/course-manage/edit-coures/' + course.id)
    },
    /**
     * 删除分类
     */
    async deleteClassify (node) {
      if (!node.id) {
        this.$message.warning('顶级分类，不允许删除')
        return
      }
      const delList = this.getAllDescendantClassify(node.id)
      delList.push(node.id)

      this.$confirm('此操作将永久此分类，及其子级分类，请确认后删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.loading = true
          await deleteCourseClassfiyApi({ id: delList })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getClassifyList()
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
      this.getClassifyList()
    },
    /**
     * 删除分类时查找所有子级
     */
    getAllDescendantClassify (id) {
      const levelBox = []
      this.classifyList_map.forEach((item) => {
        if (item.pid === id) {
          levelBox.push(item.id)
        }
      })
      if (levelBox.length > 0) {
        levelBox.forEach((item) => {
          const son = this.getAllDescendantClassify(item)
          if (son.length > 0) levelBox.push(...son)
        })
      }
      return levelBox
    },
    /**
     * 修改课程状态
     */
    async setCourseStatus (rowData) {
      await setCourseStatusApi({
        id: rowData.id,
        status: rowData.status ? 1 : 0
      })
    },
    /**
     * 搜索课程列表
     */
    async searchCourseList () {
      const value = this.searchValue.trim()
      const sendData = {
        pageSize: this.pageInfo.pageSize,
        page: 1,
        value,
        classify: this.nowCheckClassify ? this.nowCheckClassify.id : 0
      }
      const { data } = await searchCourseListApi(sendData)

      this.formatCourseList(true, data)
    },
    toAddCourse () {
      this.$router.push('/online-course/course-manage/add-coures')
    }
  },
  watch: {
    nowCheckClassify () {
      this.pageInfo.page = 1
      this.getCourseList()
    },
    searchValue () {
      if (this.searhTimeout) {
        clearTimeout(this.searhTimeout)
        this.searhTimeout = null
      }
      this.searhTimeout = setTimeout(() => {
        this.searchCourseList()
      }, 500)
    },
    showButton: {
      deep: true,
      immediate: true,
      handler: function (newD, oldD) {
        if (!newD) {
          this.column.splice(0, 0)
          this.column.splice(this.column.length - 1, 1)
        }
      }
    }
  },

  mixins: [
    /**
     * 数据上报
     */
    dataReportMixin('ONLINE_COURSE')
  ]
}
</script>

<style lang="scss" scoped>
.v-page {
  position: relative;
}
.course-manage {
  width: 100%;
  display: flex;
  ::v-deep .table_layout {
    position: relative;
    z-index: 1;
  }
}
.course-classify-tree {
  width: 300px;
}
.search-bar {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.course-manage{
  width: 100%;
}
</style>
