<template>
  <div class="edit-course-wrapper">
    <el-form
      ref="editcourse"
      :model="formInfo"
      label-width="120px"
      :rules="rules"
    >
      <el-form-item label="课程标题" prop="title">
        <el-input v-model="formInfo.title" />
      </el-form-item>
      <el-form-item label="课程副标题" prop="subTitle">
        <el-input v-model="formInfo.subTitle" />
      </el-form-item>
      <el-form-item label="课程类型" prop="type">
        <treeselect
          v-model="formInfo.type"
          :options="typeOptions"
          style="width: 120px;margin-left: 20px;"
        />
      </el-form-item>
      <el-form-item label="课程状态" prop="state">
        <el-select v-model="formInfo.state">
          <el-option
            v-for="item in courseStates"
            :key="item.label"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="封面图片">
        <div class="tool-import-cover-wrapper">
          <div class="import-cover-wrapper">
            <label style="width: 100%; height: 100%;">
              导入图片
              <input ref="importfile" type="file" hidden @change="importFile" />
            </label>
          </div>
        </div>
        <div class="progress-wrapper">
          <el-progress :percentage="progressPercent" />
        </div>
        <div>{{ formInfo.coverName }}</div>
        <!-- <img v-if="fileUrl" style="width: 400px;" :src="fileUrl" alt="没有导入图片"> -->
        <!-- <img v-if="formInfo.cover" :src="formInfo.cover" alt="没有导入图片"> -->
      </el-form-item>
      <el-form-item label="课程简介" prop="introduce">
        <el-input
          v-model="formInfo.introduce"
          type="textarea"
          autosize
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>
    <div class="submit-course-wrapper">
      <el-button size="medium" type="primary" @click="submitEditCourse"
        >提交</el-button
      >
    </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 { updateCourse } from "@/api/course.js";
export default {
  components: {
    Treeselect
  },
  data() {
    return {
      formInfo: {
        title: "",
        subTitle: "",
        type: "1",
        cover: "",
        introduce: ""
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入标题",
            trigger: "blur"
          }
        ],
        type: [
          {
            required: true,
            message: "请输入类型",
            trigger: "blur"
          }
        ],
        coverName: [
          {
            required: true,
            message: "请选择封面图片",
            trigger: "change"
          }
        ],
        introduce: [
          {
            required: true,
            message: "请选择课程简介",
            trigger: "blur"
          }
        ],
        state: [
          {
            required: true,
            message: "请选择课程状态",
            trigger: "change"
          }
        ],
        subTitle: [
          {
            required: true,
            message: "请输入课程副标题",
            trigger: "blur"
          }
        ]
      },
      progressPercent: 0,
      typeOptions: [],
      fileUrl: "",
      courseStates: [
        {
          label: "未发布",
          value: "未发布"
        },
        {
          label: "已发布",
          value: "已发布"
        },
        {
          label: "已关闭",
          value: "已关闭"
        }
      ]
    };
  },
  async mounted() {
    // alert(this.$route.params.name)
    // alert(this.$store.getters.course)
    console.log(this.$store.getters.course, "this.$store.getters.course");
    this.formInfo = {
      title: this.$store.getters.course.courseTitle,
      subTitle: this.$store.getters.course.courseSubTitle,
      type: this.$store.getters.course.categoryId,
      state: this.$store.getters.course.courseStatus,
      cover: null,
      coverName: this.$store.getters.course.courseCoverFilePath,
      introduce: this.$store.getters.course.courseBriefIntroduction,
      ...this.$store.getters.course
    };
    await this.getCourseCategory();
    // console.log(), 'this.$store.setCourse this.$store.setCourse')
  },
  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;
        });
        this.formInfo.type = res.content.filter(
          item => item.label === this.$store.getters.course.category
        )[0].id;
        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]);
          }
        }
        this.typeOptions = [...category];
      });
    },
    importFile() {
      if (this.$refs.importfile.files.length === 0) {
        // this.fileUrl = ''
        if (this.formInfo.cover) {
          this.formInfo.cover = null;
          this.formInfo.coverName = "";
        }
      } else {
        // this.fileUrl = URL.createObjectURL(this.$refs.importfile.files[0])
        console.log(
          this.formInfo.coverName,
          "this.formInfo.coverNamethis.formInfo.coverName"
        );
        this.formInfo.cover = this.$refs.importfile.files[0];
        console.log(
          this.formInfo.cover,
          "this.formInfo.cover this.formInfo.cover"
        );
        this.formInfo.coverName = this.$refs.importfile.files[0].name;
      }
    },
    submitEditCourse() {
      this.$refs.editcourse.validate(valid => {
        if (valid) {
          const updateFunc = progressEvent => {
            this.progressPercent = parseInt(
              "" + progressEvent.loaded / progressEvent.total
            );
          };
          const data = {
            categoryId: this.formInfo.type,
            courseBriefIntroduction: this.formInfo.introduce,
            courseStatus: this.formInfo.state,
            courseSubTitle: this.formInfo.subTitle,
            courseTitle: this.formInfo.title,
            id: this.formInfo.id
          };
          const formData = new FormData();
          for (const key in data) {
            formData.append(key, data[key]);
          }
          // if (this.formInfo.coverName && this.formInfo.cover) {
          //   data.courseCoverFile = this.formInfo.cover
          // }
          if (this.formInfo.cover) {
            formData.append("courseCoverFile", this.formInfo.cover);
          }
          updateCourse(formData, updateFunc)
            .then(res => {
              console.log(res, "updateCourse");
              this.$message({
                type: "success",
                message: "修改成功"
              });
            })
            .catch(() => {
              this.$message.error("修改失败");
            });
        }
      });
    }
  }
};
</script>

<style lang="scss">
.edit-course-wrapper {
  padding: 10px;
  border-radius: 5px;
  margin: 10px 10px;
  max-width: 777px;
  .submit-course-wrapper {
    display: flex;
    justify-content: flex-end;
  }
}
.tool-import-cover-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 600px;
  .import-cover-wrapper {
    width: 200px;
    height: 100px;
    background: #a1a1a1;
    color: white;
    font-size: 18px;
    text-align: center;
    line-height: 100px;
  }
  .progress-wrapper {
    flex-grow: 1;
  }
}
</style>
