<template>
  <el-container>
    <el-header v-if="isSearch">
      <el-form style="margin: 10px 0" :inline="true">
        <el-form-item label="名称：">
          <el-input type="text" v-model="search.paperName" />
        </el-form-item>
        <el-form-item label="试卷状态：">
          <el-select v-model="search.paperStatus">
            <el-option label="全部" value="" />
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-search"
            @click="initList"
          >
            搜索
          </el-button>
          <el-button class="commonBtn" icon="el-icon-refresh" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-header>

    <el-main>
      <div class="headerTop">
        <div>
          <el-button type="primary" class="el-icon-plus" @click="doAdd(1)">
            新增</el-button
          >
        </div>
        <div>
          <right-toolbar  @queryTable="initList" :search="true" @update:showSearch="isSearch = !isSearch"></right-toolbar>
        </div>
      </div>

      <el-table
        :data="list"
        height="calc(100% - 200px)"
        :row-style="{ height: '0px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
        :cell-style="{ 'text-align': 'center', padding: '2px' }"
        style="width: 100%"
      >
        <el-table-column width="80" type="index" label="序号" align="center">
          <template slot-scope="scope">
            {{ scope.$index + (search.pageNo - 1) * search.pageSize + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="parperName"
          show-overflow-tooltip
          label="试卷名称"
          align="center"
        />
        <el-table-column
          prop="questionsNumber"
          show-overflow-tooltip
          label="试题数量"
          align="center"
        />
        <!-- <el-table-column show-overflow-tooltip label="试卷状态" align="center">
          <template #default="{ row }">
            {{ initSubject(row.paperStatus) }}
          </template>
        </el-table-column> -->
        <el-table-column
          prop="parperFraction"
          show-overflow-tooltip
          label="试题分数"
          align="center"
        />
        <el-table-column
          prop="parperPassingMark"
          show-overflow-tooltip
          label="及格分数"
          align="center"
        />
        <el-table-column
          prop="createDate"
          show-overflow-tooltip
          label="创建时间"
          align="center"
        />
        <el-table-column
          prop="userName"
          show-overflow-tooltip
          label="创建人"
          align="center"
        />
        <el-table-column show-overflow-tooltip label="是否启用" align="center">
          <template #default="{ row }">
            <el-switch
              @change="changeStatus(row)"
              style="color: #fff"
              v-model="row.paperStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="启用"
              inactive-text="停用"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="doAdd(2, scope.row)">
              编辑
            </el-button>
            <el-button type="text" @click="doAdd(3, scope.row)">
              查看
            </el-button>
            <el-button
              type="text"
               
              @click="doDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :page.sync="search.pageNo"
        :limit.sync="search.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        @pagination="initList"
      />
    </el-main>

    <!-- 新增/编辑 的dialog -->
    <el-dialog
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      top="1vh"
      width="80%"
      :title="isEdit"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        inline
        class="demo-ruleForm"
      >
        <el-form-item
          label="培训计划分类："
          prop="trainingPlanClassificationId"
        >
          <el-select
            :disabled="disabledVal"
            v-model="ruleForm.trainingPlanClassificationId"
            style="width: 15vw"
          >
            <el-option
              v-for="item in optionList"
              :key="item.id"
              :label="item.categoriesName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试卷名称：" prop="parperName">
          <el-input
            :disabled="disabledVal"
            v-model="ruleForm.parperName"
            maxlength="1000"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item label="及格分数：" prop="parperPassingMark">
          <el-input
            :disabled="disabledVal"
            v-model="ruleForm.parperPassingMark"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <br />
        <div style="margin: 0;width: 100%;">
          <el-button type="primary" @click="addQuestions" :disabled="disabledVal">添加试题</el-button>
          <div style="float: right">
            <span style="margin-right: 10px;">
              试卷总分：{{ sumTotal }} 分
            </span>
            <span>
              试题数量：{{questionListTotal.length || ruleForm.questionsNumber}} 题
            </span>
          </div>
        </div>
        <br />

        <ul style="padding-left: 0px" class="ul_box">
          <li v-if="questionListSingle.length > 0" class="question_box">
            <h2 style="font-size: 0.11rem">单选题</h2>
            <div
              v-for="(item, index) in questionListSingle"
              :key="index"
              class="questionList_box"
            >
              <el-row class="title_box">
                {{ index + 1 }}. {{ item.questionTitle }} (
                {{ item.questionScore }}分 )
              </el-row>
              <div class="list_box">
                <span
                  v-for="(it, i) in item.questionOption.split('##')"
                  :key="i"
                >
                  {{ it.split("+++")[0] }}{{ it.split("+++")[1] }}
                </span>
              </div>
              <div>正确答案：{{ item.questionAnscha.split("##").toString() }}</div>
            </div>
          </li>
          <li v-if="questionListMore.length > 0" class="question_box">
            <h2 style="font-size: 0.11rem">多选题</h2>
            <div
              v-for="(item, index) in questionListMore"
              :key="index"
              class="questionList_box"
            >
              <el-row class="title_box">
                {{ index + 1 }}. {{ item.questionTitle }} (
                {{ item.questionScore }}分 )
              </el-row>
              <div class="list_box">
                <span
                  v-for="(it, i) in item.questionOption.split('##')"
                  :key="i"
                >
                {{ it.split("+++")[0] }}{{ it.split("+++")[1] }}
                </span>
              </div>
              <div>正确答案：{{ item.questionAnscha.split("##").toString() }}</div>
            </div>
          </li>
          <li v-if="questionListJudge.length > 0" class="question_box">
            <h2 style="font-size: 0.11rem">判断题</h2>
            <div
              v-for="(item, index) in questionListJudge"
              :key="index"
              class="questionList_box"
            >
              <el-row class="title_box">
                {{ index + 1 }}. {{ item.questionTitle }} (
                {{ item.questionScore }}分 )
              </el-row>
              <div class="list_box">
                <span
                  v-for="(it, i) in item.questionOption.split('##')"
                  :key="i"
                >
                {{ it.split("+++")[0] }}{{ it.split("+++")[1] }}
                </span>
              </div>
              <div>正确答案：{{ item.questionAnscha.split("##").toString() }}</div>
            </div>
          </li>
        </ul>

        <br />
        <el-form-item label="试卷状态：" prop="paperStatus">
          <el-radio-group
            :disabled="disabledVal"
            v-model="ruleForm.paperStatus"
          >
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer" v-if="!disabledVal">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="submit">提 交</el-button>
      </span>
    </el-dialog>

    <QuestionDialog
      :dialogAddVisible="dialogAddVisible"
      :questionTitleList="questionTitleList"
      @doAddQuestion="doAddQuestion"
    ></QuestionDialog>
  </el-container>
</template>

<script>
import {
  getPaperList,
  deactivatePaperById,
  saveQuestionBank,
  queryLastLevelClassification,
  getPaperById,
  getQuestionBankSelect,
  savePaper
} from '@/api/planClass/planClass.js'
import QuestionDialog from './questionDialog.vue'
import { positiveIntNum } from '@/utils/rules'
export default {
  name: 'RuoyiPlanClass',
  components: {
    QuestionDialog
  },
  data() {
    return {
      isSearch: false, //控制搜索框是否显示
      search: {
        paperName: '',
        paperStatus: '',
        pageNo: 1,
        pageSize: 10
      },
      total: 0, //总数

      // 2号弹窗所需
      dialogAddVisible: false,
      questionTitleList: [],

      list: [],
      optionList: [], //培训计划分类的下拉
      dialogVisible: false, //新增/修改的dialog
      isEdit: '',
      disabledVal: false, //查看禁用

      ruleForm: {
        trainingPlanClassificationId: '',
        parperName: '',
        parperPassingMark: '',
        paperStatus: ''
      },
      rules: {
        trainingPlanClassificationId: [
          { required: true, message: '请选择培训计划分类', trigger: 'change' }
        ],
        parperName: [
          { required: true, message: '请输入试卷名称', trigger: 'blur' }
        ],
        parperPassingMark: [
          { required: true, message: '请输入及格分数', trigger: 'blur' },
          positiveIntNum
        ],
        paperStatus: [
          { required: true, message: '请选择试卷状态', trigger: 'change' }
        ]
      },
      loading: false, // loading 效果
      sumTotal: 0, //总分
      questionListTotal: [],
      questionListSingle: [], //单选
      questionListMore: [], //多选
      questionListJudge: [] //判断
    }
  },

  mounted() {
    this.initList() // 列表初始化
    this.initQueryLastLevelClassification() //培训计划分类下拉菜单
  },

  methods: {
    // 列表初始化
    initList() {
      try {
        this.loading = true
        getPaperList(this.search).then((res) => {
          if (res.code === 200) {
            this.list = res.data.list
            this.list.forEach((item) => {
              if (item.paperStatus == '0') {
                item.paperStatus = true
              } else {
                item.paperStatus = false
              }
            })
            this.total = res.data.total
          } else {
            this.$message.error(res.msg)
          }
          this.loading = false
        })
      } catch (error) {
        this.loading = false
      }
    },
    // 重置
    reset() {
      this.search.paperName = ''
      this.search.paperStatus = ''
      this.initList()
    },
    async initQueryLastLevelClassification() {
      const res = await queryLastLevelClassification()
      this.optionList = res.data
    },
    initSubject(type) {
      switch (type) {
        case '':
          return '全部'
        case '0':
          return '启用'
        case '1':
          return '停用'
        default:
          return '-'
      }
    },
    async doAdd(type, val) {
      this.questionListTotal = []
      this.questionListSingle = []
      this.questionListMore = []
      this.questionListJudge = []
      if (type === 1) {
        this.isEdit = '新增'
        this.ruleForm = {
          trainingPlanClassificationId: '',
          parperName: '',
          parperPassingMark: '',
          paperStatus: ''
        }
        this.disabledVal = false
      } else if (type === 2) {
        this.isEdit = '编辑'
        const res = await getPaperById(val.id)
        console.log(res.data,8888);
        this.ruleForm = res.data
        this.ruleForm.parperQuestionBankList.forEach((item) => {
        if (item.questionTypes === '1') {
          this.questionListSingle.push(item)
        } else if (item.questionTypes === '2') {
          this.questionListMore.push(item)
        } else if (item.questionTypes === '3') {
          this.questionListJudge.push(item)
        }
      })
      console.log(this.ruleForm);
       this.sumTotal = res.data.parperQuestionBankList.reduce(
        (acc, current) => acc + current.questionScore,
        0
      )
      // this.ruleForm.parperPassingMark = this.sumTotal * 0.6
        this.disabledVal = false
      } else {
        this.isEdit = '查看'
        this.disabledVal = true
        const res = await getPaperById(val.id)
        this.ruleForm = res.data
        console.log(res.data,999);
        if(Array.isArray(this.ruleForm.parperQuestionBankList)){
          this.ruleForm.parperQuestionBankList.forEach((item) => {
          if (item.questionTypes === '1') {
            this.questionListSingle.push(item)
          } else if (item.questionTypes === '2') {
            this.questionListMore.push(item)
          } else if (item.questionTypes === '3') {
            this.questionListJudge.push(item)
          }
        })
        }else {
          this.ruleForm.parperQuestionBankList = []
        }
       this.sumTotal = res.data.parperQuestionBankList.reduce(
        (acc, current) => acc + current.questionScore,
        0
      )
      // this.ruleForm.parperPassingMark = this.sumTotal * 0.6

      }
      this.dialogVisible = true
    },
    // 取消按钮
    cancle() {
      this.$nextTick(() => {
        this.ruleForm = {
          trainingPlanClassificationId: '',
          parperName: '',
          parperPassingMark: '',
          paperStatus: ''
        }
        this.$refs.ruleFormRef.resetFields()
      })
      this.dialogVisible = false
    },
    // 确定按钮
    submit() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (valid) {
          this.ruleForm.questionsNumber = this.questionListTotal.length
          this.ruleForm.parperFraction = this.sumTotal
          console.log(this.ruleForm);
          if(this.isEdit === '新增'){
            this.ruleForm.parperQuestionBankList = this.questionListTotal.map(item=>{
              return  {
                id:item.id
              }
            })
          }
          const res = await savePaper(this.ruleForm)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message.success(`${this.isEdit}成功!`)
          this.ruleForm = {
            trainingPlanClassificationId: '',
            parperName: '',
            parperPassingMark: '',
            paperStatus: ''
          }
          this.dialogVisible = false
        } else {
          this.$message.warning('必传项不能为空!')
          return false
        }
      })
    },
    // 删除
    doDelete(val) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await deactivatePaperById({ id: val.id, type: '2' })
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message.warning('已取消删除')
        })
    },
    // 启用/禁用
    async changeStatus(val) {
      const obj = {
        id: val.id,
        type: val.paperStatus ? '0' : '1'
      }
      const res = await deactivatePaperById(obj)
      if (res.code !== 200) return this.$message.error(res.msg)
      this.$message.success(`${val.paperStatus ? '启用' : '禁用'}成功!`)
      this.initList()
    },
    // 添加试题
    async addQuestions() {
      if (!this.ruleForm.trainingPlanClassificationId)
        return this.$message.warning('请先选择培训计划分类,在添加试题!')
      const res = await getQuestionBankSelect({
        trainingPlanClassificationId: this.ruleForm.trainingPlanClassificationId
      })
      if (res.code !== 200) return this.$message.error(res.msg)
      this.questionTitleList = res.data
      this.dialogAddVisible = true
    },
    // 子组件传过来的题目
    doAddQuestion(val) {
      this.questionListTotal = []
      this.questionListSingle = []
      this.questionListMore = []
      this.questionListJudge = []
      this.questionListTotal = val
      this.sumTotal = this.questionListTotal.reduce(
        (acc, current) => acc + current.questionScore,
        0
      )
      // this.ruleForm.parperPassingMark = this.sumTotal * 0.6
      val.forEach((item) => {
        if (item.questionTypes === '1') {
          this.questionListSingle.push(item)
        } else if (item.questionTypes === '2') {
          this.questionListMore.push(item)
        } else if (item.questionTypes === '3') {
          this.questionListJudge.push(item)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}

::v-deep .el-loading-mask {
  background-color: rgba(0, 222, 240, 0.2) !important;
}
::v-deep .el-loading-spinner {
  top: 65% !important;
}
::v-deep .el-loading-spinner i {
  font-size: 0.1513rem !important;
}

::v-deep .el-switch__label {
  color: #fff;
}
::v-deep .el-switch__label.is-active {
  color: #1890df;
}
.ul_box {
  max-height: 60vh;
  overflow-y: auto;
  margin: 0;

  .question_box {
    border: 1px solid #00def0;
    padding: 0 10px;
    margin-top: 25px;

    .title_box {
      font-size: 0.1rem;
      margin-bottom: 0.05rem;
    }
    .questionList_box {
      margin-bottom: 20px;
    }

    .list_box {
      margin-left: 12px;
      display: flex;
      flex-direction: column;
      line-height: 0.18rem;
    }
  }
}
</style>
