<template>
  <div id="questionnaire-survey-option" class="questionnaire-survey-option">
    <div class="questionnaire-title" style="margin-bottom: 32px;">
      {{ optionList[0]&&optionList[0].Options[0] }}
      <div class="question-setting-zone">
        <img src="../../../assets/img/icons/edit-blue.png" @click="editTitle" />
      </div>
    </div>
    <div class="question-row"  v-for="(item,index) in optionList.slice(1)" :key="index">
      <div class="questionnaire-title">
        <span style="color: #C54322;" v-show="item.IsMust==1">*</span>{{index+1}}.{{ item.Question }}
        <div class="question-setting-zone">
          <img src="../../../assets/img/icons/edit-blue.png" @click="editQusetion(item,index)" />
          <img src="../../../assets/img/icons/delete-red.png" @click="deleteQusetion(item,index)" />
        </div>
      </div>
      <div class="questionnaire-options">
        <el-radio-group v-if="item.Type==1" v-model="item.answer">
          <el-radio v-for="it in item.Options" :label="it" :key="it">{{ it }}</el-radio>
        </el-radio-group>
        <el-checkbox-group v-else-if="item.Type==2" v-model="item.answer">
          <el-checkbox v-for="it in item.Options" :label="it" :key="it">{{ it }}</el-checkbox>
        </el-checkbox-group>
        <el-input v-else type="textarea" v-model="item.answer" :rows="5" resize="none"></el-input>
      </div>
    </div>
    <div class="add-sty">
      <span @click="addQusetion">
        <img src="../../../assets/img/set_m/add_ico.png" />
        添加题目
      </span>
    </div>
    <div class="operation-zone">
      <el-button type="primary" style="height: 40;width: 120px;" @click="submit">保存</el-button>
      <el-button style="height: 40;width: 120px;margin-left: 30px;" @click="cancel">取消</el-button>
    </div>
    <!-- 添加/编辑题目 弹窗 -->
    <el-dialog
    width="510px"
    :title="dialogTitle"
    :visible.sync="showQuestionOption"
    :append-to-body="true"
    v-dialogDrag @closed="questionDiaClose">
      <el-form style="padding: 10px 40px 0;"
      ref="questionForm"
      hide-required-asterisk
      :model="questionForm">
        <el-form-item label="" prop="Type" :rules="[{required:true,message:'请选择题目类型',trigger:'change'}]">
          <el-radio-group v-model="questionForm.Type" :disabled="isEdit">
            <el-radio :label="1">单选</el-radio>
            <el-radio :label="2">多选</el-radio>
            <el-radio :label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="" prop="IsMust" :rules="specialRules[0]">
          <div style="display: flex;align-items: center;justify-content: space-between;">
            <el-select v-model="questionForm.IsMust" style="width: 240px;">
              <el-option label="必答题" :value="1"></el-option>
              <el-option label="非必答题" :value="0"></el-option>
            </el-select>
            <el-input-number v-model="questionForm.Sort" style="width: 120px;"
            controls-position="right" :min="0" step-strictly placeholder="输入排序"></el-input-number>
          </div>
        </el-form-item>
        <el-form-item label="" prop="Question" :rules="[{required:true,message:'问题描述不能为空',trigger:'change'}]">
          <el-input v-model="questionForm.Question" placeholder="请输入问题描述" style="width: 100%;" />
        </el-form-item>
        <template v-if="questionForm.Type==1 || questionForm.Type==2">
          <el-form-item label="" :prop="`Options.${ansInd}`" :rules="[{required:true,message:'选项不能为空',trigger:'change'}]"
          v-for="(ans,ansInd) in questionForm.Options" :key="ansInd">
            <div style="display: flex;align-items: center;">
              <el-input v-model="questionForm.Options[ansInd]" placeholder="请输入选项" style="flex-grow: 1;" >
                <div slot="prefix" style="margin-left: 5px;color: #333333;font-size: 14px;"> 
                  {{ `${OptionLetterList[ansInd]} :`}}
                </div>
              </el-input>
              <img src="../../../assets/img/icons/delete-red.png" v-show="questionForm.Options.length>2"
              style="margin-left: 18px;width: 16px;cursor: pointer;" @click="deleteAnswer(ansInd)"/>
            </div>
          </el-form-item>
          <div class="add-sty" style="margin-top:0 ;">
            <span @click="addAnswer">
              <img src="../../../assets/img/set_m/add_ico.png" />
              添加选项
            </span>
          </div>
        </template>
        <div class="operation-zone">
          <el-button type="primary" style="width: 120px;height: 40px;" @click="submitQuestion">确定</el-button>
          <el-button style="width: 120px;height: 40px;margin-left: 26px;" @click="showQuestionOption=false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 编辑说明弹窗 -->
    <el-dialog
    width="510px"
    :title="dialogTitle"
    :visible.sync="showTitleDia"
    :append-to-body="true"
    @closed="titleDiaClose"
    v-dialogDrag>
      <el-form style="padding: 10px 40px 0;"
      ref="titleForm"
      hide-required-asterisk
      :model="titleForm">
        <el-form-item label="" prop="title" :rules="[{required:true,message:'说明不能为空',trigger:'blur'}]">
          <el-input v-model="titleForm.title" placeholder="请输入内容" style="width: 100%;" type="textarea"
          :rows="4" resize="none"></el-input>
        </el-form-item>
        <div class="operation-zone">
          <el-button type="primary" style="width: 120px;height: 40px;" @click="submitTitle">确定</el-button>
          <el-button style="width: 120px;height: 40px;margin-left: 26px;" @click="showTitleDia=false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import{etaTrialInterence}from '@/api/modules/crmApi.js';

  export default {
    name:'questionnaireOption',
    data() {
      this.OptionLetterList=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
      'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
      return {
        optionList:[],
        // 弹窗
        dialogTitle:'',
        showQuestionOption:false,
        showTitleDia:false,
        questionForm:{
          Type:1,
          IsMust:1,
          Sort:0,
          Question:'',
          Options:['','']
        },
        isEdit:false,
        questionIndex:0,
        tempTile:'尊敬的用户，感谢您使用系统，以下是对系统使用的调研问卷，我们期待您真实的反馈！',
        titleForm:{
          title:''
        },
        specialRules:[
          [
            {required:true,message:'请选择题目是否必答',trigger:'change'},
            {validator:(rule,value,callback)=>{
              if(!this.questionForm.Sort&&this.questionForm.Sort!=0){
                callback(new Error('请选择排序'))
              }else{
                callback()
              }
            },trigger:['blur','change']}
          ]
        ]
      }
    },
    methods:{
      getQuestionOption(){
        etaTrialInterence.getQuestionOptionList().then(res=>{
          if(res.Ret==200){
            this.optionList = res.Data.List || []
            if(this.optionList.length==0){
              // 添加标题项
              this.optionList.push({
                Question:'标题',
                Type:4,
                Sort:-1,
                Options:[''],
                CreateTime:this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
              })
            }
            this.tempTile = this.optionList[0].Options[0]
            this.optionList.forEach(item =>{
              this.$set(item,'answer',item.Type==2?[]:'')
            })
          }
        })
      },
      // 编辑说明
      editTitle(){
        this.titleForm.title = this.optionList[0].Options[0]
        this.dialogTitle = "编辑说明"
        this.showTitleDia = true
      },
      // 编辑说明弹窗关闭
      titleDiaClose(){
        this.titleForm.title=''
        this.$nextTick(()=>{
          this.$refs.titleForm.clearValidate()
        })
      },
      // 添加题目
      addQusetion(){
        this.dialogTitle = "添加题目"
        this.showQuestionOption = true
        this.questionForm.Sort = this.optionList[this.optionList.length-1].Sort+1
        this.isEdit=false
      },
      editQusetion(item,index){
        this.dialogTitle = "编辑题目"
        this.questionIndex = index+1
        this.questionForm={
          ...item,
          Options:[...item.Options],
          answer:item.Type==2?[]:''}
        this.isEdit=true
        this.showQuestionOption = true
      },
      // 删除题目
      deleteQusetion(item,index){
        this.$confirm('删除题目将一起删除该题目下所有回答，确认删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          if(item.QuestionnaireId){
            // 数据库里原本有，请求删除接口
            const res=await etaTrialInterence.questionOptionDelete({QuestionnaireId:item.QuestionnaireId})
            if(res.Ret !=200) return 
          }
          this.optionList.splice(index+1,1)
          this.$message.success('删除成功')
        }).catch(() => {});
      },
      // 添加选项 - 单选/多选
      addAnswer(){
        this.questionForm.Options.push('')
      },
      // 删除选项
      deleteAnswer(index){
        this.questionForm.Options.splice(index,1)
      },
      // 题目弹窗关闭
      questionDiaClose(){
        this.questionForm={
          Type:1,
          IsMust:1,
          Sort:0,
          Question:'',
          Options:['','']
        },
        this.$nextTick(()=>{
          this.$refs.questionForm.clearValidate()
        })
      },
      // 提交问题
      submitQuestion(){
        this.$refs.questionForm.validate(valid=>{
          if(valid){
            // 单选、多选选项判断
            if(this.questionForm.Type==1 || this.questionForm.Type==2){
              let clearRepeatList = Array.from(new Set(this.questionForm.Options))
              if(this.questionForm.Options.length!=clearRepeatList.length){
                this.$message.warning('有选项内容重复')
                return 
              }
            }

            if(!(this.questionForm.QuestionnaireId || this.questionForm.virtualId)){
              //添加
              this.optionList.push({
                virtualId:'00000',
                Type:this.questionForm.Type,
                Sort:this.questionForm.Sort,
                IsMust:this.questionForm.IsMust,
                Question:this.questionForm.Question,
                Options:this.questionForm.Type==3?[]:this.questionForm.Options,
                CreateTime:this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                answer:this.questionForm.Type==2?[]:''
              })
            }else{
              this.optionList[this.questionIndex]={
                ...this.questionForm,
                Options:[...this.questionForm.Options],
                answer:this.questionForm.Type==2?[]:''}
            }
            // 排序
            this.optionList.sort((a,b) =>{
              if(b.Sort != a.Sort){
                return a.Sort - b.Sort
              }else{
                return new Date(b.CreateTime) - new Date(a.CreateTime)
              }
            })
            // console.log(this.questionForm,this.optionList);
            this.$message.success(this.dialogTitle+'成功')
            this.showQuestionOption=false
          }
        })
      },
      // 提交说明
      submitTitle(){
        this.$refs.titleForm.validate(valid=>{
          if(valid){
            this.optionList[0].Options[0] = this.titleForm.title
            this.$message.success(this.dialogTitle+'成功')
            this.showTitleDia=false
          }
        })
      },
      // 保存
      submit(){
        etaTrialInterence.questionOptionSave({List:this.optionList}).then(res=>{
          if(res.Ret ==200){
            this.$message.success('保存成功')
            this.getQuestionOption()
          }
        })
      },
      // 取消保存
      cancel(){
        this.getQuestionOption()
      }
    },
    created() {
      this.getQuestionOption()
    },
  }
</script>

<style lang="scss" scoped>
  .questionnaire-survey-option{
    width: 40%;
    min-width: 750px;
    background-color: white;
    padding: 30px;
    box-sizing: border-box;
    min-height: calc(100vh - 110px);
    .question-row{
      margin-top: 26px;
      .questionnaire-options{
        margin-top: 18px;
        padding: 20px;
      }
    }
    .operation-zone{
      margin-top: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .questionnaire-title{
      font-weight: 500;
      font-size: 16px;
      display: flex;
      align-items: center;
      .question-setting-zone{
        display: flex;
        align-items: center;
        img{
          cursor: pointer;
          height: 16px;
          margin-left: 20px;
        }
      }
    }
  }

  .add-sty{
    font-size: 14px;
    font-weight: 400;
    color: #409EFF;
    margin-top: 60px;
    span{
      display: inline-flex;
      align-items: center;
      cursor: pointer;
      img{
        height: 16px;
        margin-right: 8px;
      }
    }
  }
  .operation-zone{
    padding: 50px 0 35px;
    text-align: center;
  }

</style>
<style lang="scss">
  .el-dialog .el-input {
    width: 100% !important;
  }
#questionnaire-survey-option{
  .el-checkbox{
    margin-right: 40px;
  }
  .el-radio{
    margin-right: 40px;
  }
}
</style>