<template>
  <div class="add-course-wrapper">
    <el-form
      ref="addcourse"
      :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="type">
        <treeselect v-model="formInfo.type" :options="typeOptions" style="width: 320px;" />
      </el-form-item>
      <el-form-item label="课程副标题" prop="subTitle">
        <el-input v-model="formInfo.subTitle" />
      </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="封面图片" prop="coverName">
        <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($event)">
            </label>
          </div>
          <div class="progress-wrapper">
            <el-progress :percentage="progressPercent" />
          </div>
        </div>
        <img v-if="fileUrl" style="width: 400px;" :src="fileUrl" 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="submitCourse">提交</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 {
  createCourse
} from '@/api/course.js'
export default {
  name: 'Addcourse',
  components: {
    Treeselect
  },
  data() {
    return {
      formInfo: {
        title: '',
        type: '',
        coverName: '',
        cover: null,
        introduce: '',
        state: '已关闭',
        subTitle: ''
      },
      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'
          }
        ]
      },
      courseStates: [
        {
          label: '未发布',
          value: '未发布'
        },
        {
          label: '已发布',
          value: '已发布'
        },
        {
          label: '已关闭',
          value: '已关闭'
        }
      ],
      progressPercent: 0,
      typeOptions: [
        {
          id: 1,
          label: 'a',
          children: [
            {
              id: 12,
              label: 'aa'
            },
            {
              id: 13,
              label: 'ab'
            }
          ]
        }, {
          id: 2,
          label: 'b',
          children: []
        },
        {
          id: 3,
          label: 'c',
          children: []
        }
      ],
      fileUrl: ''
    }
  },
  async mounted() {
    await this.getCourseCategory()
  },
  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])
          }
        }
        this.typeOptions = [...category]
        if (this.typeOptions.length > 0) {
          this.formInfo.type = this.typeOptions[0].id
        }
      })
    },
    // 导入图片
    importFile($event) {
      console.log($event)
      console.log($event.target)
      console.log(this.$refs.importfile.files, 'files')
      if (this.$refs.importfile.files.length === 0) {
        this.fileUrl = ''
        this.formInfo.coverName = ''
        this.formInfo.cover = null
      } else {
        this.fileUrl = URL.createObjectURL(this.$refs.importfile.files[0])
        this.formInfo.coverName = this.$refs.importfile.files[0].name
        this.formInfo.cover = this.$refs.importfile.files[0]
      }
    },
    // 提交课程
    submitCourse() {
      this.$refs.addcourse.validate((valid) => {
        if (valid) {
          // this.$refs.addcourse
          const data = {
            categoryId: this.formInfo.type,
            courseBriefIntroduction: this.formInfo.introduce,
            courseStatus: this.formInfo.state,
            courseSubTitle: this.formInfo.subTitle,
            courseTitle: this.formInfo.title,
            courseCoverFile: this.formInfo.cover
          }
          const formData = new FormData()
          for (const key in data) {
            formData.append(key, data[key])
          }
          const updateFunc = (progressEvent) => {
            this.progressPercent = parseInt('' + progressEvent.loaded / progressEvent.total)
          }
          createCourse(formData, updateFunc).then(res => {
            this.$message.success({
              type: 'success',
              message: '添加成功'
            })
            this.formInfo.title = ''
            this.formInfo.introduce = ''
            this.formInfo.subTitle = ''
          }).catch(() => {
            this.$message.error('添加失败')
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
  .add-course-wrapper {
    padding: 30px;
    width: 80%;
    margin: 30px auto;
    box-shadow: 0 0 9px 1px #eee;
    border-radius: 30px;
    .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>
