<template>
  <div v-loading="page_is_loading">
    <div class="gy-area-title">考试属性</div>
    <div class="gy-form inline" style="--fix: 77px">
      <div class="gy-form-item mb">
        <div class="gy-label middle require">考试名称：</div>
        <el-input
          v-model="form.title"
          placeholder="请输入名称"
          style="width: 350px"
        ></el-input>
      </div>
      <div class="gy-form-item mb">
        <div class="gy-label middle require">考试分类：</div>
        <ExamClassifySelector v-model="form.classifyId"></ExamClassifySelector>
      </div>
    </div>
    <div class="gy-form mb" style="--fix: 77px">
      <div class="gy-form-item">
        <div class="gy-label">考试描述：</div>
        <el-input
          type="textarea"
          placeholder="请输入考试描述信息"
          v-model="form.examDesc"
          style="width: 100%"
        ></el-input>
      </div>
    </div>
    <div class="gy-area-title">考试控制</div>
    <div class="gy-form inline" style="--fix: 77px">
      <div class="gy-form-item mb">
        <div class="gy-label middle require">考试时间：</div>
        <!-- <el-date-picker v-model="form.examStartTime" type="datetime" placeholder="请选择开始时间">
        </el-date-picker>
        <div class="gy-label middle" style="min-width: 30px;">-</div>
        <el-date-picker v-model="form.examEndTime" type="datetime" placeholder="请选择结束时间">
        </el-date-picker> -->
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          value-format="yyyy-MM-ddTHH:mm:ss.000Z"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </div>
      <div class="gy-form-item mb">
        <div class="gy-label middle require">考试时长：</div>
        <div>
          <el-input
            v-model="form.examDuration"
            placeholder="60"
            :min="1"
            type="number"
            style="width: 90px"
          >
          </el-input>
          分钟
        </div>
      </div>
      <div class="gy-form-item">
        <div class="gy-label middle require">考试机会：</div>
        <div>
          <el-input
            v-model="form.examTimes"
            placeholder="3"
            :min="1"
            :step="1"
            type="number"
            style="width: 90px"
          >
          </el-input>
          次
        </div>
      </div>
    </div>
    <div class="gy-area-title">试卷模式</div>
    <el-radio-group v-model="form.examMode">
      <div class="gy-form inline" style="--fix: 77px; padding-left: 10px">
        <div class="gy-form-item">
          <div>
            <el-radio :label="0"
              >整卷模式
              <el-button
                type="text"
                icon="i-j-fbks-yulan"
                @click="
                  mode_preview_dialog_mode = 0;
                  mode_preview_dialog_show = true;
                "
                >预览</el-button
              >
            </el-radio>
          </div>
        </div>
        <div class="gy-form-item">
          <div>
            <el-radio :label="1"
              >逐题模式
              <el-button
                type="text"
                icon="i-j-fbks-yulan"
                @click="
                  mode_preview_dialog_mode = 1;
                  mode_preview_dialog_show = true;
                "
                >预览</el-button
              >
            </el-radio>
          </div>
        </div>
      </div>
    </el-radio-group>
    <ModePriviewDialog
      v-if="mode_preview_dialog_show"
      :mode="mode_preview_dialog_mode"
      @onCancel="mode_preview_dialog_show = false"
    ></ModePriviewDialog>
    <div class="gy-area-title">选择试卷</div>
    <div class="gy-form inline" style="--fix: 77px">
      <div class="gy-form-item mb">
        <div class="gy-label middle require">试卷：</div>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          class="addbtn-restyle"
          @click="select_paper_dialog_show = true"
          v-if="current_selected_paper == null"
          >选取试卷</el-button
        >
        <el-button
          type="text"
          v-else
          @click="select_paper_dialog_show = true"
          >{{ current_selected_paper?.title }}</el-button
        >
        <el-button
          type="text"
          icon="i-j-fbks-yulan"
          @click="previewPaper"
          v-show="current_selected_paper != null"
          >预览</el-button
        >
      </div>
      <div class="gy-form-item">
        <div class="gy-label middle">总分：</div>
        <div style="height: 32px; line-height: 32px">
          {{ current_selected_paper ? current_selected_paper.totalScore : 0 }}
        </div>
      </div>
      <div class="gy-form-item">
        <div class="gy-label middle">及格分：</div>
        <div style="margin-right: 20px">
          <el-input
            v-model="form.passPercent"
            placeholder="60"
            min="0"
            max="100"
            step="5"
            type="number"
            style="width: 90px"
          ></el-input>
          <span> % </span>
        </div>
        <el-button
          type="text"
          icon="i-j-ksap-bianji2"
          @click="edit_tips_dialog_show = true"
          >自定义评语设置</el-button
        >
      </div>
    </div>
    <div class="gy-area-title">阅卷方式</div>
    <el-radio-group v-model="form.gradePaperMode">
      <div
        class="gy-form inline middle"
        style="--fix: 77px; padding-left: 10px; height: 32px"
      >
        <div class="gy-form-item middle" style="margin-right: 65px">
          <el-radio :label="0">机器阅卷 </el-radio>
        </div>
        <div class="gy-form-item middle">
          <el-radio :label="1">人工阅卷</el-radio>
        </div>
        <div class="gy-form-item middle" v-show="form.gradePaperMode === 1">
          <div style="font-size: 14px; margin-right: 10px">
            {{ examiner_info?.name }}
          </div>
          <el-button
            type="primary"
            class="addbtn-restyle"
            plain
            icon="el-icon-plus"
            @click="teacher_dialog_show = true"
            >选取阅卷人</el-button
          >
        </div>
      </div>
    </el-radio-group>
    <div class="gy-area-title">选取学员</div>
    <StudentsSelector
      v-model="current_selected_students"
      :transOptions="students_selector_options"
    ></StudentsSelector>

    <div style="width: 100%; margin-top: 20px; text-align: center">
      <el-button type="primary" round @click="onSave">保存</el-button>
      <el-button type="primary" round @click="onCancel" plain>取消</el-button>
    </div>
    <DialogLayout
      :visible="select_paper_dialog_show"
      title="选取试卷"
      :actionBarOption="{ noConfirm: true, noCencel: true }"
      @onCancel="select_paper_dialog_show = false"
    >
      <ExamPaperSelector
        :mountedLoad="true"
        @onSelect="paperSelected"
      ></ExamPaperSelector>
    </DialogLayout>
    <ExamTipsForm
      v-model="edit_tips_dialog_show"
      :successTips.sync="form.successTips"
      :failedTips.sync="form.failedTips"
      :waitingTips.sync="form.waitingTips"
    ></ExamTipsForm>
    <TeacherSelector
      :teacher.sync="examiner_info"
      v-model="teacher_dialog_show"
      @onChange="examninerChanged"
    ></TeacherSelector>
    <QuestionListPreview
      :questionList="preview_current_questions_list"
      v-if="preview_paper_dialog_show"
      @onCancel="preview_paper_dialog_show = false"
    ></QuestionListPreview>
  </div>
</template>

<script>
import ExamTipsForm from './components/ExamTipsForm.vue'
import '@/views/assessment-evaluation/utils/gyStyle.scss'
import ExamClassifySelector from './components/ExamClassifySelector.vue'
import ExamPaperSelector from '@/views/assessment-evaluation/examination-paper-manage/components/ExamPaperSelector.vue'
import { DialogLayout } from '@/components/layout'
import {
  createExamApi,
  getExamDetailsByIdApi,
  patchExamDetailsByIdApi,
  getQuestionsByPaperApi
} from '@/api/assessment-evaluation/exam'

import TeacherSelector from './components/TeacherSelector.vue'
import StudentsSelector from './components/StudentsSelector.vue'
import ModePriviewDialog from './components/ModePriviewDialog.vue'
import QuestionListPreview from '../../examination-paper-manage/add-modify-paper/components/QuestionListPreview.vue'
/**
 * 初始化页面时用到的模板数据
 */
const formInitData = {
  title: '',
  classifyId: null,
  examDesc: '',
  examStartTime: null,
  examEndTime: null,
  examDuration: 60,
  examTimes: 1,
  successTips: '恭喜您，成功通过本次考试！',
  failedTips: '很遗憾，您没有通过本次考试！',
  waitingTips: '请等待老师人工评分！',
  // 试卷模式
  examMode: 0,
  // 阅卷方式
  gradePaperMode: 0,
  // 试卷ID
  examPaperId: null,
  // 阅卷人
  examinerId: '',
  totalScore: 0,
  passPercent: 60
}
export default {
  components: {
    ExamClassifySelector,
    ExamPaperSelector,
    StudentsSelector,
    DialogLayout,
    ExamTipsForm,
    TeacherSelector,
    ModePriviewDialog,
    QuestionListPreview
  },
  data () {
    return {
      /**
       * 所选日期时间范围
       */
      dateRange: [],
      form: { ...formInitData },
      page_is_loading: false,
      examiner_info: null,
      select_paper_dialog_show: false,
      edit_tips_dialog_show: false,
      current_selected_paper: null,
      teacher_dialog_show: false,
      current_selected_students: [],
      students_selector_options: null,
      mode_preview_dialog_show: false,
      mode_preview_dialog_mode: 0,
      preview_paper_dialog_show: false,
      preview_current_questions_list: []
    }
  },
  watch: {
    examiner_info: {
      deep: true,
      immediate: true,
      handler (nv) {
        nv && (this.form.examinerId = nv.id)
      }
    },
    dateRange: {
      deep: true,
      immediate: true,
      handler (nv) {
        if (nv.length) {
          this.form.examStartTime = nv[0]
          this.form.examEndTime = nv[1]
        }
      }
    },
    current_selected_paper: {
      deep: true,
      immediate: true,
      handler (nv) {
        if (nv) {
          this.form.examPaperId = nv.id
          this.form.totalScore = nv.totalScore
        }
      }
    }
  },
  computed: {
    isModify () {
      return this.$route.params.examId != null
    },
    isCopy () {
      return this.$route.params.type === 'copy'
    },
    isAgain () {
      return this.$route.params.type === 'again'
    }
  },
  activated () {
    this.initFrom()
    this.examiner_info = this.$store.user

    if (Object.keys(this.$route.query).includes('paperId')) {
      this.current_selected_paper = {
        id: this.$route.query.paperId,
        title: this.$route.query.title,
        totalScore: this.$route.query.totalScore
      }
    }
    if (this.isModify) {
      this.getExamDetails()
    } else {
      this.form.examinerId = this.$store.user.id
    }
  },
  methods: {
    /**
     * 预览试卷
     */
    previewPaper () {
      this.page_is_loading = true
      getQuestionsByPaperApi(this.current_selected_paper.id)
        .then((res) => {
          this.preview_current_questions_list = res.data
          this.preview_paper_dialog_show = true
        })
        .finally((_) => {
          this.page_is_loading = false
        })
    },
    /**
     * 判卷人被修改回调
     */
    examninerChanged (examniner) {
      if (!Object.keys(examniner).includes('id')) {
        this.examiner_info = this.$store.user
      } else {
        this.examiner_info = examniner
      }
      this.teacher_dialog_show = false
    },
    /**
     * 获取考试详细数据
     */
    getExamDetails () {
      this.page_is_loading = true
      getExamDetailsByIdApi(this.$route.params.examId)
        .then((res) => {
          const tempForm = {}
          const resExamInfo = res.data.exam.examInfo
          const resExamInfoKeys = Object.keys(resExamInfo)
          const initKeys = Object.keys(formInitData)
          resExamInfoKeys.forEach((item) => {
            if (initKeys.includes(item)) {
              tempForm[item] = resExamInfo[item]
            }
          })
          tempForm.id = resExamInfo.id
          this.form = tempForm
          this.dateRange = [
            new Date(tempForm.examStartTime),
            new Date(tempForm.examEndTime)
          ]

          this.form.examStartTime = new Date(this.form.examStartTime)
          this.form.examEndTime = new Date(this.form.examEndTime)
          if (this.isAgain) {
            if (this.form.title.indexOf('【复制再考】') === -1) {
              this.form.title = this.form.title + '【复制再考】'
            }
            this.form.examStartTime = null
            this.form.examEndTime = null
          }
          if (this.isAgain || this.isCopy) {
            delete this.form.id
          }
          this.current_selected_paper = res.data.exam.paperInExam
          this.current_selected_students = res.data.students.map((_) => _.id)
          this.students_selector_options = res.data.students
          this.examiner_info = res.data.exam.examInfo.userinfo
        })
        .catch((err) => {
          console.info(err)
        })
        .finally((_) => {
          this.page_is_loading = false
        })
    },
    /**
     * 考试结束提示时的提示信息被修改回调
     */
    tipsChanged (tips) {
      this.form.successTips = tips.successTips
      this.form.failedTips = tips.failedTips
      this.form.waitingTips = tips.waitingTips
      // 隐藏弹窗
      this.edit_tips_dialog_show = false
    },
    /**
     * 试卷被选取
     */
    paperSelected (row) {
      this.current_selected_paper = row

      this.select_paper_dialog_show = false
    },
    /**
     * 初始化form表单
     */
    initFrom () {
      this.form = { ...formInitData }
      this.current_selected_students = []
      this.students_selector_options = []
      this.current_selected_paper = null
      this.dateRange = []
    },
    onCancel () {
      this.$router.replace({ path: '/assessment-evaluation/exam-arrangement' })
      this.initFrom()
    },
    // 保存
    onSave () {
      const form = this.form
      console.log(form)
      this.$message.closeAll()
      const date = new Date()
      if (!form.title) return this.$message.error('请输入考试名称')
      if (!form.classifyId) return this.$message.error('请选择考试分类')
      if (!form.examStartTime) return this.$message.error('请选择考试开始时间')
      if (!form.examEndTime) return this.$message.error('请选择考试结束时间')
      if (date.getTime(form.examEndTime) < date.getTime(form.examStartTime)) {
        return this.$message.error('考试结束时间应晚于考试开始时间')
      }
      if (!form.examDuration) return this.$message.error('请填写考试时长')
      if (!form.examTimes) return this.$message.error('请填写考试机会')
      if (form.examMode == null) return this.$message.error('请选择试卷模式')
      if (!form.examPaperId) return this.$message.error('请选择试卷')
      if (!form.passPercent) return this.$message.error('请填写及格分占比')
      if (form.gradePaperMode == null) {
        return this.$message.error('请选择阅卷方式')
      }
      if (form.gradePaperMode === 1 && !form.examinerId) {
        return this.$message.error('人工阅卷需要确认阅卷人')
      }
      if (form.passPercent < 0 || form.passPercent > 100) {
        return this.$message.error('及格分占比应在0-100之间')
      }
      if (form.examDuration < 1) {
        return this.$message.error('请设置正确的考试时长')
      }
      if (form.examTimes < 1) return this.$message.error('考试次数最少1次')
      if (this.current_selected_students.length === 0) {
        return this.$message.error('请选择考试学员')
      }
      if (this.isModify && !this.isAgain && !this.isCopy) {
        this.onModify()
        return
      }
      this.page_is_loading = true
      createExamApi({
        exam: this.form,
        students: this.current_selected_students
      })
        .then((res) => {
          this.$message.success('发布成功')
          // TODO: 暂时保存后跳转到列表页，之后需要留在当前页，可发布考试（已完成）
          this.$router.replace({
            path: '/assessment-evaluation/exam-arrangement'
          })
        })
        .catch((err) => {
          console.info(err)
        })
        .finally(() => {
          this.page_is_loading = false
        })
    },
    onModify () {
      this.page_is_loading = true
      patchExamDetailsByIdApi({
        id: this.form.id,
        exam: this.form,
        students: this.current_selected_students
      })
        .then((res) => {
          this.$message.success('编辑成功')
          this.$router.replace({
            path: '/assessment-evaluation/exam-arrangement'
          })
        })
        .catch((err) => {
          console.info(err)
        })
        .finally(() => {
          this.page_is_loading = false
        })
    }
  }
}
</script>

<style>
</style>
