<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.questionTitle" />
        </el-form-item>
        <el-form-item label="题目类型：">
          <el-select v-model="search.questionTypes">
            <el-option label="全部" value="0" />
            <el-option label="单选题" value="1" />
            <el-option label="多选题" value="2" />
            <el-option label="判断题" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="培训计划分类：">
          <el-select v-model="search.trainingPlanClassificationId">
            <el-option
              v-for="item in optionList"
              :key="item.id"
              :label="item.categoriesName"
              :value="item.id"
            />
          </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="questionTitle"
          show-overflow-tooltip
          label="题目标题"
          align="center"
        />
        <el-table-column show-overflow-tooltip label="题目类型" align="center">
          <template #default="{ row }">
            {{ initSubject(row.questionTypes) }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="培训计划分类"
          align="center"
        >
          <template #default="{ row }">
            {{ row.trainingPlanClassificationId }}
          </template>
        </el-table-column>
        <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 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"
      width="700px"
      :title="isEdit"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div style="max-height: 80vh; overflow: auto">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleFormRef"
          label-width="150px"
          class="demo-ruleForm"
        >
          <el-form-item label="题目标题：" prop="questionTitle">
            <el-input
              :disabled="disabledVal"
              v-model="ruleForm.questionTitle"
              maxlength="100"
              type="textarea"
              rows="3"
            ></el-input>
          </el-form-item>
          <el-form-item label="题目类型：" prop="questionTypes">
            <el-select
              :disabled="disabledVal"
              v-model="ruleForm.questionTypes"
              style="width: 100%"
              @change="changeType"
            >
              <el-option label="单选题" value="1" />
              <el-option label="多选题" value="2" />
              <el-option label="判断题" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="题目选项：">
            <div
              v-for="(item, index) in ruleForm.questionOptionXuan"
              :key="index"
            >
              <div style="display: flex; align-items: center; margin-top: 10px">
                <span> {{ item.code }}. </span>
                <el-input
                  :disabled="disabledVal"
                  v-model="item.title"
                  type="textarea"
                  maxlength="1000"
                  style="width: 85%"
                ></el-input>
                <div
                  class="minus_box"
                  v-if="ruleForm.questionOptionXuan.length - 1 === index && !disabledVal&&ruleForm.questionTypes !=3"
                  @click="delOption(item.code)"
                >
                  <span></span>
                </div>
              </div>
            </div>
            <el-button
              v-if="!disabledVal&&ruleForm.questionTypes !=3"
              type="primary"
              size="small"
              @click="addQuestion(ruleForm.questionOptionXuan.length)"
              style="margin-top: 10px"
              >+增加选项</el-button
            >
          </el-form-item>
          <el-form-item label="题目答案：" prop="questionAnschas">
            <el-select
              v-model="ruleForm.questionAnschas"
              placeholder="请选择题目答案"
              :disabled="disabledVal"
              style="width: 100%"
              multiple
              @change="changeAnswer"
            >
              <el-option
                :label="item.code"
                :value="item.code"
                v-for="(item, index) in ruleForm.questionOptionXuan"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="培训计划分类："
            prop="trainingPlanClassificationId"
          >
            <el-select
              :disabled="disabledVal"
              v-model="ruleForm.trainingPlanClassificationId"
              style="width: 100%"
            >
              <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="questionScore">
            <el-input
              :disabled="disabledVal"
              v-model="ruleForm.questionScore"
              type="text"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <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>
  </el-container>
</template>

<script>
import {
  getQuestionBankList,
  saveQuestionBank,
  queryLastLevelClassification,
  delQuestionBankById,
  getQuestionBankById
} from '@/api/planClass/planClass.js'
import { positiveIntNum } from '@/utils/rules'

export default {
  name: 'RuoyiPlanClass',

  data() {
    return {
      isSearch: false, //控制搜索框是否显示
      search: {
        questionTitle: '',
        questionTypes: '',
        trainingPlanClassificationId: '',
        pageNo: 1,
        pageSize: 10
      },
      total: 0, //总数

      list: [],
      dialogVisible: false, //新增/修改的dialog
      isEdit: '',
      disabledVal: false, //查看禁用

      rod: [],
      i: 0,
      questionType: null,
      ruleForm: {
        questionTitle: '',
        questionOptionXuan: [
          {
            // 选中的A B C D
            code: 'A',
            // input中输入的每个选项
            title: '',
            // 布尔值true或false，选的哪个选项，哪个选项就为true
            isRight: false
          },
          {
            code: 'B',
            title: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            isRight: false
          }
        ],
        questionAnschas: [],
        questionTypes: '',
        trainingPlanClassificationId: '',
        questionScore: ''
      },
      rules: {
        questionTitle: [
          { required: true, message: '请输入题目标题', trigger: 'blur' }
        ],
        questionOption: [
          { required: true, message: '请输入题目选项', trigger: 'blur' }
        ],
        questionAnschas: [
          { required: true, message: '请选择题目答案', trigger: 'blur' }
        ],
        questionTypes: [
          { required: true, message: '请选择题目类型', trigger: 'change' }
        ],
        trainingPlanClassificationId: [
          { required: true, message: '请选择培训计划分类', trigger: 'change' }
        ],
        questionScore: [
          { required: true, message: '请输入题目分值', trigger: 'blur' },
          positiveIntNum
        ]
      },
      loading: false // loading 效果
    }
  },

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

  methods: {
    // 随机顺序生成ABCDE...字母的函数
    setDesc() {
      const letterArr = []
      // 字母A的code值是65，但因为已经到字母D了，所以直接从69E开始循环
      for (let i = 69; i < 91; i++) {
        letterArr[i] = String.fromCharCode(i)
      }
      return letterArr
    },
    // 增加选项和答案按钮
    addQuestion(index) {
      // 调用随机顺序生成ABCDE...字母的函数，可以打印randomAbc 数组看下
      // 有69个元素是空的，所以直接进行了截取
      const randomAbc = this.setDesc().splice(69)
      // console.log(this.i,888);
      this.i = index - 4
      const res = [
        ...this.ruleForm.questionOptionXuan,
        {
          code: randomAbc[this.i],
          title: '',
          isRight: false
        }
      ]
      this.i++
      this.ruleForm.questionOptionXuan = res
      this.$forceUpdate();
    },
    delOption(code) {
      // this.ruleForm.questionOptionXuan.splice(index,1)
      this.ruleForm.questionOptionXuan =
        this.ruleForm.questionOptionXuan.filter((item) => item.code !== code)
        this.$forceUpdate();
    },

    // 列表初始化
    initList() {
      try {
        this.loading = true
        getQuestionBankList(this.search).then((res) => {
          if (res.code === 200) {
            this.list = res.data.list
            this.total = res.data.total
          } else {
            this.$message.error(res.msg)
          }
          this.loading = false
        })
      } catch (error) {
        this.loading = false
      }
    },
    // 重置
    reset() {
      this.search.questionTitle = ''
      this.search.questionTypes = ''
      this.search.trainingPlanClassificationId = ''
      this.initList()
    },
    async initQueryLastLevelClassification() {
      const res = await queryLastLevelClassification()
      this.optionList = res.data
    },
    initSubject(type) {
      switch (type) {
        case '0':
          return '全部'
        case '1':
          return '单选题'
        case '2':
          return '多选题'
        case '3':
          return '判断题'
        default:
          return '-'
      }
    },
    async doAdd(type, val) {
      if (type === 1) {
        this.isEdit = '新增'
        this.ruleForm = {
          questionTitle: '',
          questionOptions: [],
          questionAnschas: [],
          questionOptionXuan: [
            {
              // 选中的A B C D
              code: 'A',
              // input中输入的每个选项
              title: '',
              // 布尔值true或false，选的哪个选项，哪个选项就为true
              isRight: false
            },
            {
              code: 'B',
              title: '',
              isRight: false
            },
            {
              code: 'C',
              title: '',
              isRight: false
            },
            {
              code: 'D',
              title: '',
              isRight: false
            }
          ],
          questionTypes: '',
          trainingPlanClassificationId: '',
          questionScore: ''
        }
        this.disabledVal = false
      } else if (type === 2) {
        this.isEdit = '编辑'
        const res = await getQuestionBankById(val.id)
        this.ruleForm = { ...res.data ,questionOptionXuan:res.data.questionOptions.map(
          (item) => {
            return {
              code: item.split('+++')[0].split('.')[0],
              title: item.split('+++')[1],
              isRight: false
            }
          }
        )}
        // this.ruleForm.questionOptionXuan = res.data.questionOptions.map(
        //   (item) => {
        //     return {
        //       code: item.split('+++')[0].split('.')[0],
        //       title: item.split('+++')[1],
        //       isRight: false
        //     }
        //   }
        // )
        this.disabledVal = false
      } else {
        this.isEdit = '查看'
        const res = await getQuestionBankById(val.id)
        this.ruleForm = { ...res.data }
        this.ruleForm.questionOptionXuan = res.data.questionOptions.map(
          (item) => {
            return {
              code: item.split('+++')[0].split('.')[0],
              title: item.split('+++')[1],
              isRight: false
            }
          }
        )
        this.disabledVal = true
      }
      this.$nextTick(()=>{
        this.dialogVisible = true
        })
    },
    // 取消按钮
    cancle() {
      this.$nextTick(() => {
        this.ruleForm = {
          questionTitle: '',
          questionOption: '',
          questionAnschas: [],
          questionTypes: '',
          trainingPlanClassificationId: '',
          questionScore: ''
        }
        this.$refs.ruleFormRef.resetFields()
      })
      this.dialogVisible = false
    },
    // 确定按钮
    submit() {

      this.$refs.ruleFormRef.validate(async (valid) => {
        if (valid) {
          if(!this.ruleForm.questionOptionXuan.every(item=>item.title!=='')) return this.$message.warning(`题目选项内容不能为空!`)
          this.ruleForm.questionOptions = this.ruleForm.questionOptionXuan.map(
            (item) => {
              return item.code + '.' + '+++' + item.title
            }
          )
          const res = await saveQuestionBank(this.ruleForm)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message.success(`${this.isEdit}成功!`)
          this.ruleForm = {
            questionTitle: '',
            questionOption: '',
            questionAnschas: [],
            questionTypes: '',
            trainingPlanClassificationId: '',
            questionScore: ''
          }
          this.dialogVisible = false
        } else {
          this.$message.warning('必传项不能为空!')
          return false
        }
      })
    },
    // 删除
    doDelete(val) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delQuestionBankById(val.id)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message.warning('已取消删除')
        })
    },
    // 修改题目类型
    changeType(val) {
      console.log(val,888);
      this.ruleForm.questionAnschas = []

      if(val ==3){
        this.ruleForm.questionOptionXuan=[
      {
            // 选中的A B C D
            code: 'A',
            // input中输入的每个选项
            title: '是',
          },
          {
            code: 'B',
            title: '否',
          },
      ]
      }else if (val == 1){
        this.ruleForm.questionOptionXuan= [
          {
            // 选中的A B C D
            code: 'A',
            // input中输入的每个选项
            title: '',
            // 布尔值true或false，选的哪个选项，哪个选项就为true
            isRight: false
          },
          {
            code: 'B',
            title: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            isRight: false
          }
        ]
      }else {
        this.ruleForm.questionOptionXuan= [
          {
            // 选中的A B C D
            code: 'A',
            // input中输入的每个选项
            title: '',
            // 布尔值true或false，选的哪个选项，哪个选项就为true
            isRight: false
          },
          {
            code: 'B',
            title: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            isRight: false
          }
        ]
      }
     
    },
    // 修改答案
    changeAnswer() {
      if (this.ruleForm.questionTypes === '1') {
        if (this.ruleForm.questionAnschas.length > 1) {
          return this.$message.warning('单选题只能有一个选项')
        }
      } else if (this.ruleForm.questionTypes === '3') {
        if (this.ruleForm.questionAnschas.length > 1) {
          return this.$message.warning('判断题只能有一个选项')
        }
      }
    }
  }
}
</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;
}

.minus_box {
  width: 20px;
  height: 20px;
  margin-left: 5px;
  cursor: pointer;
  border-radius: 50%;
  border: 2px solid red;
  display: flex;
  justify-content: center;
  align-items: center;

  span {
    display: inline-block;
    width: 10px;
    height: 2px;
    background-color: red;
  }
}
</style>
