<!-- eslint-disable unicorn/prefer-ternary -->
<script setup lang="ts">
import { questionResourceService } from '#/api/service/question-bank/question-resource'
import { router } from '#/router'
import hud from '#/utils/hud'
import num from '#/utils/num'

const route = useRoute()
const { id, fileId } = route.query
const files = ref([] as any)
const fileIdx = ref(undefined as any)
const expectedTotalNum = ref(0)

const wrapperRef = ref()
const questionListRef = ref()
const wrapperHeight = computed(() => {
  return wrapperRef.value?.offsetHeight
    ? `${wrapperRef.value?.offsetHeight}px !important`
    : '100%'
})

// 滚动到指定序号的题目
function scrollToQuestion(index: number) {
  if (!questionListRef.value) return

  const itemBoxes = questionListRef.value.querySelectorAll('.item-box')
  const targetItem = itemBoxes[index - 1] // index从1开始，数组从0开始

  if (targetItem) {
    targetItem.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    })
  }
}

function getOptionLabel(item: any, idx: any) {
  return `【文件${idx + 1}】【${item.typeName}】入库：${item.generateNum || 0}，解析：${item.analysisNum}，期望：${item.totalNum}`
}

// 当前选中的文件
const curFile = computed(() => {
  return files.value[fileIdx.value] || {}
})

// 当前有错误的题目序号
const errorQuestionIndexes = computed(() => {
  if (!curFile.value?.jsonData) return []
  const arr = []
  for (let i = 0; i < curFile.value.jsonData.length; i++) {
    const question = curFile.value.jsonData[i]
    if (question.error) {
      arr.push(i + 1)
    }
  }
  return arr
})

watch(
  () => curFile.value,
  async () => {
    expectedTotalNum.value = curFile.value.totalNum
  },
)

function reload(success: any = undefined) {
  hud.load({
    task: async () => {
      const data = await questionResourceService.listFiles(id)
      files.value = data.rows

      success && success()
    },
    option: '加载',
  })
}

onMounted(async () => {
  reload(() => {
    if (fileId) {
      fileIdx.value = files.value.findIndex((item: any) => item.id === fileId)
    } else {
      fileIdx.value = 0
    }
  })
})

const uploadFiles = ref([] as any)
function updateFile() {
  if (!num.isPositiveInt(expectedTotalNum.value)) {
    hud.error('请输入正确的题目数量')
    return
  }
  if (
    !uploadFiles.value?.length &&
    Number(curFile.value.totalNum) === Number(expectedTotalNum.value)
  ) {
    hud.error('题目数量没有变化')
    return
  }
  hud.load({
    task: async () => {
      if (uploadFiles.value?.length) {
        await questionResourceService.updateFile(
          curFile.value.id,
          expectedTotalNum.value,
          uploadFiles.value[0].raw,
        )
      } else {
        await questionResourceService.updateTotalNum(
          curFile.value.id,
          expectedTotalNum.value,
        )
      }

      // 刷新
      reload()
    },
    option: '更新',
    hideSuccess: false,
  })
}

function showQuestions() {
  router.push({
    path: '/question-bank/question-mgr',
    query: {
      fileId: files.value[fileIdx.value].id,
    },
  })
}

function downloadOriginFile() {
  open(curFile.value.fileUrl)
}

const suggestVisible = ref(false)
function showSuggest() {
  suggestVisible.value = true
}
</script>

<template>
  <div class="question-resource-detail">
    <question-suggest v-model="suggestVisible" />
    <div v-if="curFile" class="header">
      <div class="row">
        <div class="left">
          <el-select class="select" v-model="fileIdx" placeholder="请选择文件">
            <el-option
              v-for="(item, idx) in files"
              :key="item.id"
              :label="getOptionLabel(item, idx)"
              :value="idx"
            >
              <span :class="{ 'error-option': item.errorMsg }">{{
                getOptionLabel(item, idx)
              }}</span>
            </el-option>
          </el-select>
          <a
            class="link"
            target="__blank"
            v-if="curFile.fileUrl"
            :href="curFile.fileUrl"
          >
            下载源文档
          </a>
          <!-- <el-button type="primary" @click="showQuestions">
            题目列表
          </el-button> -->
          <span class="error-msg">{{ curFile.errorMsg }}</span>
        </div>
      </div>
      <div class="row">
        <div class="left">
          <span>期望题目数量：</span>
          <el-input class="total-num" v-model="expectedTotalNum" />
          <el-upload
            class="select-button"
            v-model:file-list="uploadFiles"
            name="file"
            :limit="1"
            :auto-upload="false"
          >
            <el-button type="primary"> 选择新的文档 </el-button>
          </el-upload>
          <el-button type="success" @click="updateFile"> 更新 </el-button>
        </div>
        <div class="right">
          <div v-if="errorQuestionIndexes?.length" class="error-index-list">
            <span>错题序号(可点击)：</span>
            <span
              class="error-index"
              v-for="item in errorQuestionIndexes"
              :key="item"
              @click="scrollToQuestion(item)"
            >
              {{ item }}
            </span>
          </div>
        </div>
      </div>
    </div>
    <div
      class="question-list-wrapper"
      ref="wrapperRef"
      :style="{
        height: wrapperHeight,
      }"
    >
      <div
        class="question-list"
        ref="questionListRef"
        :style="{
          height: wrapperHeight,
        }"
      >
        <div
          class="item-box"
          v-for="(item, idx) in curFile.jsonData"
          :key="idx"
        >
          <question-item
            :index="idx + 1"
            :question="item as any"
            @suggest="showSuggest"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.el-select-dropdown__item {
  .error-option {
    color: red !important;
  }
}
</style>

<style lang="scss" scoped>
.question-resource-detail {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
  padding: 16px;

  .header {
    font-size: 16px;
    background-color: #fff;
    border-radius: 4px;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 16px;

    .link {
      text-decoration: underline;
      color: blue;
    }

    .row {
      display: flex;
      align-items: center;
      gap: 40px;
      justify-content: space-between;

      .left {
        display: flex;
        align-items: center;
        gap: 20px;
      }

      .right {
        display: flex;
        align-items: center;
        gap: 20px;
        flex: 1;
      }
    }

    .error-index-list {
      display: flex;
      align-items: center;
      gap: 12px;
      flex-wrap: wrap;

      .error-index {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background-color: $error-color;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
      }
    }

    .select {
      width: 400px;
    }

    .error-msg {
      color: red;
      font-size: 18px;
      flex: 1;
    }

    .select-button {
      display: flex;
      align-items: center;
    }

    .total-num {
      width: 60px;

      :deep(.el-input__inner) {
        text-align: center;
      }
    }
  }

  .question-list-wrapper {
    flex: 1;
    height: 100%;
    overflow: hidden;
  }

  .question-list {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    gap: 20px;
    overflow: auto;
  }
}
</style>
