<template>
  <div>
    <xy-dialog ref="dialog" :is-show.sync="isShow" type="form" :title="type === 'add' ? '新增资料' : '编辑资料'" :form="form"
      :rules="rules" @submit="submit">
      <template v-slot:name>
        <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.name" placeholder="请输入学习内容名称" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:expire_day>
        <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.expire_day" style="width: 300px;">
              <el-option v-for="item in studyDates" :value="item.id" :key="item.id" :label="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>

      <template v-slot:rate>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            测试通过标准正确率需要达到：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.rate" placeholder="请输入正确率" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:minute>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            至少需要学习：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.minute" placeholder="请输入" clearable style="width: 150px;margin-right:5px">
            </el-input>分钟
          </div>
        </div>
      </template>
      <template v-slot:content>
        <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.content" placeholder="请输入学习内容" clearable
              style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:type>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            面向对象：
          </div>
          <div class="xy-table-item-content">
            <el-select clearable placeholder="请选择类型" v-model="form.type" style="width: 300px;">
              <el-option v-for="item in types" :value="item.id" :key="item.id" :label="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:file>
        <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:ask_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.ask_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.ask_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="title" :rules="[{ required: true, message: '请输入题目名称' }]">
          <el-input v-model="questionForm.title" 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['ans'][index]" v-if="index<questionForm.ansnum">
              <el-input v-model="questionForm['ans'][index]" 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="index">
              </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="index">
              </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 {
    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: [],
        types: [{
            id: 1,
            value: "访客"
          },
          {
            id: 2,
            value: "施工"
          },
          {
            id: 3,
            value: "车辆"
          }
        ],
        form: {
          name: "",
          expire_day: "",
          type: "",
          rate: "",
          minute: "",
          content: "",
          file: [],
          ask_list: []
        },
        // 题库
        drawer: false,
        drawerIndex: 0,
        drawerEdit: false,
        questionForm: {
          title: "",
          type: "",
          ans: [],// 答案内容存储
          answer: [],// 传递的答案数组
          ansnum: "",// 答案数量
          correctKey: "",//单选答案index
          correctKeydouble: []//多选答案index
        },
        // questionRules:[

        // ]
        questionType: [{
          label: "单选",
          value: 1,
        }, {
          label: "多选",
          value: 2
        }],
        answerLabel: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', "K", "L"],
        questionTable: [{
            label: '序号',
            sortable: false,
            type: "index"
          }, {
            label: '题目名称',
            sortable: false,
            prop: 'title',
          },
          {
            label: '题目类型',
            sortable: false,
            prop: 'type',
            formatter: (cell, data, value) => {
              return value == 1 ? '单选' : '多选'
            }
          },
          {
            label: '答案选项',
            sortable: false,
            prop: 'isans'
          },
        ],
        rules: {},
        studyDates: [{
          id: 90,
          value: '三个月'
        }, {
          id: 180,
          value: '六个月'
        }, {
          id: 270,
          value: '九个月'
        }]

      }
    },
    created() {},
    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.file = fileList.map((item) => {
          return item.response ? item.response.id : item.id
        });
      },
      picListRemoveHandler(file, fileList) {
        this.form.file = fileList.map((item) => {
          return item.response ? item.response.id : item.id
        });
      },


      async getDetail() {
        const res = await show({
          id: this.id
        })
        let answer = []
        for(var m of res.asks){
          let conArr = [] // 答案内容
          let result = '' // 单选答案index
          let resultdouble = [] // 多选答案index
          let _isans = ''
          m.answer.map((k,i)=>{
            conArr.push(k.content)
            if(k.result==1){
              m.type==1?result = i:resultdouble.push(i)
            }
          })
          if(m.type==1){
            _isans = this.answerLabel[result]
          }else{
            resultdouble.map(k => {
              _isans += this.answerLabel[k]
            })
          }
          answer.push({
              "title": m.title,
              "type": m.type,
              "ans": conArr,
              "answer": m.answer,
              "ansnum": m.answer.length,
              "correctKey": result,
              "correctKeydouble": resultdouble,
              "isans": _isans
          })
        }
        // this.questionForm = answer
        this.form = {
          name: res?.name,
          expire_day: res?.expire_day,
          type: res ? parseInt(res.type) : "",
          rate: res?.rate,
          minute: res?.minute,
          content: res?.content,
          file: res?.file,
          ask_list: answer
        }
        console.log("before",this.form.ask_list)
        this.fileList = res?.file_detail
      },
      // 题库
      closeDrawer() {
        this.questionForm = {
          title: "",
          type: "",
          ans: [],
          answer: [],
          ansnum: "",
          isans: '',
          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() {
        // return
        this.$refs['questionForm'].validate().then(res => {
          let answerArr = []
          let obj = this.questionForm
          obj.ans.map((item, index) => {
            answerArr.push({
              content: item,
              result: 0
            })
          })
          if (obj.type == 1) {
            answerArr[obj.correctKey]['result'] = 1
            obj.isans = this.answerLabel[obj.correctKey]
          } else {
            obj.correctKeydouble.map(k => {
              answerArr[k]['result'] = 1
              obj.isans += this.answerLabel[k]
            })
          }
          obj.answer = answerArr
          if (this.drawerEdit) {
            this.form.ask_list[this.drawerIndex] = obj
            this.drawerIndex = 0
            this.drawerEdit = false
          } else {
            this.form.ask_list.push(obj)
          }
          this.$nextTick(function() {
            this.questionForm = {
              title: "",
              type: "",
              ans: [],
              answer: [],
              ansnum: "",
              correctKey: "",
              correctKeydouble: ""
            }
            this.drawer = false
          })

        }).catch(err => {
          this.$successMessage('请填写完整信息！', '', 'warning')
        })
      },
      submit() {
        console.log(this.form)
        // return
        let that = this
        if (this.type === 'editor') {
          this.form.id = this.id
        }
        save({
          ...that.form
        }).then(res => {
          this.$successMessage(this.type, '学习资料')
          this.isShow = false
          this.$emit('refresh')
        })
      }
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          if (this.type === 'editor') {
            this.getDetail()
          }
        } else {
          this.id = ''
          this.type = ''
          this.fileList = []
          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>
