<script setup lang="ts" name="ExamList">
import { ref, onMounted, reactive, toRefs, onBeforeUpdate, getCurrentInstance } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { questionnaireMobile, submitquestionnaire } from '@/api/satisfaction/index'
import { useDict } from '@/common/utils/dict'
import { getCompanyName } from '@/common/utils/transcoding'
// import { showFailToast, showLoadingToast, closeToast, showSuccessToast } from 'vant'

const { questionnaire_type, markpape_type, yes_no, topic_type, single_option, judge_option, train_examination_targets } = useDict('questionnaire_type', 'markpape_type', 'yes_no', 'topic_type', 'single_option', 'judge_option', 'train_examination_targets')
const { proxy }:any = getCurrentInstance()
// const router = useRouter()
// const route = useRoute()
const mainId = ref('')
const mineId = ref('')
onLoad((option)=>{
  mainId.value = option.mainId ? option.mainId : ''
  mineId.value = option.mineId ? option.mineId : ''
  if(option.mainId) {
    getInfo(option.mainId)
  }
})
function getInfo(mainId) {
  questionnaireMobile(mainId).then(response => {
    form.value = response.data
  })
}
const leaveTypeName = ref('')
const show = reactive({
  leaveType: false
})

const data:any = reactive({
  form: {
    id: null,
    belongCompany: null,
    questionnaireTitle: null,
    questionnaireBlurb: null,
    examinationType: null,
    questionBankId: null,
    questionBankName: null,
    questionnaireTargets: null,
    questionnaireTargetsName: null,
    questionnaireTargetsId: null,
    isAll: null,
    isAnonymity: '1',
    isStatus: '0',
    isRelease: '1',
    tenantId: null,
    companyId: null,
    deptId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    questionnaireTargetsUserList: [], // 用户
    questionDirectoryList: []// 题库
  },
  rules: {
    belongCompany: [{ required: true, message: '所属公司不能为空', trigger: 'blur' }],
    examinationName: [{ required: true, message: '考试名称不能为空', trigger: 'blur' }],
    examinationType: [{ required: true, message: '考试类型不能为空', trigger: 'blur' }],
    examinationTotal: [{ required: true, message: '题目总数不能为空', trigger: 'blur' }],
    examinationFullScore: [{ required: true, message: '考试满分不能为空', trigger: 'blur' },
      { pattern: /^[1-9]\d{0,1}$|^100$/, message: '请输入正确的格式,1-100的整数' }],
    examinationPassScore: [{ required: true, message: '及格分数不能为空', trigger: 'blur' },
      { pattern: /^[1-9]\d{0,1}$|^100$/, message: '请输入正确的格式,1-100的整数' }],
    examinationStartTime: [{ required: true, message: '考试开始时间不能为空', trigger: 'blur' }],
    examinationEndTime: [{ required: true, message: '考试结束时间不能为空', trigger: 'blur' }],
    isExamination: [{ required: true, message: '是否可以补考不能为空', trigger: 'blur' }],
    isPlan: [{ required: true, message: '是否关联计划不能为空', trigger: 'blur' }],
    planName: [{ required: true, message: '计划名称不能为空', trigger: 'blur' }],
    markPapeType: [{ required: true, message: '阅卷类型不能为空', trigger: 'blur' }],
    markPapePeople: [{ required: true, message: '阅卷人不能为空', trigger: 'blur' }],
    isRandom: [{ required: true, message: '是否随机选题不能为空', trigger: 'blur' }],
    examinationDuration: [{ required: true, message: '考试时长(分钟)不能为空', trigger: 'blur' },
      { pattern: /^[1-9]\d*$/, message: '请输入正确的格式,正整数' }],
    questionBankName: [{ required: true, message: '题库名称不能为空', trigger: 'blur' }]
  },
  queryParams: {
  }
})

const { form, rules, queryParams } = toRefs(data)

const loading = ref(false)

const isRead = ref(false)
function onClickStart() {
  isRead.value = true
}
const planShow = ref(false)
const markPapeShow = ref(false)

// 回显数据字
const selectDictLabel = (datas: any, value: number | string) => {
  if (value === undefined) {
    return ''
  }
  const actions: Array<number | string> = []
  Object.keys(datas).some((key) => {
    if (datas[key].value === '' + value) {
      actions.push(datas[key].label)
      return true
    }
  })
  if (actions.length === 0) {
    actions.push(value)
  }
  return actions.join('')
}
const exercisesIndex = ref(0)

/**
 * 单选
 * @param index
 * @param childIndex
 */
function singleCorrectAnswer(index, childIndex:any) {
  console.log(index, childIndex)
  form.value.questionDirectoryList[index].mineAnswerName = form.value.questionDirectoryList[index].questionDirectoryOptionList[childIndex].directoryOption
  form.value.questionDirectoryList[index].mineAnswer = form.value.questionDirectoryList[index].questionDirectoryOptionList[childIndex].directoryOption
  form.value.questionDirectoryList[index].mineAnswerScore = form.value.questionDirectoryList[index].questionDirectoryOptionList[childIndex].optionScore
}
/**
 * 多选
 * @param index
 * @param childIndex
 */
function doubleCorrectAnswer(index, childIndex:any) {

  let list = form.value.questionDirectoryList[exercisesIndex.value].mineAnswerSub
  let sum = 0
  for (let i = 0; i < list.length; i++) {
    sum = sum + Number(form.value.questionDirectoryList[exercisesIndex.value].questionDirectoryOptionList.find(item => item.directoryOption === list[i]).optionScore)
  }

  form.value.questionDirectoryList[exercisesIndex.value].mineAnswer = form.value.questionDirectoryList[exercisesIndex.value].mineAnswerSub.join(',')
  form.value.questionDirectoryList[exercisesIndex.value].mineAnswerName = form.value.questionDirectoryList[exercisesIndex.value].mineAnswerSub.join(',')
  form.value.questionDirectoryList[exercisesIndex.value].mineAnswerScore = sum


}
const checkboxRefs:any = ref([])
const toggle = (index, childIndex) => {

  proxy.$refs[`checkboxRefs${index}${childIndex}`][0].toggle()


}
function judgeCorrectAnswer(index, childIndex) {

  form.value.questionDirectoryList[index].mineAnswerName = judge_option.value[childIndex].label
  // form.value.questionDirectoryList[index].mineAnswer = judge_option.value[childIndex].label
  form.value.questionDirectoryList[index].mineAnswerScore = form.value.questionDirectoryList[index].questionDirectoryOptionList[childIndex].optionScore

  // form.value.questionDirectoryList[index].mineAnswerScore = form.value.questionDirectoryList[index].questionDirectoryOptionList[childIndex].optionScore
}
function handlePreView() {
  if (form.value.questionDirectoryList[exercisesIndex.value].topicType === '4' && (form.value.questionDirectoryList[exercisesIndex.value].mineAnswer === null || form.value.questionDirectoryList[exercisesIndex.value].mineAnswer === '')) {
    // showFailToast('请输入答案')
    uni.showToast({
      title: '请输入答案',
      icon: 'none'
    })
    return
  }
  if (form.value.questionDirectoryList[exercisesIndex.value].topicType === '4' && (form.value.questionDirectoryList[exercisesIndex.value].mineAnswer)) {
    form.value.questionDirectoryList[exercisesIndex.value].mineAnswerName = form.value.questionDirectoryList[exercisesIndex.value].mineAnswer
  
    form.value.questionDirectoryList[exercisesIndex.value].mineAnswerScore = '0'
  }
  if (!form.value.questionDirectoryList[exercisesIndex.value].mineAnswerName || form.value.questionDirectoryList[exercisesIndex.value].mineAnswerName === '') {
      uni.showToast({
        title: '请输入答案',
        icon: 'none'
      })
    return
  }
  exercisesIndex.value++
}
function changejianDa() {
  console.log(form.value.questionDirectoryList[exercisesIndex.value].mineAnswer)
  form.value.questionDirectoryList[exercisesIndex.value].mineAnswerName = form.value.questionDirectoryList[exercisesIndex.value].mineAnswer
  form.value.questionDirectoryList[exercisesIndex.value].mineAnswerScore = '0'
}
// 校验失败
function onFailed(e) {
  console.log('error', e)
}
// 校验结果
function onSubmit() {

  form.value.questionDirectoryList.forEach(element => {
    if (exercisesIndex.value === form.value.questionDirectoryList.length - 1) {
      if (element.topicType === '1') {
        if (element.mineAnswerName === null || element.mineAnswerName === '') {
          uni.showToast({
            title: '请输入答案'
          })
          return
        }
      }
      if (element.topicType === '2') {
        if (element.mineAnswerName === null || element.mineAnswerName === '') {
          uni.showToast({
            title: '请输入答案'
          })
          return
        }
      }
      if (element.topicType === '3') {
        if (element.mineAnswerName === null || element.mineAnswerName === '') {
          uni.showToast({
            title: '请输入答案'
          })
          return
        }
      }
      if (element.topicType === '4') {
        console.log(element.mineAnswer)
        if (element.mineAnswer) {
          element.mineAnswerName = element.mineAnswer
           element.mineAnswerScore = '0'
        }
        if (element.mineAnswer === null || element.mineAnswer === '') {
          uni.showToast({
            title: '请输入答案'
          })
          return
        }

      }

    }
  })


  modalRef.value.open()
}
const modalRef:any = ref(null)
const dialogShow = ref(false)
function confirmSubmit() {
   uni.showLoading({ title: '提交中...', mask: true })
  form.value.mineId = mineId.value
  console.log(form.value)
  submitquestionnaire(form.value).then(response => {
     uni.hideLoading()
    uni.showToast({ title: '提交成功' })
    setTimeout(() => uni.navigateBack(), 1300)
  }).catch(() => {
    uni.hideLoading()
  })
}
</script>

<template>
  <div class="container full float-bottom">
    <div class="container__body">
      <div class="container__card flex">
        <div v-if="!isRead">
          <uv-cell title="所属公司" :value="getCompanyName(form.belongCompany)" />
          
          <uv-cell title="问卷名称" :value="form.questionnaireTitle" />
          
          <uv-cell title="问卷类型" :value="selectDictLabel(questionnaire_type, form.examinationType)" />
          
          <uv-cell title="题库名称" :value="form.questionBankName" />
          
          <uv-cell title="是否匿名" :value="selectDictLabel(yes_no, form.isAnonymity)" />
          <uv-cell title="是否发布" :value="selectDictLabel(yes_no, form.isRelease)" />

          <uv-cell title="问卷简介" :value="form.questionnaireBlurb" />
          <uv-cell title="问卷对象" :value="selectDictLabel(train_examination_targets, form.questionnaireTargets)" />
          <uv-cell title="问卷范围" :value="form.questionnaireTargetsName" />

        </div>
        <uv-form
          v-if="isRead"
          ref="formRef"
          label-position="top"
          @submit="onSubmit">
          
          <uv-cell-group>
            <block v-for="(item, index) in form.questionDirectoryList" :key="index">
              <!-- 当前题目展示 -->
              <uv-cell-group v-if="exercisesIndex === index">
                <!-- 题目类型和内容 -->
                <view class="tigan">
                  <view 
                    class="leixing"
                    :class="[
                      item.topicType === '1' ? 'question-single' :
                      item.topicType === '2' ? 'question-double' :
                      item.topicType === '3' ? 'question-panduan' :
                      item.topicType === '4' ? 'question-jianda' :
                      'question-common'
                    ]">
                    {{ selectDictLabel(topic_type, item.topicType) }}
                  </view>
                  <view class="neirong">
                    {{ item.topicContact }}
                  </view>
                </view>
                
                <!-- 单选题 -->
                <uv-radio-group
                  v-model="item.mineAnswer"
                  v-if="exercisesIndex === index && item.topicType === '1'">
                  <uv-cell-group>
                    <uv-cell
                      v-for="(childItem, childIndex) in item.questionDirectoryOptionList"
                      :key="`${index}${childIndex}`"
                      :title="`${childItem.directoryOption}：${childItem.optionContent}（${childItem.optionScore}分）`"
                      >
                      <template #right-icon>
                        <uv-radio :name="childItem.directoryOption" @change="singleCorrectAnswer(index,childIndex)"/>
                      </template>
                    </uv-cell>
                  </uv-cell-group>
                </uv-radio-group>
                
                <!-- 多选题 -->
                <uv-checkbox-group
                  v-model="item.mineAnswerSub"
                  v-if="exercisesIndex === index && item.topicType === '2'"
                  @change="doubleCorrectAnswer">
                  <uv-cell-group>
                    <uv-cell
                      v-for="(childItem, childIndex) in item.questionDirectoryOptionList"
                      :key="`${index}${childIndex}`"
                      :title="`${childItem.directoryOption}：${childItem.optionContent}（${childItem.optionScore}分）`"
                      @click="toggle(index, childIndex)">
                      <template #right-icon>
                        <uv-checkbox
                          :name="childItem.directoryOption"
                          :ref="el => { if (el) checkboxRefs[`checkboxRefs${index}${childIndex}`] = [el] }"
                          @click.stop
                        />
                      </template>
                    </uv-cell>
                  </uv-cell-group>
                </uv-checkbox-group>
                
                <!-- 判断题 -->
                <uv-radio-group
                  v-model="item.mineAnswer"
                  v-if="exercisesIndex === index && item.topicType === '3'">
                  <uv-cell-group>
                    <uv-cell
                      v-for="(dict, childIndex) in judge_option"
                      :key="dict.value"
                      :title="`${childIndex + 1}. ${dict.label}（${item.questionDirectoryOptionList[childIndex].optionScore}分）`"
                     >
                      <template #right-icon>
                        <uv-radio :name="dict.value"  @change="judgeCorrectAnswer(index,childIndex)"/>
                      </template>
                    </uv-cell>
                  </uv-cell-group>
                </uv-radio-group>
                
                <!-- 简答题 -->
                <uv-cell-group v-if="exercisesIndex === index && item.topicType === '4'">
                  <uv-textarea
                    v-model="item.mineAnswer"
                    placeholder="请输入答案"
                    count
                    maxlength="300"
                    @change="changejianDa"
                  />
                </uv-cell-group>
              </uv-cell-group>
            </block>
          </uv-cell-group>
        </uv-form>
      </div>
    </div>


    <div class="bottom-option">
      <uv-button
      v-if="!isRead"
      class="button-submit float-bottom"
      type="primary"
      :loading="loading"
      @click="onClickStart">开始答题</uv-button>
      <div
        v-if="isRead && exercisesIndex <= form.questionDirectoryList.length - 1"
        class="button-submit float-bottom"
        style="background: transparent;box-shadow: none;display: flex;">
        <div style="flex: 1;margin-right: 20rpx;" v-if="isRead && (exercisesIndex <= form.questionDirectoryList.length -1) && exercisesIndex > 0">
          <uv-button
        
          class="button-submit"
          style="flex: 1;"
          type="primary"
          :loading="loading"
          @click="exercisesIndex--">上一题</uv-button>
        </div>
        <div style="flex: 1;"  v-if="isRead && exercisesIndex < form.questionDirectoryList.length - 1">
          <uv-button
        
          class="button-submit"
          style="flex: 1;"
          type="primary"
          :loading="loading"
          @click="handlePreView">下一题</uv-button>
        </div>
        <div style="flex: 1;" v-if="isRead && exercisesIndex === form.questionDirectoryList.length - 1">
          <uv-button
        
          class="button-submit"
          style="flex: 1;"
          type="primary"
          :loading="loading"
          @click="onSubmit">提交</uv-button>
        </div>

      
      
        
      </div>
    </div>

    
    <uv-modal
      ref="modalRef"
      title="提示"
      show-cancel-button
      @confirm="confirmSubmit">
      <div class="is-sure">是否确认提交？</div>
    </uv-modal>
  </div>
</template>

<style lang="less" scoped>

.tigan {
  padding: 24rpx;
  position: relative;
  
  .leixing {
    position: absolute;
    top: 24rpx;
    left: 24rpx;
    width: 84rpx;
    height: 40rpx;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26rpx;
  }
  
  .question-single {
    background: rgba(255, 141, 1, 0.1);
    border: 1rpx solid rgba(255, 141, 26, 0.35);
    color: rgba(255, 141, 26, 1);
  }
  
  .question-double {
    background: rgba(42, 130, 228, 0.09);
    border: 1rpx solid rgba(42, 130, 228, 0.3);
    color: rgba(42, 130, 228, 1);
  }
  
  .question-panduan {
    background: rgba(255, 87, 51, 0.12);
    border: 1rpx solid rgba(255, 87, 51, 0.36);
    color: rgba(255, 87, 51, 1);
  }
  
  .question-jianda {
    background: rgba(121, 166, 23, 0.12);
    border: 1rpx solid rgba(121, 166, 23, 0.38);
    color: rgba(121, 166, 23, 1);
  }
  
  .neirong {
    text-indent: 92rpx;
    font-size: 30rpx;
    color: rgba(37, 37, 37, 1);
    line-height: 50rpx;
  }
}

.option-btn-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 24rpx;
  padding-bottom: 60rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(221, 237, 253, 0.54);
  box-sizing: border-box;
  .uv-button {
    margin-left: 24rpx;
    flex: 1;
    
    &:first-child {
      margin-left: 0;
    }
  }
}

.flex-container {
  display: flex;
}

.is-sure {
  display: flex;
  justify-content: center;
  padding: 40rpx 0;
}
.bottom-option {
  position: fixed;
  bottom: 100rpx;
  left: 0;
  width: 100%;
  padding: 0 24rpx;
  box-sizing: border-box;
}
</style>
