<template>
  <div class="v-page add-live">
    <el-form
      ref="infoForm"
      :model="liveInfo"
      label-width="88px"
      :rules="infoRules"
      inline
    >
      <h2 class="v-title">基本信息</h2>

      <el-form-item label="直播名称" prop="title">
        <el-input v-model="liveInfo.title"></el-input>
      </el-form-item>
      <el-form-item label="直播时间" prop="startTime">
        <el-date-picker
          type="datetime"
          placeholder="选择日期"
          v-model="liveInfo.startTime"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="直播时长" prop="duration">
        <el-tooltip
          class="item"
          effect="dark"
          :content="`${liveInfo.duration}小时`"
          placement="top"
        >
          <div>
            <el-input-number
              v-model="liveInfo.duration"
              :min="0.1"
              :step="0.1"
              :max="10"
              controls-position="right"
            >
            </el-input-number>
          </div>
        </el-tooltip>
      </el-form-item>
      <el-form-item class="live-info-explain" label="直播简介">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入内容"
          v-model="liveInfo.explain"
        >
        </el-input>
      </el-form-item>
      <el-form-item class="" label="直播封面">
        <div class="_photo" @click="toUpload('cover', ['image'])">
          <img v-if="liveInfo.cover" :src="liveInfo.cover.fileLinkTransfer()" />
          <i v-else class="_icon el-icon-plus" />
          <span class="_photo-hint">建议图片尺寸像素为4:3</span>
        </div>
      </el-form-item>
      <el-form-item class="" label="直播暖场">
        <div>
          <div class="_photo" @click="toUpload('warmUpPicture', ['image'])">
            <img
              v-if="liveInfo.warmUpPicture"
              :src="liveInfo.warmUpPicture.fileLinkTransfer()"
            />
            <i v-else class="_icon el-icon-plus" />
            <span class="_photo-hint">建议图片尺寸像素为4:3</span>
          </div>
          <div
            class="warmUpMusice-control"
            v-if="liveInfo.warmUpMusice"
            @click="toUpload('warmUpMusice', ['audio'])"
          >
            {{ liveInfo.warmUpMusice.name }}
          </div>
          <!-- <audio
            id="warmUpMusice"
            style="width: 120px"
            v-show="false"
            v-if="liveInfo.warmUpMusice"
            :src="liveInfo.warmUpMusice"
            controls
          ></audio> -->
          <selfButton
            v-else
            @click="toUpload('warmUpMusice', ['audio'])"
            style="width: 120px"
            >暖场音乐</selfButton
          >
        </div>
      </el-form-item>
      <div>
        <el-form-item
          label="回放设置"
          prop="playback"
          style="display: inlin-block"
        >
          <el-switch
            v-model="liveInfo.playback"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item
          v-if="liveInfo.playback"
          label="回放期限"
          style="display: inlin-block"
          prop="playback"
        >
          <div>
            <el-radio
              v-model="liveInfo.playbackDeadline"
              :label="null"
              @change="liveInfo.isPlaybackDeadline = false"
              >永久</el-radio
            >
            <el-radio
              v-model="liveInfo.isPlaybackDeadline"
              :label="true"
              @change="liveInfo.playbackDeadline = new Date()"
              >限时</el-radio
            >
            <el-date-picker
              v-if="liveInfo.isPlaybackDeadline"
              type="date"
              placeholder="选择日期"
              v-model="liveInfo.playbackDeadline"
            ></el-date-picker>
          </div>
        </el-form-item>
      </div>
      <h2 class="v-title">人员选择</h2>
      <div>
        <el-form-item class="" label="选择讲师">
          <el-tag style="margin-right: 10px">{{
            liveInfo.lecturerInfo?.name
          }}</el-tag>
          <selfButton :width="'100px'" @click="isShowLecturerSelect = true"
            >选择老师</selfButton
          >
          <TeacherSelect
            :teacher="
              liveInfo.lecturerInfo ? liveInfo.lecturerInfo : $store.user
            "
            v-model="isShowLecturerSelect"
            @onChange="lecturerChanged"
          ></TeacherSelect>
        </el-form-item>
        <el-form-item class="" label="选择学员">
          <el-tag style="margin-right: 10px"
            >已选择：{{ current_selected_students.length }} 人</el-tag
          >
          <selfButton :width="'100px'" @click="isShowStudentSelect = true"
            >选择学员</selfButton
          >
          <dialog-layout
            v-show="isShowStudentSelect"
            @onCancel="isShowStudentSelect = false"
            :visible="true"
            :actionBarOption="{ noConfirm: true, noCencel: true }"
          >
            <StudentsSelector
              v-model="current_selected_students"
              :transOptions="liveInfo.liveStudent"
            ></StudentsSelector>
          </dialog-layout>
        </el-form-item>
      </div>
      <h2 class="v-title">授课课件</h2>
      <el-form-item
        label="选择课件"
        style="display: inlin-block"
        prop="playback"
      >
        <el-tag
          v-show="!ware.delFlag"
          style="margin-right: 10px"
          v-for="(ware, index) in liveInfo.liveCourseware"
          :key="index"
          >{{ ware.info.name }}</el-tag
        >
        <selfButton :width="'100px'" @click="addCourseware"
          >添加课件</selfButton
        >
        <dialog-layout
          v-show="isShowCoursewareSelect"
          @onCancel="isShowCoursewareSelect = false"
          :visible="true"
          :actionBarOption="{ noConfirm: true, noCencel: true }"
        >
          <CoursewareSelect
            ref="ResourceManage"
            :nowCheckSection="nowCheckWareTransform"
            @delForSection="delForLiveCourseware"
            @addToSection="addToLiveCourseware"
          ></CoursewareSelect>
        </dialog-layout>
      </el-form-item>
      <h2 class="v-title">课堂答题</h2>
      <PaperSelectQuestionTable
        v-if="questionInfo"
        ref="QuestionTable"
        style="width: 60%; margin: 10px"
        :isMounted="true"
        @current-change="changeQuestionsInfo"
        :questionData="questionInfo"
      >
      </PaperSelectQuestionTable>
      <h2 class="v-title" v-if="isShowEveal">互动设置</h2>
      <CourseEvealuate
        v-if="isShowEveal"
        :nowCheckCourse="liveInfo"
        ref="CourseEvealuate"
        :isStudy="false"
        :isShowSelf="false"
        :courseDimensionality="courseDimensionality"
        :studentDimensionality="studentDimensionality"
        @addDimensionality="addDimensionality"
        @dleteInput="dleteInput"
      ></CourseEvealuate>
    </el-form>
    <div class="add-live-floor">
      <div>
        <el-button type="primary" @click="saveLive">保存</el-button>
        <el-button type="danger" @click="cancelEditor">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  addLiveAPI,
  editorLiveAPI,
  getLiveInfoAPI
} from '@/api/online-teaching/live-manage'
import selfButton from '../../online-course/components/button-selft.vue'
import TeacherSelect from '@/views/assessment-evaluation/exam-arrangement/add-modify-exam/components/TeacherSelector.vue'
import { getDistFile } from '@/utils'
import StudentsSelector from '@/views/assessment-evaluation/exam-arrangement/add-modify-exam/components/StudentsSelector.vue'
import dialogLayout from '@/components/layout/DialogLayout.vue'
import CoursewareSelect from '../../online-course/components/add-course/course-courseware.vue'
import PaperSelectQuestionTable from '@/views/assessment-evaluation/examination-paper-manage/add-modify-paper/components/PaperSelectQuestionTable.vue'
import CourseEvealuate from '../../online-course/components/add-course/course-evaluate.vue'
import { uploadApi } from '@/api/system'
import { deepClone } from '@/views/online-course/utils'

export default {
  components: {
    selfButton,
    TeacherSelect,
    StudentsSelector,
    dialogLayout,
    CoursewareSelect,
    PaperSelectQuestionTable,
    CourseEvealuate
  },
  data () {
    return {
      id: 0,
      liveInfo: {
        title: '',
        startTime: '',
        actualStartTime: null,
        actualEndTime: null,
        duration: 0,
        classify: 0,
        explain: '',
        cover: '',
        status: 0,
        warmUpPicture: '',
        warmUpMusice: '',
        playback: 0,
        playbackDeadline: null,
        lecturer: this.$store?.user.id,
        openDiscussion: 0,
        openEval: 0,
        lecturerInfo: {
          id: this.$store?.user.id,
          name: this.$store?.user.name
        },
        txtOrGradeEvealute: 0,
        textEvaluateTitle: '',
        liveCourseware: [],
        evalDimension: [],
        liveQuestion: [],
        liveStudent: []
      },
      infoRules: {
        title: [{ required: true, message: '请输入直播名称', trigger: 'blur' }],
        startTime: [
          { required: true, message: '请输入直播开始时间', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请输入直播持续时间', trigger: 'blur' }
        ]
      },
      isShowLecturerSelect: false,
      isShowStudentSelect: false,
      isShowCoursewareSelect: false,
      nowCheckWareTransform: {},
      current_selected_students: [],
      questionInfo: false,
      courseDimensionality: [],
      studentDimensionality: [],
      isShowEveal: false
    }
  },
  async created () {},
  async activated () {
    this.id = this.$route.query.id
    if (+this.id) {
      await this.getLiveInfoAPI(this.id)
    } else {
      this.isShowEveal = true
    }
    this.exerciseFormat()
  },
  watch: {},
  mounted () {

    // this.$set(this.liveInfo, 'liveStudent', [
    //   { id: 'd672a5f9-487c-410d-a9a3-0b66d528ea98', name: 'xx', orgId: 1 }
    // ])
  },
  methods: {
    async getLiveInfoAPI (id) {
      const { data } = await getLiveInfoAPI(id)
      data.liveStudent.forEach((student) => {
        student.name = student.info.name
        student.id = student.info.id
        student.orgId = student.info.orgId
      })
      this.courseDimensionality = data.evalDimension
      data.courseware = data.liveCourseware
      if (data.playbackDeadline) {
        data.isPlaybackDeadline = true
      }
      const isCopy = this.$route.query.isCopy
      if (isCopy) {
        data.title = ''
        data.startTime = new Date()
        data.status = 0
        data.updateTime = undefined
        data.createTime = undefined
      }
      this.$set(this, 'liveInfo', data)
      // this.liveInfo = data
      this.isShowEveal = true

      this.current_selected_students = data.liveStudent.map((sd) => sd.id)
    },
    async toUpload (key, accepts, isUrl) {
      const [file] = await getDistFile({ accepts })

      this.liveInfo[key] = file
    },
    lecturerChanged (e) {
      this.liveInfo.lecturerInfo = e
      this.liveInfo.lecturer = e.id
      this.isShowLecturerSelect = false
    },
    addCourseware () {
      this.liveInfo.liveCourseware?.forEach((item) => {

        // item.fileId = item.coursewareId
      })
      // this.nowCheckWareTransform.onlyKey = true
      this.$set(this.nowCheckWareTransform, 'onlyKey', true)
      this.nowCheckWareTransform.courseware =
        this.liveInfo.liveCourseware || []
      this.isShowCoursewareSelect = true

      this.$nextTick(() => {
        this.$refs.ResourceManage.getSelected()
      })
    },
    addToLiveCourseware (res) {
      res.isSelected = true
      const wareList = this.nowCheckWareTransform.courseware
      wareList.push({
        fileId: res.id,
        liveId: this.liveInfo.id,
        info: res
      })
    },
    delForLiveCourseware (res) {
      res.isSelected = false
      const wareList = this.nowCheckWareTransform.courseware
      const index = wareList.findIndex((ware) => {
        if (ware.fileId === res.id) {
          return true
        }
        return false
      })
      wareList.splice(index, 1)
    },
    exerciseFormat () {
      const questionInfo = { fixdQuestions: [], randQuestions: [] }
      this.liveInfo.liveQuestion.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
    },
    changeQuestionsInfo (data) {
      this.liveInfo.liveQuestion = []
      const fixdQuestions = data.fixdQuestions.map((exer) => {
        return {
          liveId: this.liveInfo.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 {
          liveId: this.baseCourseForm.id,
          questionId: exer.id,
          score: exer.itemScore,
          type: exer.typeId,
          isFixed: 0
        }
      })
      this.liveInfo.liveQuestion = [...fixdQuestions, ...randQuestions]
    },
    // 添加新维度
    addDimensionality (type) {
      let noDleList = []
      const typeKey = type ? 'studentDimensionality' : 'courseDimensionality'
      noDleList = this[typeKey]
      if (noDleList.length >= 5) {
        this.$message.warning('只支持5个评价维度！')
        return
      }
      this[typeKey].push({
        liveId: this.liveInfo.id,
        dimensionality: '',
        type,
        delFlag: 0
      })
    },
    // 删除当前课程评价维度中的输入框
    dleteInput (array, index) {
      array.splice(index, 1)
    },
    saveLive () {
      this.$refs.infoForm.validate(async (isok) => {
        if (isok) {
          const uploadList = []
          if (this.liveInfo.cover instanceof File) {
            uploadList.push({ key: 'cover', file: this.liveInfo.cover })
          }
          if (this.liveInfo.warmUpPicture instanceof File) {
            uploadList.push({
              key: 'warmUpPicture',
              file: this.liveInfo.warmUpPicture
            })
          }
          if (this.liveInfo.warmUpMusice instanceof File) {
            uploadList.push({
              key: 'warmUpMusice',
              file: this.liveInfo.warmUpMusice
            })
          }
          const res = await Promise.all(
            uploadList.map((f) => uploadApi(f.file, {}))
          )
          this.liveInfo.evalDimension = [...this.courseDimensionality]
          const saveData = deepClone(this.liveInfo)
          saveData.evalDimension = [...this.courseDimensionality]
          saveData.startTime = this.liveInfo.startTime

          saveData.liveStudent = this.current_selected_students
          saveData.actualStartTime = this.liveInfo.actualStartTime
          saveData.actualEndTime = this.liveInfo.actualEndTime
          saveData.playbackDeadline = this.liveInfo.playbackDeadline
          uploadList.forEach((item, index) => {
            saveData[item.key] = res[index].data.diskname
          })
          const keyList = [
            'openDiscussion',
            'textEvaluateTitle',
            'txtOrGradeEvealute',
            'openEval',
            'openQuiz',
            'openSelfEvaluation',
            'evalDimension'
          ]
          const basec = deepClone(
            this.$refs.CourseEvealuate.$data.baseCourseForm
          )
          keyList.forEach((key) => {
            saveData[key] = basec[key]
          })
          if (+this.id) {
            if (this.$route.query.isCopy) {
              saveData.id = undefined

              await addLiveAPI({ ...saveData })
            } else {
              await editorLiveAPI({ ...saveData, id: this.id })
            }
          } else {
            await addLiveAPI(saveData)
          }
          this.$router.push('/online-course/live-lectures')
          // this.$router.push('/online-teaching/live-lectures')
        } else {
          this.$message.warning('请将信息补充完整')
        }
      })
    },
    cancelEditor () {
      this.$confirm('确定取消编辑当前直播?取消后已编辑内容无法回复！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        // eslint-disable-next-line prefer-promise-reject-errors
      })
        .then((res) => this.$router.push('/online-course/live-lectures'))
        // .then((res) => this.$router.push('/online-teaching/live-lectures'))
        .catch((_) => reject())
    }
  }
}
</script>

<style lang="scss" scoped>
.v-page {
  display: unset;
}
.v-title {
  margin-bottom: 10px;
}
.add-live {
  overflow: auto;
  position: relative;
  height: 100%;
  ::v-deep .el-form-item__content {
    min-width: 400px;
  }
  ::v-deep .live-info-explain {
    width: 100%;
    .el-form-item__content {
      width: calc(100% - 80px);
    }
  }
  ._photo {
    width: 120px;
    height: 90px;
    padding: 3px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    color: #dcdfe6;
    cursor: pointer;
    position: relative;
    ::v-deep ._photo-hint {
      position: absolute;
      top: 50%;
      left: 100%;
      transform: translate(10px, -50%);
      font-size: 12px;
      width: 130px;
    }
    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }

    ._icon {
      font-size: 20px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    &:hover {
      color: $--color-primary;
      border-color: $--color-primary;
    }
  }
  .warmUpMusice-control {
    margin-top: 5px;
    padding: 0 3px;
    width: 120px;
    height: 20px;
    font-size: 12px;
    line-height: 18px;
    border-radius: 4px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: $--color-primary;
    border: 1px dashed $--color-primary;
    cursor: pointer;
  }
  .resource-manage {
    height: 50vh;
    min-height: 400px;
  }
  .add-live-floor {
    position: sticky;
    bottom: -20px;
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: center;
    background-color: white;
    z-index: 1;
    align-items: center;
    > div {
      > :first-child {
        margin-right: 100px;
      }
    }
  }
}
</style>
