<template>
  <div class="total-wrapper">
    <div class="teach-tools-add-wrapper">
      <el-button type="primary" @click="addCoure">新增</el-button>
    </div>
    <div class="teach-search-wrapper">
      <el-input
        v-model="inputSearchName"
        style="width: 280px;"
        placeholder="请输入课程名称"
      />
      <treeSelect
        v-model="inputChosenType"
        style="width: 260px;margin-left: 20px;"
        :options="typeOptions"
      />
      <el-select
        v-model="inputChosenState"
        style="margin-left: 20px;"
        placeholder="课程状态"
      >
        <el-option
          v-for="item in courseStateList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        v-model="inputChosenDate"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="margin-left: 20px;"
      />
      <el-input
        v-model="inputCreator"
        style="width: 180px;margin-left: 20px;"
        placeholder="请输入发布人"
      />
      <el-button style="margin-left: 20px;" type="success" @click="getAllCourse"
        >查询</el-button
      >
    </div>
    <div class="table-wraperr">
      <el-table :data="courseList">
        <el-table-column label="课程名称" width="180">
          <template slot-scope="scope">
            <div
              style="color: skyblue;cursor: pointer;"
              @click="jumpToClassHour(scope.row)"
            >
              {{ scope.row.courseName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100" />
        <el-table-column prop="studentSum" label="学生数" width="120" />
        <el-table-column prop="courseState" label="课程状态" width="180" />
        <el-table-column label="创建者/时间" width="180">
          <template slot-scope="scope">
            <div>{{ scope.row.creator }}</div>
            <div>{{ scope.row.createDateTime }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="580">
          <template slot-scope="scope">
            <div class="tool-manage-wrapper">
              <el-button size="medium" @click="manageCourse(scope.row)"
                >管理</el-button
              >
              <div class="other-manage-wrapper">
                <el-button size="medium" @click="publicCourse(scope.row)"
                  >发布课程</el-button
                >
                <el-button size="medium" @click="deleteCourse(scope.row)"
                  >删除课程</el-button
                >
                <el-button size="medium" @click="closeCourse(scope.row)"
                  >关闭课程</el-button
                >
                <el-button size="medium" @click="manageStu">学生管理</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="curPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalElement"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import TreeSelect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getOnlineTrainingCategory } from "@/api/coursecategory.js";
import { findCourse, updateCourse, onlineTraining } from "@/api/course.js";
import { parseTime } from "../../utils";
import {} from "@/api/course.js";
export default {
  name: "Teach",
  components: {
    TreeSelect
  },
  data() {
    return {
      // 搜索的名称
      inputSearchName: "",
      // 选择的分类
      inputChosenType: "1",
      typeOptions: [],
      courseStateList: [
        {
          label: "全选",
          value: "全选"
        },
        {
          label: "未发布",
          value: "未发布"
        },
        {
          label: "已发布",
          value: "已发布"
        },
        {
          label: "已关闭",
          value: "已关闭"
        }
      ],
      // 选择的课程状态
      inputChosenState: "",
      // 选择的日期
      inputChosenDate: "",
      // 创建人
      inputCreator: "",
      // 课程列表
      courseList: [
        {
          courseName: "大学习、大培训、大考试",
          price: "8888.00",
          studentSum: 154,
          creator: "陈老师",
          createDateTime: "2021-10-00 14:43:32",
          courseState: "已发布"
        },
        {
          courseName: "安全管理员【换证】新",
          price: "300.00",
          studentSum: 127,
          creator: "陈老师",
          createDateTime: "2021-03-31 14:42:32",
          courseState: "已发布"
        }
      ],
      // 当前页码
      currentPage: 1,
      curPageSize: 10,
      totalElement: 10
    };
  },
  async mounted() {
    await this.getCourseCategory();
    await this.getAllCourse();
  },
  methods: {
    async getCourseCategory() {
      const params = {
        page: 0,
        size: 99999
      };
      await getOnlineTrainingCategory(params).then(res => {
        console.log(res, "getOnlineTrainingCategory getOnlineTrainingCategory");
        res.content.forEach(item => {
          item.children = [];
          item.isShow = false;
          item.level = 1;
          item.label = item.name;
        });
        const category = [];
        // 给指定父 id 元素添加元素
        function addType(item) {
          const pid = item.pid;
          const id = item.id;
          // 判断自己是否已经添加过
          let isAdded = false;
          function isAddElement(item1) {
            if (item1.id === id) {
              isAdded = true;
            }
            for (const item2 of item1.children) {
              isAddElement(item2);
            }
          }

          function addElement(item1) {
            if (item1.id === pid) {
              item1.children.push(item);
              item.level = item1.level + 1;
              return;
            }
            for (const item2 of item1.children) {
              addElement(item2);
            }
          }
          for (const ele of category) {
            isAddElement(ele);
          }
          if (isAdded === false) {
            for (const ele of category) {
              addElement(ele);
            }
          }
        }
        function composeCategory(pid) {
          if (!pid) {
            for (let i = 0; i < res.content.length; i++) {
              if (res.content[i].pid) {
                composeCategory(res.content[i].pid);
                addType(res.content[i]);
              }
            }
          }
          if (pid) {
            for (let i = 0; i < res.content.length; i++) {
              if (res.content[i].id === pid && res.content[i].pid) {
                composeCategory(res.content[i].pid);
                addType(res.content[i]);
                // res.content[i].level = category[category.length - 1].level + 1
                // category[category.length - 1].children.push(res.content[i])
              } else if (res.content[i].id === pid && !res.content[i].pid) {
                if (!category.filter(item => item.id === pid).length) {
                  category.push(res.content[i]);
                }
              }
            }
          }
        }
        composeCategory();
        for (let i = 0; i < res.content.length; i++) {
          const pArray = category.filter(item => item.id === res.content[i].id);
          if (!pArray.length && !res.content[i].pid) {
            category.push(res.content[i]);
          }
        }
        function removeChildrenOfNull(arr1) {
          for (let i = 0; i < arr1.length; i++) {
            if (arr1[i].children.length === 0) {
              delete arr1[i].children;
            } else {
              removeChildrenOfNull(arr1[i].children);
            }
          }
        }
        removeChildrenOfNull(category);
        this.typeOptions = [...category];
        this.typeOptions.unshift({
          createBy: "admin",
          createTime: "2022-01-20 14:33:57",
          description: "213",
          id: -1,
          isShow: false,
          label: "全选",
          level: 1,
          name: "全选",
          pid: 6,
          updateBy: "admin",
          updateTime: "2022-01-20 14:33:57"
        });
        console.log(this.typeOptions, "this.typeOptions this.typeOptions");

        if (this.typeOptions.length > 0) {
          this.inputChosenType = this.typeOptions[0].id;
        }
      });
    },
    async getAllCourse() {
      const params = {
        page: this.currentPage - 1,
        size: this.curPageSize
      };
      if (this.inputSearchName) {
        params.courseTitle = this.inputSearchName;
      }
      if (this.inputChosenType !== -1) {
        if (this.inputChosenType) {
          params.categoryId = this.inputChosenType;
        }
      }
      if (this.inputChosenState !== "全选") {
        if (this.inputChosenState) {
          params.courseStatus = this.inputChosenState;
        }
      }
      if (this.inputCreator) {
        params.courseTeacher = this.inputCreator;
      }
      if (this.inputChosenDate instanceof Array) {
        params.courseStartCreateTime = parseTime(this.inputChosenDate[0]);
        params.courseEndCreateTime = parseTime(this.inputChosenDate[1]);
      }
      findCourse(params).then(res => {
        console.log(res, "findCourse findCourse");
        this.courseList = [
          ...res.content.map(item => {
            return {
              ...item,
              courseName: item.courseTitle,
              creator: item.courseTeacher,
              createDateTime: item.courseCreateTime,
              courseState: item.courseStatus
            };
          })
        ];
        this.totalElement = res.totalElements;
      });
    },
    handleSizeChange(val) {
      this.curPageSize = val;
      this.getAllCourse();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getAllCourse();
    },
    addCoure() {
      // 新增课程
      // 跳转到新增课程的网页
      this.$router.push({
        path: "/train/teach/addcourse"
      });
    },
    manageCourse(row) {
      // 跳转到管理课程页面
      row.categoryId = this.inputChosenType;
      const newObj = { ...row };
      console.log(newObj, "newObj newObj newObj");
      this.$store.dispatch("setCourse", newObj).then(() => {
        this.$router.push({
          path: "/train/teach/editcourse/" + row.id
        });
      });
    },
    // 删除课程
    deleteCourse(row) {
      this.$confirm("此操作将永久删除该课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          onlineTraining([row.id])
            .then(res => {
              this.getAllCourse();
              this.$message({
                type: "success",
                message: "删除成功"
              });
            })
            .catch(() => {
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    publicCourse(row) {
      const formData = new FormData();
      const data = {
        categoryId: this.inputChosenType,
        courseBriefIntroduction: row.courseBriefIntroduction,
        courseStatus: "已发布",
        courseSubTitle: row.courseSubTitle,
        courseTitle: row.courseTitle,
        id: row.id
      };
      for (const key in data) {
        formData.append(key, data[key]);
      }
      updateCourse(formData, () => {})
        .then(res => {
          this.$message({
            type: "success",
            message: "修改成功"
          });
          this.getAllCourse();
        })
        .catch(() => {
          this.$message.error("修改失败");
        });
    },
    closeCourse(row) {
      const formData = new FormData();
      const data = {
        categoryId: this.inputChosenType,
        courseBriefIntroduction: row.courseBriefIntroduction,
        courseStatus: "已关闭",
        courseSubTitle: row.courseSubTitle,
        courseTitle: row.courseTitle,
        id: row.id
      };
      for (const key in data) {
        formData.append(key, data[key]);
      }
      updateCourse(formData, () => {})
        .then(res => {
          this.$message({
            type: "success",
            message: "修改成功"
          });
          this.getAllCourse();
        })
        .catch(() => {
          this.$message.error("修改失败");
        });
    },
    jumpToClassHour(row) {
      // row
      console.log(row.id, "row.id row.id");
      this.$router.push({
        path: "/train/teach/addcoursehour/" + row.id
      });
    },
    manageStu() {
      this.$router.push({
        path: "/train/teach/student/333333333"
      });
    }
  }
};
</script>

<style lang="scss">
.total-wrapper {
  padding: 10px;
  border-radius: 5px;
  margin: 10px 10px;
  .teach-tools-add-wrapper {
    padding: 10px;
    border-radius: 5px;
    margin: 10px 10px;
    background: #fff;
  }
  .teach-search-wrapper {
    padding: 10px;
    border-radius: 5px;
    margin: 10px 10px;
    background: #fff;
  }
  .table-wraperr {
    padding: 10px;
    border-radius: 5px;
    margin: 10px 10px;
    background: #fff;
  }
}
.teach-search-wrapper {
  margin: 15px 0;
  display: flex;
  align-items: center;
}
.tool-manage-wrapper {
  display: flex;
  .other-manage-wrapper {
    display: none;
  }
  &:hover {
    .other-manage-wrapper {
      margin-left: 20px;
      display: flex;
    }
  }
}
</style>
