<script setup lang='ts'>
import QuestionMap, { QuestionKeyList, updateQuestionMap } from './componsables/xgstda/store/question'
import AreaList from './componsables/xgstda/store/area'

import request from '~/utils/request'

const props = defineProps<{
  disabled: boolean
}>()

const _ykl_lc_ = JSON.parse(sessionStorage.getItem('ykl_lc')!)

let dialogVisible = $ref(false)

let lastData: any

async function handleClickLink() {
  if (props.disabled)
    return

  request({
    url: `${window.GLOBAL_CONFIG.yzy}/yzy/kmksyjlc/format`,
    data: {
      api: 'json',
      client: 'web',
      ze_id: _ykl_lc_.ze_id,
    },
  }).then((res) => {
    if (res.code === '1') {
      lastData = res.data.format
      const info = res.data?.format?.info
      if (info !== undefined) {
        AreaList.value = info.area ?? []
        updateQuestionMap()
        dialogVisible = true
      }
    }
    else {
      ElMessage({
        message: res.msg,
        type: 'error',
        grouping: true,
      })
    }
  }).catch(() => {
    ElMessage({
      message: '操作失败',
      type: 'error',
      grouping: true,
    })
  })
}

// const checkList = ref({})

function handleInput(v: string, _name: string) {
  const value = v.substr(-1).toLocaleUpperCase()
  const idx = value.charCodeAt(0) - 64
  if (idx <= QuestionMap.value[_name].options && idx > 0) {
    QuestionMap.value[_name].answerstr = value
    QuestionMap.value[_name].answer = idx
  }
}

function handleInputMulti(v: string, _name: string) {
  const values = [...new Set(v.toLocaleUpperCase().split('').map(n => n.trim()).sort())]
  const idxs = values.map(value => value.charCodeAt(0) - 64).filter(idx => idx <= QuestionMap.value[_name].options && idx > 0)

  QuestionMap.value[_name].answerstr = idxs.map(idx => String.fromCharCode(idx + 64)).join('')
  QuestionMap.value[_name].answer = idxs
}

function handleInputJudge(v: string, _name: string) {
  const value = v.substr(-1).toLocaleUpperCase()
  const idx = value.charCodeAt(0) - 64
  // F
  if (idx === 6) {
    QuestionMap.value[_name].answerstr = 'F'
    QuestionMap.value[_name].answer = 2
  }
  // T
  if (idx === 20) {
    QuestionMap.value[_name].answerstr = 'T'
    QuestionMap.value[_name].answer = 1
  }
}

const strMap: any = {}
const formatAnswer = {
  num2opt(num: number) {
    if (strMap[num] === undefined) {
      const value = String.fromCharCode(65 + num - 1)
      strMap[num] = value
    }
    return strMap[num]
  },

  num2pdopt(num: number) {
    return ['T', 'F'][num - 1]
  },

  blank2ans(arr: unknown[]) {
    return arr.join('※')
  },

  multi2ans(arr: number[]) {
    return arr
      .sort()
      .map(n => formatAnswer.num2opt(n))
      .sort()
      .join('')
  },

  judgeAnsByType(ans: any, type: number) {
    if (type === 1)
      return formatAnswer.num2opt(ans)
    if (type === 2)
      return formatAnswer.multi2ans(ans)
    if (type === 3)
      return formatAnswer.num2pdopt(ans)
    if (type === 4)
      return formatAnswer.blank2ans(ans)
    if (type === 5)
      return ans
  },

  judgeOptByType(ans: number, type: number) {
    if (type === 1)
      return formatAnswer.num2opt(ans)
    if (type === 2)
      return formatAnswer.num2opt(ans)
    if (type === 3)
      return formatAnswer.num2pdopt(ans)
  },
}

const submitLoading = ref(false)
function handleSubmit() {
  submitLoading.value = true
  const newData = {
    ...lastData,
    info: {
      ...lastData.info,
      area: AreaList.value,
    },
  }

  newData?.pages?.forEach((page: any) => {
    page?.questions?.forEach((question: any) => {
      question.answer = formatAnswer.judgeAnsByType(QuestionMap.value[question.name].answer, QuestionMap.value[question.name]._type)
    })
  })
  request({
    url: `${window.GLOBAL_CONFIG.yzy}/yzy/kmksyjlc/save`,
    data: {
      version: 1,
      ykl_id: _ykl_lc_.ykl_id,
      yk: {
        ykl_dtkmb: JSON.stringify(newData),
      },
    },
  }).then((res) => {
    if (res.code === '1') {
      request({
        url: `${window.GLOBAL_CONFIG.yzy}/yzy/kmksyjlc/recheck_answer`,
        data: {
          ze_id: _ykl_lc_.ze_id,
        },
      }).then(
        (res2) => {
          if (res2.code === '1') {
            ElMessage({
              message: '操作成功',
              type: 'success',
              grouping: true,
            })
            submitLoading.value = false
            dialogVisible = false
          }
          else {
            ElMessage({
              message: res2.msg,
              type: 'error',
              grouping: true,
            })
          }
        },
      )
    }
    else {
      ElMessage({
        message: res.msg,
        type: 'error',
        grouping: true,
      })
    }
  }).catch(() => {
    ElMessage({
      message: '操作失败',
      type: 'error',
      grouping: true,
    })
  })
}

function handleBeforeClose(done: () => void) {
  if (submitLoading.value) {
    ElMessage({
      message: '正在提交，请稍后',
      type: 'warning',
      grouping: true,
    })
    // done()
  }
  else {
    done()
  }
}
</script>

<template>
  <el-link type="primary" :disabled="disabled" @click="handleClickLink">
    修改试题答案
  </el-link>
  <el-dialog v-model="dialogVisible" title="修改试题答案" width="855px" :before-close="handleBeforeClose">
    <div>
      <div v-for="(_name, idq) in QuestionKeyList" :key="idq">
        <div class="q_row">
          <!-- <el-checkbox v-model="checkList[_name]"> -->
          <div class="q_id">
            {{ _name }}.
          </div>
          <!-- </el-checkbox> -->
          <template v-if="QuestionMap[_name]._type === 1">
            <el-input
              :model-value="QuestionMap[_name].answerstr" placeholder="输入答案或使用选择器"
              style="width:160px;margin-right: 20px;" @input="handleInput($event, _name)"
            />
            <div class="q_options">
              <el-radio
                v-for="option in QuestionMap[_name].options" :key="option" v-model="QuestionMap[_name].answer"
                :label="option" border
              >
                {{
                  String.fromCharCode(65
                    + option - 1)
                }}
              </el-radio>
            </div>
          </template>
          <template v-if="QuestionMap[_name]._type === 2">
            <el-input
              :model-value="QuestionMap[_name].answerstr" placeholder="输入答案或使用选择器"
              style="width:160px;margin-right: 20px;" @input="handleInputMulti($event, _name)"
            />
            <div class="q_options">
              <el-checkbox-group v-model="QuestionMap[_name].answer">
                <el-checkbox v-for="option in QuestionMap[_name].options" :key="option" :label="option" border>
                  {{
                    String.fromCharCode(65
                      + option - 1)
                  }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </template>
          <template v-if="QuestionMap[_name]._type === 3">
            <el-input
              :model-value="QuestionMap[_name].answerstr" placeholder="输入答案或使用选择器"
              style="width:160px;margin-right: 20px;" @input="handleInputJudge($event, _name)"
            />
            <div class="q_options">
              <el-radio
                v-for="option in QuestionMap[_name].options" :key="option" v-model="QuestionMap[_name].answer"
                :label="option" border
              >
                {{ ['T', 'F'][option - 1] }}
              </el-radio>
            </div>
          </template>
          <template v-if="QuestionMap[_name]._type === 4">
            <div class="q_options tk">
              <el-input
                v-for="option in QuestionMap[_name].options" :key="option"
                v-model="QuestionMap[_name].answer[option - 1]" class="tk_input" :placeholder="`第${option}空`"
              >
                {{ option }}
              </el-input>
            </div>
            <div class="q_num">
              <span>填空数：</span>
              <el-input-number v-model="QuestionMap[_name].options" :min="0" :precision="0" />
            </div>
          </template>
          <template v-if="QuestionMap[_name]._type === 5">
            <div class="q_options q_text">
              <!-- <el-input type="textarea" v-model="QuestionMap[_name].answer"></el-input> -->
              <tinymce-vue v-model="QuestionMap[_name].answer" />
            </div>
          </template>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="flex justify-center">
        <el-button type="primary" size="large" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.q_row {
  display: flex;
  // height: 42px;
  padding: 4px 0;
  justify-content: start;
  align-items: center;

  .q_id {
    flex: none;
    font-size: 20px;
    font-weight: bold;
    margin-right: 10px;
    height: 42px;
    line-height: 42px;
    width: 40px;
    text-align: right;
  }

  .q_text {
    padding-right: 20px;

  }

  .q_options {
    flex: auto;

    // overflow: hidden;
    &.tk {
      display: flex;
      justify-content: start;
      align-items: center;

      .tk_input {
        flex: auto;
        max-width: 200px;
        margin-right: 10px;
      }
    }
  }

  .q_num {
    flex: none;
    padding-right: 20px;
  }

  .q_handle {
    flex: none;
  }
}
</style>
