<!--  -->
<template>
  <div class="add-course">
    <courseInfo
      :error_input="error_input"
      :classify="classify"
      :isStudy="isStudy"
      :nowCheckCourse="nowCheckCourse"
    ></courseInfo>
    <h2 class="v-title" v-if="isStudy">课程统计</h2>
    <CourseStatistices
      v-if="isStudy"
      :nowCheckCourse="nowCheckCourse"
    ></CourseStatistices>
    <h2 class="v-title">课程章节</h2>
    <CourseSection
      @startStudy="startStudy"
      ref="CourseSection"
      :isStudy="isStudy"
      :baseCourseForm="baseCourseForm"
    ></CourseSection>

    <h2
      class="v-title"
      style="margin: 10px 0"
      v-if="(isStudy && baseCourseForm.exercise.length > 0) || !isStudy"
    >
      课后习题
    </h2>
    <PaperSelectQuestionTable
      v-if="questionInfo"
      ref="QuestionTable"
      style="width: 60%; margin: 10px"
      :isMounted="true"
      @current-change="changeQuestionsInfo"
      :questionData="questionInfo"
    >
    </PaperSelectQuestionTable>
    <div v-else-if="isStudy && baseCourseForm.exercise.length > 0" style="padding-bottom: 10px; display: flex" >
      <el-tag style="margin-right: 10px"
        >{{ baseCourseForm.exercise.length }} 道试题</el-tag
      >
      <buttonSelftVue
        :width="'100px'"
        icon=""
        @click="
          () => {
            if (!baseCourseForm.exercise?.length) {
              $message.warin('当前课程无试题！');
              return;
            }
            $router.push({
              path: '/online-course/my-course/course-exercies',
              query: { recordId: nowCheckCourse.id, model: 1 },
            });
            $refs['CourseSection'].nowStudyCourseware = false;
          }
        "
        >开始做题</buttonSelftVue
      >
      <buttonSelftVue
        :width="'100px'"
        :icon="''"
        @click="
          () => {
            if (!baseCourseForm.exercise?.length) {
              $message.warin('当前课程无试题！');
              return;
            }
            $router.push({
              path: '/online-course/my-course/course-exercies',
              query: { recordId: nowCheckCourse.id, model: 1, viewer: true },
            });
            $refs['CourseSection'].nowStudyCourseware = false;
          }
        "
        >查看答卷</buttonSelftVue
      >
    </div>
    <h2 class="v-title" style="position: relative" v-if="!isStudy">选取学员</h2>
    <div class="check-student-org" v-if="!isStudy">
      <div class="form-item">
        <!-- <span class="form-label"
          >所属班级：
          <i class="must-write">*</i>
        </span> -->
        <div class="form-input">
          <el-cascader
            :class="error_input.studyOrgId && 'error-input'"
            size="mini"
            style="width: 300px"
            :options="orgList"
            v-model="baseCourseForm.studyOrgId"
            :placeholder="'请选择需要学习的相关班级'"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            clearable
          ></el-cascader>
        </div>
      </div>
    </div>
    <h2 class="v-title" style="margin: 10px 0" v-if="!isStudy">互动设置</h2>
    <CourseEvealuate
      :nowCheckCourse="nowCheckCourse"
      :isStudy="isStudy"
      :courseDimensionality="courseDimensionality"
      :studentDimensionality="studentDimensionality"
      @addDimensionality="addDimensionality"
      @dleteInput="dleteInput"
    ></CourseEvealuate>

    <h2
      v-if="this.baseCourseForm.openDiscussion && isStudy"
      class="v-title"
      style="margin: 30px 0 0 0"
    >
      评论
      <span style="font-size: 12px"
        >{{ this.nowCheckCourse.openDiscussion
        }}{{ this.nowCheckCourse.discussion.length }}</span
      >
    </h2>
    <CourseDisscuss
      v-if="this.baseCourseForm.openDiscussion && isStudy"
      :nowCheckCourse="nowCheckCourse"
    ></CourseDisscuss>
    <div class="add-course-buttom">
      <div class="add-course-buttom-fixed" v-if="!isStudy">
        <el-button plain @click="$emit('close_addCourse')">取消</el-button>
        <el-button type="primary" style="margin-left: 100px" @click="saveCourse"
          >保存</el-button
        >
      </div>
      <div class="add-course-buttom-fixed" v-else>
        <el-button type="danger" @click="$emit('close_addCourse')"
          >退出学习</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { findAllOrgApi } from '@/api/system/org'
// import { deepClone } from '../../utils'
import CourseSection from './course-section.vue'
import courseInfo from './course-info.vue'
import {
  addCourseApi,
  editorCourseApi
} from '@/api/online-course/online-course'
import PaperSelectQuestionTable from '@/views/assessment-evaluation/examination-paper-manage/add-modify-paper/components/PaperSelectQuestionTable.vue'
import CourseStatistices from './course-statistics.vue'
import CourseEvealuate from './course-evaluate.vue'
import buttonSelftVue from '../button-selft.vue'
import { uploadApi } from '@/api/system'
import CourseDisscuss from '../course-disscuss.vue'
export default {
  props: {
    classify: { type: Array, required: true },
    nowCheckCourse: { type: Object, required: true },
    isStudy: { type: Boolean, default: false }
  },
  // import引入的组件需要注入到对象中才能使用
  components: {
    CourseSection,
    courseInfo,
    CourseStatistices,
    CourseEvealuate,
    PaperSelectQuestionTable,
    buttonSelftVue,
    CourseDisscuss
  },
  data () {
    // 这里存放数据
    return {
      rules: [],
      orgList: [],
      baseCourseForm: {},
      classifyOptions: {},
      // 学员的评价维度
      studentDimensionality: [],
      // 课程的评价维度
      courseDimensionality: [],
      // 暂存删除在服务器中有记载的评价维度
      saveEvealGradeList: [],
      // 输入框填写有误的对象
      error_input: {},
      // 当前选中的练习题
      nowCheckExercises: null,
      questionInfo: undefined
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    if (!this.isStudy) {
      this.baseCourseForm = this.nowCheckCourse
      this.exerciseFormat()
    } else {
      this.baseCourseForm = this.nowCheckCourse.courseInfo
      this.baseCourseForm.recordInfo = this.nowCheckCourse
    }
    this.getOrgList()
    this.manageDimensionality(true)
  },
  // 方法集合
  methods: {
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },

    //
    // 添加新维度
    addDimensionality (type) {
      let noDleList = []
      const typeKey = type ? 'studentDimensionality' : 'courseDimensionality'

      noDleList = this[typeKey].filter((item) => {
        if (!item.id || !item.delFlag) {
          return true
        }
        return false
      })

      if (noDleList.length >= 5) {
        this.$message.warning('只支持5个评价维度！')
        return
      }
      this[typeKey].push({
        courseId: this.baseCourseForm.id,
        dimensionality: '',
        type,
        delFlag: 0
      })
    },
    // 删除当前课程评价维度中的输入框
    dleteInput (array, index) {
      if (array[index].id) {
        this.saveEvealGradeList.push(array[index])
        array[index].delFlag = 1
        array.splice(index, 1)
      } else {
        array.splice(index, 1)
      }
    },
    // 保存课程信息
    async saveCourse () {
      try {
        if (this.checkInfoOk()) {
          this.manageDimensionality()
          const newForm = this.baseCourseForm
          if (!newForm.id) {
            newForm.creator = this.$store.user.id
          }
          if (newForm.cover instanceof File) {
            const { data } = await uploadApi(newForm.cover, {
              type: 'course-cover'
            })
            newForm.cover = data.diskname
          }
          newForm.updater = this.$store.user.id
          newForm.evalDimension.push(...this.saveEvealGradeList)
          const noDelSection = this.baseCourseForm.courseSectionContent.filter(
            (item) => {
              if (!item.delFlag) {
                return true
              }
              return false
            }
          )
          newForm.sectionCount = noDelSection.length
          if (Array.isArray(newForm.classify)) {
            newForm.classify = newForm.classify[newForm.classify.length - 1]
          }
          if (Array.isArray(newForm.studyOrgId)) {
            newForm.studyOrgId =
              newForm.studyOrgId[newForm.studyOrgId.length - 1]
          }
          let res
          if (newForm.id) {
            res = await editorCourseApi(newForm.id, newForm)
          } else {
            res = await addCourseApi(newForm)
          }
          if (res.code !== 0) {
            // eslint-disable-next-line no-throw-literal
            throw '保存失败,错误详情请查看控制台'
          }
          this.$emit('close_addCourse')
        }
      } catch (error) {
        this.$message.error(error)
      }
    },
    checkInfoOk () {
      const form = this.baseCourseForm
      this.error_input = {}
      const errorList = []
      if (!form.name) {
        this.error_input.name = true
        errorList.push('名称')
      }
      if (!form.classify && form.classify !== 0) {
        this.error_input.classify = true
        errorList.push('分类')
      }
      if (!form.studyOrgId) {
        this.error_input.studyOrgId = true
        errorList.push('学习班级')
      }
      let badCourseName = false
      let badCourse = false
      let badEveal = false
      this.baseCourseForm.courseSectionContent.forEach((item) => {
        if (!item.delFlag && item.name.trim().length <= 0) {
          badCourseName = true
        }
        if (!item.delFlag && item.courseware) {
          const coursewares = item.courseware.filter((cw) => {
            if (!cw.delFlag) {
              return true
            }
            return false
          })
          if (coursewares && coursewares.length < 1) {
            badCourse = true
          }
        }
      })
      if (this.baseCourseForm.txtOrGradeEvealute) {
        this.courseDimensionality.forEach((item) => {
          if (
            !item.delFlag &&
            item.dimensionality.trim().length < 1 &&
            item.type === 0
          ) {
            badEveal = true
          }
        })
      }
      if (this.baseCourseForm.textOrGradeSelfEval) {
        this.studentDimensionality.forEach((item) => {
          if (
            !item.delFlag &&
            item.dimensionality.trim().length < 1 &&
            item.type === 1
          ) {
            badEveal = true
          }
        })
      }
      if (badCourseName) {
        errorList.push('所有章节的名称')
      }
      if (badEveal) {
        errorList.push('各个评价维度标题')
      }
      if (badCourse) {
        errorList.push('每个章节的课件不可为空')
      }
      if (this.baseCourseForm.courseSectionContent.length <= 0) {
        errorList.push('课程章节')
      }
      if (errorList.length > 0) {
        this.$message.error(`课程【${errorList.join('、')},】不可为空`)
        return false
      } else {
        return true
      }
    },
    // 整理评价维度信息
    manageDimensionality (isSplit) {
      if (isSplit) {
        this.baseCourseForm.evalDimension.forEach((item) => {
          if (item.type) {
            this.studentDimensionality.push(item)
          } else {
            this.courseDimensionality.push(item)
          }
        })
      } else {
        // eslint-disable-next-line vue/no-mutating-props
        this.baseCourseForm.evalDimension = []
        // eslint-disable-next-line vue/no-mutating-props
        this.baseCourseForm.evalDimension.push(...this.studentDimensionality)
        // eslint-disable-next-line vue/no-mutating-props
        this.baseCourseForm.evalDimension.push(...this.courseDimensionality)
      }
    },
    getQuestionsInfo () {},
    changeQuestionsInfo (data) {
      this.baseCourseForm.exercise = []
      const fixdQuestions = data.fixdQuestions.map((exer) => {
        return {
          courseId: this.baseCourseForm.id,
          questionId: exer.id,
          score: exer.itemScore,
          type: exer.typeId,
          isFixed: 1,
          creator: this.$store.user.id,
          updater: this.$store.user.id
        }
      })
      const randQuestions = data.randQuestions.map((exer) => {
        return {
          courseId: this.baseCourseForm.id,
          questionId: exer.id,
          score: exer.itemScore,
          type: exer.typeId,
          isFixed: 0
        }
      })
      this.baseCourseForm.exercise = [...fixdQuestions, ...randQuestions]
    },
    async getOrgList () {
      const { data } = await findAllOrgApi()
      this.$set(this, 'orgList', data.toTree().tree)
    },
    exerciseFormat () {
      const questionInfo = { fixdQuestions: [], randQuestions: [] }
      this.baseCourseForm?.exercise?.forEach((exer) => {
        if (exer.isFixed) {
          const data = { ...exer.info, ...exer }
          data.id = exer.info.id
          data.typeId = data.type
          data.itemScore = data.score
          questionInfo.fixdQuestions.push(data)
        } else {
          const data = { ...exer.info, ...exer }
          data.id = exer.info.id
          data.typeId = data.type
          data.itemScore = data.score
          questionInfo.randQuestions.push(data)
        }
      })
      this.questionInfo = questionInfo
    }
  }
}
</script>
<style lang='scss' scoped>
::v-deep .v-title {
  padding-left: 6px;
  font-size: 15px;
  border-left: 6px solid $--color-primary;
}
.add-course {
  background-color: #fff;
  width: 100%;

  .must-write {
    position: absolute;
    left: -12px;
    color: red;
    top: 0;
  }
  ::v-deep .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 4px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    .el-upload:hover {
      border-color: #409eff;

      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
    }
  }
  ::v-deep .add-section-button {
    background-color: transparent;
    color: $--color-primary;
    border: 1px dashed;
    // width: 100px;
    padding: 4px;
  }
  ::v-deep .dialog_layout {
    z-index: 100;
    // ._ctx {
    //   // overflow: unset;
    // }
  }
  .course-exercises {
    padding: 10px 0 20px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    > span {
      margin-right: 10px;
    }
    > button {
      color: $--color-primary;
      border: 1px dashed $--color-primary;
    }
  }
  .check-student-org {
    position: relative;
    padding: 10px;
  }

  .add-course-buttom {
    padding: 12px;
    display: flex;
    align-items: center;
    background-color: white;
    justify-content: center;
    position: sticky;
    bottom: -20px;
    z-index: 1;
  }
  ::v-deep .error-input {
    input {
      border: 1px solid red;
    }
  }
  ::v-deep .el-input-group__append {
    padding: 0 10px !important;
    cursor: pointer;
  }
  .delete-input-button {
    color: red;
  }
}
</style>
