<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>
        <PaperClassifySelector v-model="form.classifyId"></PaperClassifySelector>
      </div>
    </div>
    <div class="gy-form" style="--fix:77px;">
      <div class="gy-form-item mb">
        <div class="gy-label">试卷描述：</div>
        <el-input type="textarea" placeholder="请输入试卷描述信息" v-model="form.paperDesc" style="width:100%"></el-input>
      </div>
    </div>
    <div class="gy-form" style="--fix:77px;" v-if="!isSimTest">
      <div class="gy-form-item mb">
        <div class="gy-label middle ">共享试卷：</div>
        <div>
          <el-switch
            v-model="form.share"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </div>
      </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-input v-model="form.paperDuration" placeholder="时长" type="number" style="width:90px "></el-input>
      </div>
      <div class="gy-form-item mb">
        <div class="gy-label middle ">及格分：</div>
        <div>
          <el-input v-model="form.passPercent" placeholder="60" min="0" max="100" step="5" type="number"
            style="width:90px "></el-input> %
        </div>
      </div>
      <div class="gy-form-item">
        <div class="gy-label middle " style="height:32px">
          计：<span style="color:red;padding:0 5px">{{Math.ceil(form.totalScore * form.passPercent /100) }}</span>分，总分 <span style="color:red;padding:0 5px">{{ form.totalScore }}</span> 分
        </div>
      </div>
    </div>
    <div class="gy-form inline" style="--fix:100px;">
      <div class="gy-form-item mb" style="margin-right: 45px;">
        <div class="gy-label middle ">试题排序乱序：</div>
        <div>
          <el-switch
            v-model="form.questionsIsRandomSort"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </div>
      </div>
      <div class="gy-form-item mb">
        <div class="gy-label middle ">试题选项乱序：</div>
        <div>
          <el-switch
            v-model="form.optionsIsRandomSort"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </div>
      </div>
    </div>

    <div class="gy-area-title">设置题型</div>
    <div>
      <PaperSelectQuestionTable @current-change="changeQuestionsInfo" :questionData="questionInfo" @totalScore="totalScoreChange">
      </PaperSelectQuestionTable>
    </div>
    <div style="width:100%;margin-top:20px;text-align: center;">
      <el-button type="primary" round @click="onToPublishExam" v-if="isSimTest">立即考试</el-button>
      <el-button type="error" plain round @click="$router.go(-1)" v-if="!isSimTest">返回</el-button>
      <el-button type="primary" round @click="onPreview">预览</el-button>
      <el-button type="primary" round @click="onSave(false)" v-if="!isSimTest">保存</el-button>
      <el-button type="primary" round @click="onToPublishExam" v-if="!isSimTest">发布考试</el-button>
    </div>
    <QuestionListPreview :questionList="current_questions_list" v-if="preview_dialog_show"
      @onCancel="preview_dialog_show = false;"></QuestionListPreview>
  </div>
</template>

<script>
import '@/views/assessment-evaluation/utils/gyStyle.scss'
import QuestionListPreview from './components/QuestionListPreview.vue'
import PaperClassifySelector from './components/PaperClassifySelector.vue'
import PaperSelectQuestionTable from './components/PaperSelectQuestionTable.vue'
import { createPaperApi, getPaperInfoByIdApi, patchPaperInfoByIdApi, createSimTestApi } from '@/api/assessment-evaluation/paper'
import { createSimExamHistoryApi } from '@/api/assessment-evaluation/onlineTest'

export default {
  components: { PaperClassifySelector, PaperSelectQuestionTable, QuestionListPreview },
  data () {
    return {
      form: {
        title: '',
        classifyId: null,
        paperDesc: '',
        totalScore: 0,
        questionCount: 0,
        passPercent: 60,
        paperDuration: 120,
        optionsIsRandomSort: 0,
        questionsIsRandomSort: 0,
        share: 0
      },
      paperInfo: {},
      questionInfo: {},
      page_is_loading: false,
      current_questions_list: [],
      preview_dialog_show: false
    }
  },
  props: {
    isSimTest: {
      default: false

    }
  },
  computed: {
    isModify () {
      return this.$route.params.paperId != null
    }
  },
  activated () {
    this.initFrom()
    if (this.isModify) {
      // return false
      this.getPaperInfo()
    }
  },
  methods: {
    totalScoreChange (total) {
      this.totalScore = total
    },
    initFrom () {
      this.form = {
        title: '',
        classifyId: null,
        paperDesc: '',
        totalScore: 0,
        questionCount: 0,
        passPercent: 60,
        paperDuration: 60,
        optionsIsRandomSort: 0,
        questionsIsRandomSort: 0,
        share: 0
      }
      if (this.isSimTest) this.form.isPracticeExam = 1

      this.paperInfo = {}
      this.questionInfo = {}
    },
    // 预览
    onPreview () {
      // this.$message('开发中')

      if (this.questionInfo?.fixdQuestions || this.questionInfo?.randQuestions) {
        this.current_questions_list = this.questionInfo?.fixdQuestions?.concat(this.questionInfo?.randQuestions)
        this.preview_dialog_show = true
      } else if (this.form.questionInfo?.fixdQuestions || this.form.questionInfo?.randQuestions) {
        this.current_questions_list = this.form.questionInfo?.fixdQuestions?.concat(this.form.questionInfo?.randQuestions)
        this.preview_dialog_show = true
      }
    },
    // 保存
    onSave (isToPublishExam = false) {
      const form = this.form
      if (!form.title) return this.$message.error('请输入试卷名称')
      if (!form.classifyId) return this.$message.error('请选择试卷分类')
      if (!form.paperDuration) return this.$message.error('请填写答题时长')
      if (!form.passPercent) return this.$message.error('请填写及格分占比')
      if (form.passPercent < 0 || form.passPercent > 100) return this.$message.error('及格分占比应在0-100之间')
      if (form.questionCount === 0) return this.$message.error('请选择一些试题')
      if (form.totalScore === 0) return this.$message.error('请确认题型的分值')
      if (isToPublishExam) {
        form.status = 1
      }
      if (this.isSimTest) {
        this.toCreateSimTest()
        return
      }
      if (this.isModify) {
        this.onModify(isToPublishExam)
        return
      }
      this.page_is_loading = true
      createPaperApi(this.form).then(res => {
        this.$message.success('保存成功')
        this.paperInfo = res.data.newPaper
        // TODO: 暂时保存后跳转到列表页，之后需要留在当前页，可发布考试
        if (isToPublishExam) {
          this.backOrToPublish(res.data.newPaper.id, res.data.newPaper.title, res.data.newPaper.totalScore)
        } else {
          this.$router.replace({ path: '/assessment-evaluation/examination-paper-manage' })
        }
      }).catch(err => {
        console.info(err)
      }).finally(() => {
        this.page_is_loading = false
      })
    },
    toCreateSimTest () {
      this.page_is_loading = true
      createSimTestApi(this.form).then(res => {
        this.paperInfo = res.data.newPaper
        const { studentOnlineExam } = res.data
        createSimExamHistoryApi({ onlineExamId: studentOnlineExam.id }).then(res => {
          if (res.data) {
            this.$message.success('开始考试')
            this.$router.push({ path: '/assessment-evaluation/online-test/begin-online-exam/' + res.data.id })
          }
        })
        // TODO: 暂时保存后跳转到列表页，之后需要留在当前页，可发布考试
      }).catch(err => {
        console.info(err)
      }).finally(() => {
        this.page_is_loading = false
      })
    },
    backOrToPublish (paperId = null, title = null, totalScore = null) {
      let url = '/assessment-evaluation/examination-paper-manage'
      const query = {}
      if (paperId && title) {
        url = '/assessment-evaluation/exam-arrangement/add-modify-exam'
        query.paperId = paperId
        query.title = title
        query.totalScore = totalScore
      }
      this.$router.replace({ path: url, query })
    },
    onModify (isToPublishExam = false) {
      this.page_is_loading = true
      patchPaperInfoByIdApi(this.form).then(res => {
        this.$message.success('编辑成功')
        if (isToPublishExam) {
          this.backOrToPublish(res.data.newPaper.id, res.data.newPaper.title, res.data.newPaper.totalScore)
        }
      }).catch(err => {
        console.info(err)
      }).finally(() => {
        this.page_is_loading = false
      })
    },
    // 去发布考试
    onToPublishExam () {
      this.onSave(true)
    },
    changeQuestionsInfo (questionInfo) {
      this.questionInfo = {}
      this.form.questionInfo = questionInfo
      this.form.questionCount = questionInfo.questionCount
      this.form.totalScore = questionInfo.totalScore
    },
    getPaperInfo () {
      const id = this.$route.params.paperId
      if (!id) return
      this.page_is_loading = true
      getPaperInfoByIdApi(id).then(res => {
        this.pageInfo = res.data
        this.form.id = this.pageInfo.id
        this.form.title = this.pageInfo.title
        this.form.classifyId = this.pageInfo.classifyId
        this.form.paperDesc = this.pageInfo.paperDesc
        this.form.passPercent = this.pageInfo.passPercent
        this.form.paperDuration = this.pageInfo.paperDuration
        this.form.questionsIsRandomSort = this.pageInfo.questionsIsRandomSort
        this.form.optionsIsRandomSort = this.pageInfo.optionsIsRandomSort
        this.form.share = this.pageInfo.share
        this.questionInfo = this.pageInfo.questionInfo
      }).finally(() => {
        this.page_is_loading = false
      })
    }
  }
}
</script>

<style>

</style>
