<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { startExamination, submitAnswers } from '@/api/train/exam'
import { useDict } from '@/common/utils/dict'
import { getCompanyName } from '@/common/utils/transcoding'
import { parseTime, selectDictLabel } from '@/common/utils/ruoyi'
const { examination_type, markpape_type, yes_no, topic_type, single_option, judge_option } = useDict(
  'examination_type', 'markpape_type', 'yes_no', 'topic_type', 'single_option', 'judge_option'
)

const { proxy }: any = getCurrentInstance()
const leaveTypeName = ref('')
const show = reactive({ leaveType: false })

const data = reactive({
  form: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    belongCompany: null,
    examinationName: null,
    examinationType: null,
    examinationTotal: null,
    examinationDuration: null,
    examinationFullScore: null,
    examinationPassScore: null,
    examinationStartTime: null,
    examinationEndTime: null,
    isExamination: '1',
    isPlan: '1',
    planId: null,
    planName: null,
    markPapeType: '1',
    markPapePeople: null,
    isRandom: '1',
    questionBankId: null,
    questionBankName: null,
    tenantId: null,
    companyId: null,
    deptId: null,
    cardList: [
      { topicType: '1', topicRatio: null, topicTotal: null },
      { topicType: '2', topicRatio: null, topicTotal: null },
      { topicType: '3', topicRatio: null, topicTotal: null },
      { topicType: '4', topicRatio: null, topicTotal: null }
    ],
    questionDirectoryList: [],
    repairExamination: null
  }
})

const { form }:any = toRefs(data)
const loading = ref(false)
const isRead = ref(false)
const planShow = ref(false)
const markPapeShow = ref(false)
const exercisesIndex = ref(0)
const dialogShow = ref(false)
const checkboxRefs = ref([])

onLoad((options) => {
  if (options.mainId) {
    getInfo(options.mainId, options.repairExamination)
  }
})

function getInfo(mainId, repairExamination) {
  startExamination(mainId, repairExamination).then(response => {
    form.value = response.data
    form.value.repairExamination = repairExamination
    form.value.questionDirectoryList.forEach((element:any) => {
      if (element.mineAnswer === null) {
        element.mineAnswerSub = []
      }
    })
    
    planShow.value = form.value.isPlan === '1'
    markPapeShow.value = form.value.markPapeType !== '1'
  })
}

function onClickStart() {
  isRead.value = true
}

function singleCorrectAnswer(index, childIndex) {
  console.log(index, childIndex)
  form.value.questionDirectoryList[index].mineAnswerName = 
    form.value.questionDirectoryList[index].questionDirectoryOptionList[childIndex].directoryOption
}

function doubleCorrectAnswer() {
  const current:any = form.value.questionDirectoryList[exercisesIndex.value]
  current.mineAnswer = current.mineAnswerSub.join(',')
  current.mineAnswerName = current.mineAnswerSub.join(',')
}

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

function judgeCorrectAnswer(index, childIndex) {




  form.value.questionDirectoryList[index].mineAnswerName = judge_option.value[childIndex].label
}

function handlePreView() {
  const current:any = form.value.questionDirectoryList[exercisesIndex.value]
  console.log(1)
  if (current.topicType === '4' && !current.mineAnswer) {
     console.log(2)
    uni.showToast({ title: '请输入答案', icon: 'none' })
    return
  }
  
  if (current.topicType === '4') {
    current.mineAnswerName = current.mineAnswer
  }
  if (current.topicType === '3') {
    current.mineAnswerName = current.mineAnswer
  }
  
  if (!current.mineAnswerName) {
     console.log(3)
    uni.showToast({ title: '请输入答案', icon: 'none' })
    return
  }
  
  exercisesIndex.value++
}

function changejianDa() {
  form.value.questionDirectoryList[exercisesIndex.value].mineAnswerName = 
    form.value.questionDirectoryList[exercisesIndex.value].mineAnswer
}

function onSubmit() {

  

  form.value.questionDirectoryList.forEach(element => {
    if (element.topicType === '3' && element.mineAnswer) {
      element.mineAnswerName = element.mineAnswer
    }
    if (element.topicType === '4' && element.mineAnswer) {
      element.mineAnswerName = element.mineAnswer
    }
    
    if (!element.mineAnswerName) {
      uni.showToast({ title: '请输入答案', icon: 'none' })
      console.log('element',element)
      throw new Error('答案不能为空')
    }
  })
  
  modalRef.value.open()
}
const modalRef:any = ref(null)
function confirmSubmit() {
  console.log('form.value',form.value)

  uni.showLoading({ title: '提交中...', mask: true })
  
  submitAnswers(form.value).then(() => {
    uni.hideLoading()
    uni.showToast({ title: '提交成功' })
    setTimeout(() => uni.navigateBack(), 1300)
  }).catch(() => {
    uni.hideLoading()
  })
}
</script>

<template>
  <view class="container">
    <view class="container__body">
      <view class="container__card">
        <view v-if="!isRead">
          <uv-cell title="所属公司" :value="getCompanyName(form.belongCompany)" />
          <uv-cell title="考试名称" :value="form.examinationName" />
          <uv-cell title="考试类型" :value="selectDictLabel(examination_type, form.examinationType)" />
          <uv-cell title="考试满分" :value="form.examinationFullScore" />
          <uv-cell title="及格分数" :value="form.examinationPassScore" />
          <uv-cell title="考试开始时间" :value="form.examinationStartTime" />
          <uv-cell title="考试结束时间" :value="form.examinationEndTime" />
          <uv-cell title="考试时长(分钟)" :value="form.examinationDuration" />
          <uv-cell title="是否关联计划" :value="selectDictLabel(yes_no, form.isPlan)" />
          <uv-cell v-if="planShow" title="计划名称" :value="form.planName" />
          <uv-cell title="是否随机选题" :value="selectDictLabel(yes_no, form.isRandom)" />
          <uv-cell title="是否可以补考" :value="selectDictLabel(yes_no, form.isExamination)" />
          <uv-cell title="阅卷类型" :value="selectDictLabel(markpape_type, form.markPapeType)" />
          <uv-cell v-if="markPapeShow" title="阅卷人" :value="form.markPapePeople" />
          <uv-cell title="题库名称" :value="form.questionBankName" />
        </view>

        <uv-form v-if="isRead" ref="formRef">
          <uv-cell-group>
            <view 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-cell-group>

              <!-- 单选题 -->
              <uv-radio-group 
                v-model="item.mineAnswer"
                v-if="exercisesIndex === index && item.topicType === '1'">
                <uv-cell
                  customStyle="width: 100%;"
                  v-for="(childItem,childIndex) in item.questionDirectoryOptionList"
                  :key="`${index}${childIndex}`"
                  :title="`${childItem.directoryOption}： ${childItem.optionContent}`"
                 >
                  <template #right-icon>
                    <uv-radio :name="childItem.directoryOption"  @change="singleCorrectAnswer(index,childIndex)"/>
                  </template>
                </uv-cell>
              </uv-radio-group>

              <!-- 多选题 -->
              <uv-checkbox-group
                v-model="item.mineAnswerSub"
                v-if="exercisesIndex === index && item.topicType==='2'"
                @change="doubleCorrectAnswer">
                <uv-cell
                  v-for="(childItem,childIndex) in item.questionDirectoryOptionList"
                  :key="`${index}${childIndex}`"
                  :title="`${childItem.directoryOption}： ${childItem.optionContent}`"
                  @click="toggle(index,childIndex)">
                  <template #right-icon>
                    <uv-checkbox :name="childItem.directoryOption" :ref="`checkboxRefs${index}${childIndex}`" />
                  </template>
                </uv-cell>
              </uv-checkbox-group>

              <!-- 判断题 -->
              <uv-radio-group 
                v-model="item.mineAnswer"
                v-if="exercisesIndex === index && item.topicType === '3'">
                <uv-cell
                  v-for="(dict,childIndex) in judge_option"
                  :key="dict.value"
                  :title="`${childIndex+1}. ${dict.label}`"
                  @click="judgeCorrectAnswer(index,childIndex)">
                  <template #right-icon>
                    <uv-radio :name="dict.value" />
                  </template>
                </uv-cell>
              </uv-radio-group>

              <!-- 简答题 -->
              <uv-cell-group v-if="exercisesIndex === index && item.topicType === '4'">
      
                <uv-textarea
                  v-model="item.mineAnswer"
                  placeholder="请输入答案"
                  count
                  maxlength="300"
                 
                />
              </uv-cell-group>
            </view>
          </uv-cell-group>
        </uv-form>
      </view>
    </view>

    <!-- 底部按钮 -->
    <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">
      <view class="is-sure">是否确认提交？</view>
    </uv-modal>
  </view>
</template>

<style lang="scss" 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>