<template>
  <div>
    <xy-dialog ref="dialog" :is-show.sync="isShow" type="form" :title="type === 'add' ? '新增资料' : '编辑资料'" :form="form"
      :rules="rules" @submit="submit">
      <template v-slot:studyName>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>学习内容名称：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.studyName" placeholder="请输入学习内容名称" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:studyDates>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>学习测验有效期：
          </div>
          <div class="xy-table-item-content">
            <el-select clearable placeholder="请选择类型" v-model="form.type" style="width: 300px;">
              <el-option v-for="item in studyDates" :value="item.value" :key="item.value" :label="item.label">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>

      <template v-slot:range>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            测试通过标准正确率需要达到：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.range" placeholder="请输入正确率" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:min>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            至少需要学习：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.min" placeholder="请输入" clearable style="width: 150px;margin-right:5px"></el-input>分钟
          </div>
        </div>
      </template>
      <template v-slot:recommend>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            学习内容：
          </div>
          <div class="xy-table-item-content">
            <el-input :autosize="{minRows:2}" type="textarea" v-model="form.recommend" placeholder="请输入学习内容" clearable
              style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:picture_list>
        <div class="xy-table-item">
          <div class="xy-table-item-label">资料上传：</div>
          <div class="xy-table-item-content">
            <el-upload style="width: 620px" :multiple="true" class="upload-demo" :action="action"
              :before-upload="uploadBeforePic" :on-success="picListSuccessHandler" :on-remove="picListRemoveHandler"
              :file-list="fileList" list-type="picture" multiple>
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">
                只能上传jpg/png/mp4文件，且不超过10M
              </div> -->
            </el-upload>
          </div>
        </div>
      </template>
      <template v-slot:question_list>
        <div class="xy-table-item">
          <div class="xy-table-item-label">测试题库：</div>
          <div class="xy-table-item-content">
            <Button type="primary" icon="md-add" style="margin-bottom: 10px" @click="drawer=true">新增题目</Button>
            <xy-table style="width: 620px" :height="260" :is-page="false" :list="form.question_list"
              :table-item="questionTable">
              <template v-slot:btns>
                <el-table-column label="操作" width="180" header-align="center" align="center">
                  <template v-slot:default="scope">
                    <Button size="small" type="primary" ghost @click="editQuestion(scope.row,scope.$index)">编辑</Button>
                    <Button style="margin-left:8px" size="small" type="primary" ghost
                      @click="form.question_list.splice(scope.$index, 1)">删除</Button>
                  </template>
                </el-table-column>
              </template>
            </xy-table>
          </div>
        </div>
      </template>

    </xy-dialog>
    <!-- 题库 -->
    <el-drawer :title="drawerEdit?'编辑':'新增'" :visible.sync="drawer" direction="rtl" @close="closeDrawer">
      <el-form :model="questionForm" ref="questionForm" label-width="100px"
        style="padding:20px;height:100%;padding-bottom: 120px;overflow-y: auto;">
        <el-form-item label="题目名称" prop="name" :rules="[{ required: true, message: '请输入题目名称' }]">
          <el-input v-model="questionForm.name" placeholder="请输入题目名称"></el-input>
        </el-form-item>
        <el-form-item label="题目类型" prop="type" :rules="[{ required: true, message: '请选择题目类型' }]">
          <el-select clearable placeholder="请选择类型" v-model="questionForm.type" style="width:100%">
            <el-option v-for="item in questionType" :value="item.value" :key="item.value" :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="答案数量" prop="ansnum" :rules="[{ required: true, message: '请输入答案数量' }]">
          <el-input type="number" v-model="questionForm.ansnum" placeholder="请输入答案数量"></el-input>
        </el-form-item>
        <div v-if="questionForm.ansnum>0">
          <template v-for="(item,index) in answerLabel">
            <el-form-item :label="`选项${item}`" :prop="questionForm[item]" v-if="index<questionForm.ansnum">
              <el-input v-model="questionForm[item]" placeholder="请输入答案"></el-input>
            </el-form-item>
          </template>
        </div>
        <el-form-item v-if="questionForm.type==2&&questionForm.ansnum>1" label="正确选项" prop="correctKeydouble">
          <el-select v-model="questionForm.correctKeydouble" style="width: 100%" multiple placeholder="请选择正确选项">
            <template v-for="(item,index) in answerLabel">
              <el-option v-if="index<questionForm.ansnum" :key="index" :label="item" :value="item">
              </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item v-else label="正确选项" prop="correctKey">
          <el-select v-model="questionForm.correctKey" style="width: 100%" placeholder="请选择正确选项">
            <template v-for="(item,index) in answerLabel">
              <el-option v-if="index<questionForm.ansnum" :key="index" :label="item" :value="item">
              </el-option>
            </template>
          </el-select>
        </el-form-item>
        <div style="text-align: right;">
          <Button ghost type="primary" @click="closeDrawer">取消</Button>
          <Button type="primary" @click="submitAnswer" style="margin-left:8px">确定</Button>
        </div>
      </el-form>


    </el-drawer>

  </div>
</template>

<script>
  import {
    store,
    show,
    save
  } from "@/api/resource/study.js"
  import {
    getparameter
  } from "@/api/system/dictionary";
  export default {
    components: {},
    data() {
      return {
        isShow: false,
        type: 'add',
        id: '',
        action: `${process.env.VUE_APP_UPLOAD_API}`,
        fileList: [],
        form: {
          studyName: "",
          studyDates: "",
          min: "",
          range: "",
          recommend: "",
          picture_list: [],

          question_list: [
            {A:'A',
            B:"b",
            ans:"A",
            ansnum:"2",
            correctKey: "A",
            correctKeydouble:"",
            name:"单选1",
            type:1,
            typeName:"单选"},
            {A:'AB',
            B:"bA",
            ans:"B",
            ansnum:"2",
            correctKey: "B",
            correctKeydouble:"",
            name:"单选2",
            type:1,
            typeName:"单选"},
            {A:'ABC',
            B:"bAC",
            ans:"A,B",
            ansnum:"2",
            correctKey: "",
            correctKeydouble:["A","B"],
            name:"多选2",
            type:2,
            typeName:"多选"}
          ]
        },
                  // 题库
        drawer: false,
        drawerIndex: 0,
        drawerEdit:false,
        questionForm: {
          name: "",
          type: "",
          ansnum: "",
          correctKey: "",
          correctKeydouble: ""
        },
        // questionRules:[

        // ]
        questionType: [{
          label: "单选",
          value: 1,
        }, {
          label: "多选",
          value: 2
        }],
        answerLabel: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
        questionTable: [
          {
            label: '序号',
            sortable: false,
            type:"index"
          },{
            label: '题目名称',
            sortable: false,
            prop: 'name',
          },
          {
            label: '题目类型',
            sortable: false,
            prop: 'typeName'
          },
          {
            label: '答案选项',
            sortable: false,
            prop: 'ans'
          },
        ],
        rules: {},
        studyDates: []

      }
    },
    created() {
      this.getLabels()
    },
    methods: {
      async getLabels() {
        const res = await getparameter({
          number: "studyDate",
        });
        this.studyDates = res?.detail;
      },
      //上传
      uploadBeforePic(file) {
        if (file.size / 1000 > 2048) {
          this.$successMessage('上传图片大小超过2M！', '', 'warning')
          return false;
        }
      },
      picListSuccessHandler(res, file, fileList) {
        this.form.picture_list = fileList.map((item) => {
          return item.response ? {
            picture: item.response.url,
            type: 0,
          } : {
            picture: item.url,
            type: 0,
          };
        });
      },
      picListRemoveHandler(file, fileList) {
        this.form.picture_list = fileList.map((item) => {
          return item.response ? {
            picture: item.response.url,
            type: 0,
          } : {
            picture: item.url,
            type: 0,
          };
        });
      },


      async getDetail() {
        const res = await show({
          id: this.id
        })
        this.form = {

        }
      },
      // 题库
      closeDrawer() {
        this.questionForm = {
          name: "",
          type: "",
          ansnum: "",
          correctKey: "",
          correctKeydouble: ""
        }
        this.drawer = false
      },
      editQuestion(row, index) {
        console.log(row, index)
        this.questionForm = row
        this.drawerIndex = index
        this.drawerEdit = true
        this.drawer = true
      },
      submitAnswer() {
        console.log(this.questionForm)
        this.$refs['questionForm'].validate().then(res => {
          let obj = this.questionForm
          obj.typeName = obj.type == 1 ? "单选" : "多选"
          obj.ans = obj.type == 1 ? obj.correctKey : obj.correctKeydouble.join(",")
          if(this.drawerEdit){
            this.form.question_list[this.drawerIndex]=obj
            this.drawerIndex = 0
            this.drawerEdit = false
          }else{
            this.form.question_list.push(obj)
          }

          this.$nextTick(function() {
            // this.$refs['questionForm'].resetFields()
            this.questionForm = {
              name: "",
              type: "",
              ansnum: "",
              correctKey: "",
              correctKeydouble: ""
            }
            this.drawer = false
          })

        }).catch(err => {
          this.$successMessage('请填写完整信息！', '', 'warning')
        })
      },
      submit() {

        if (this.type === 'add') {
          console.log(this.form)
          // return
          store({

          }).then(res => {
            this.$successMessage('add', '资料')
            this.isShow = false
            this.$emit('refresh')
          })
          return
        }
        if (this.type === 'editor') {
          save({
            id: this.id,

          }).then(res => {
            this.$successMessage('editor', '资料')
            this.isShow = false
            this.$emit('refresh')
          })
        }
      }
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          if (this.type === 'editor') {
            this.getDetail()
          }
        } else {
          this.id = ''
          this.type = ''
          this.$refs['dialog'].reset()
        }
      }
    }

  }
</script>

<style scoped lang="scss">

  .img__delete {
    transform: scale(0.8, 0.8);

    position: absolute;
    top: 4px;
    right: 4px;
  }
  ::v-deep .xy-table-item-label {
    width: 160px !important;
  }
</style>
