<!-- eslint-disable vue/no-mutating-props -->
<script setup lang="ts">
import type { Question } from '.'

import { useUserStore } from '@vben/stores'

import { View } from '@element-plus/icons-vue'

import {
  difficulty_map,
  questionService,
  status_approving,
  status_draft,
  status_map,
  status_rejected,
  status_reviewed,
  status_reviewing,
} from '#/api/service/question-bank/question'
import { router } from '#/router'
import hud from '#/utils/hud'

defineOptions({ name: 'QuestionItem' })

const props = defineProps<{
  index?: any
  question: Question
}>()

const emits = defineEmits(['refresh', 'suggest'])
const { userInfo } = storeToRefs(useUserStore())

// 查看
function view() {
  router.push({
    path: '/question-bank/question-add',
    query: {
      id: props.question.id,
    },
  })
}

// 进入下一步的状态
function next() {
  hud.confirmLoad(`确定要${nextButtonText.value}么？`, {
    task: async () => {
      await questionService.updateStatus(props.question.id, nextStatus.value)
      props.question.status = nextStatus.value || props.question.status
      emits('refresh')
    },
    option: '操作',
  })
}

// 进入拒绝的状态
function rejected() {
  hud.confirmLoad(`确定要拒绝么？`, {
    task: async () => {
      await questionService.updateStatus(props.question.id, status_rejected)
      props.question.status = status_rejected
      emits('refresh')
    },
    option: '操作',
  })
}

// 选项是否要水平显示
const optionsHorizontal = computed(() => {
  if (!props.question.options?.length) return false
  return willOptionsHorizontal(props.question.options)
})

function willOptionsHorizontal(options: any) {
  if (!options?.length) return false
  let maxOptionLen = 0
  for (const option of options) {
    if (!option.value) return true
    maxOptionLen = Math.max(maxOptionLen, option.value.length)
  }
  return maxOptionLen < 10
}

// 是否为完形填空
const isWanXing = computed(() => {
  if (!props.question.options?.length) return false
  for (const option of props.question.options) {
    if (option.options && !option.stem) return true
  }
  return false
})

// 是否为阅读理解
const isYueDu = computed(() => {
  if (!props.question.options?.length) return false
  for (const option of props.question.options) {
    if (option.options && option.stem) return true
  }
  return false
})

const nextStatus = computed(() => {
  if (questionService.isReadonly(props.question, userInfo.value.id)) {
    return undefined
  }
  if (props.question.status === status_reviewing) {
    return status_reviewed
  }
  if (props.question.status === status_approving) {
    return status_reviewing
  }
  if (props.question.status === status_draft) {
    return status_approving
  }
  return undefined
})

const nextButtonText = computed(() => {
  if (nextStatus.value === status_reviewed) {
    return '复核通过'
  }
  if (nextStatus.value === status_reviewing) {
    return '审核通过'
  }
  if (nextStatus.value === status_approving) {
    return '提交审核'
  }
  return ''
})

// 显示拒绝按钮
const showRejected = computed(() => {
  return (
    nextStatus.value === status_reviewed ||
    nextStatus.value === status_reviewing
  )
})

const tagType = computed(() => {
  const status = props.question.status
  if (status === status_approving || status === status_reviewing) {
    return 'warning'
  }
  if (status === status_rejected) {
    return 'danger'
  }
  if (status === status_draft) {
    return 'primary'
  }
  if (status === status_reviewed) {
    return 'success'
  }
  return undefined
})

function canShowRemove() {
  return false
  // 如果是题目的创建者，且还没有复审通过，都可以删除

  // if (props.question.status === status_reviewed) {
  //   // 如果是审核通过的题目，只有复审人员可以删除
  //   return props.question.reviewerId === userInfo.value.id
  // } else {
  //   return props.question.creatorId === userInfo.value.id
  // }
}

// 删除题目
function remove() {
  hud.confirmLoad('确定要删除这道题目么？', {
    task: async () => {},
    option: '删除',
  })
}

// 查看文档
function viewDoc() {
  router.push({
    path: '/question-bank/question-resource-detail',
    query: {
      id: props.question.resourceId,
      fileId: props.question.fileId,
    },
  })
}

// 查看建议
function showSuggest() {
  emits('suggest')
}
</script>

<template>
  <div
    class="question-item"
    :class="{
      error: question.error,
    }"
  >
    <div class="header">
      <span class="index">
        <span>{{ index }}</span>
      </span>
      <div class="content">
        <div class="left">
          <template v-if="question.configJson?.textbookTitle">
            <span class="book-chapter">{{
              question.configJson.textbookTitle
            }}</span>
            <span class="divider">|</span>
          </template>
          <template v-if="question.typeName">
            <span class="type">{{ question.typeName }}</span>
            <span class="divider">|</span>
          </template>
          <template v-if="question.difficulty">
            <span class="difficulty">{{
              difficulty_map[question.difficulty]
            }}</span>
            <span class="divider">|</span>
          </template>
          <template v-if="question.hard">
            <span class="difficulty">{{ question.hard }}</span>
            <span class="divider">|</span>
          </template>
          <template v-if="question.year">
            <span class="year">{{ question.year }}</span>
            <span class="divider">|</span>
          </template>
          <template v-if="question.chapterNames">
            <span class="chaper-names">{{ question.chapterNames }}</span>
          </template>
        </div>
        <div class="right"></div>
      </div>
    </div>
    <div v-if="question.creator" class="header operations">
      <div class="content">
        <div class="left">
          <el-button v-if="question.fileId" @click="viewDoc" :icon="View"
            >文档</el-button
          >
          <el-button @click="view" :icon="View"> 查看 </el-button>
          <el-button v-if="nextButtonText" :type="tagType" @click="next">
            {{ nextButtonText }}
          </el-button>
          <el-button v-if="showRejected" type="danger" @click="rejected"
            >拒绝</el-button
          >
          <el-button v-if="canShowRemove()" type="danger" @click="remove">
            删除
          </el-button>
          <el-tag :type="tagType">
            {{ status_map[question.status] }}
          </el-tag>
          <span v-if="question.creator">创建人：{{ question.creator }}</span>
          <span v-if="question.approver">审批人：{{ question.approver }}</span>
          <span v-if="question.reviewer">复核人：{{ question.reviewer }}</span>
        </div>
        <div class="right"></div>
      </div>
    </div>
    <div class="middle">
      <div v-if="question.error" class="error">
        {{ question.error }}
        <el-button type="primary" @click="showSuggest">查看建议</el-button>
      </div>
      <blockquote v-if="question.error" class="data">
        <latex-text :text="question.data" />
      </blockquote>
      <div v-if="question.stem" class="stem">
        <latex-text :text="question.stem" />
      </div>
      <template v-if="question.options">
        <div v-if="isYueDu" class="options yuedu">
          <div
            class="option"
            v-for="(item, index) in question.options"
            :key="index"
          >
            <div class="index-stem">
              <span class="index">{{ index + 1 }}</span>
              <latex-text :text="item.stem" />
            </div>
            <div
              class="sub-options"
              :class="{
                vertical: !willOptionsHorizontal(item.options),
              }"
            >
              <span
                class="sub-option"
                v-for="(subItem, subIndex) in item.options"
                :key="subIndex"
              >
                <span>{{ subItem.label }}.</span>
                <latex-text :text="subItem.value" />
              </span>
            </div>
          </div>
        </div>
        <div v-else-if="isWanXing" class="options">
          <div
            class="option"
            v-for="(item, index) in question.options"
            :key="index"
          >
            <span class="index">{{ index + 1 }}</span>
            <div class="sub-options">
              <span
                class="sub-option"
                v-for="(subItem, subIndex) in item.options"
                :key="subIndex"
              >
                <span>{{ subItem.label }}.</span>
                <span>{{ subItem.value }}</span>
              </span>
            </div>
          </div>
        </div>
        <div
          v-else
          class="options"
          :class="{
            horizontal: optionsHorizontal,
          }"
        >
          <div
            class="option"
            v-for="(item, index) in question.options"
            :key="index"
          >
            <span>{{ item.label }}.</span>
            <latex-text :text="item.value" />
          </div>
        </div>
      </template>
      <div v-if="question.exam" class="exam item-section">
        <span class="item-title">【考点】</span>
        <span class="item-content">
          <latex-text :text="question.exam" />
        </span>
      </div>
      <div v-if="question.answer" class="answer item-section">
        <span class="item-title">【答案】</span>
        <span class="item-content">
          <div v-if="question.answer" class="answer-list">
            <div
              v-for="(item, index) in question.answer"
              :key="index"
              class="answer-list-item"
            >
              <template v-if="!Array.isArray(item)">
                <span v-if="question.answer.length > 1" class="answer-index">{{
                  index + 1
                }}</span>
                <latex-text :text="item" />
              </template>
              <template v-else>
                <template v-for="(subItem, j) in item" :key="j">
                  <span class="answer-index">{{ index + 1 }}.{{ j + 1 }}</span>
                  <latex-text :text="subItem" />
                </template>
              </template>
            </div>
          </div>
        </span>
      </div>
      <div v-if="question.analysis" class="analysis item-section">
        <span class="item-title">【分析】</span>
        <span class="item-content">
          <latex-text :text="question.analysis" />
        </span>
      </div>
      <div v-if="question.solve" class="solve item-section">
        <span class="item-title">【解答】</span>
        <span class="item-content">
          <latex-text :text="question.solve" />
        </span>
      </div>
      <div v-if="question.comment" class="comment item-section">
        <span class="item-title">【点评】</span>
        <span class="item-content">
          <latex-text :text="question.comment" />
        </span>
      </div>
      <div v-if="question.knowledge" class="knowledge item-section">
        <span class="item-title">【知识点】</span>
        <span class="item-content">
          <latex-text :text="question.knowledge" />
        </span>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.question-item {
  u {
    display: inline-block;
    justify-content: center;
    min-width: 20px;
    padding: 0 16px;
    margin: 0 10px;
    text-indent: 0;
    text-decoration: none;
    border-bottom: 1px solid #00f;
  }

  span[data-w-e-type='formula']::before {
    color: red;
    content: '[公式]';
  }

  .stem {
    p + u {
      margin-left: 2em;
    }

    p {
      text-indent: 2em;
    }
  }

  table {
    margin-top: 6px;
    td,
    th {
      border: 1px solid #333;
      padding: 6px;
    }
  }
}
</style>

<style lang="scss" scoped>
$fz: 16px;
$padding: 16px;
@mixin index {
  min-width: 24px;
  height: 24px;
  padding: 0 4px;
  line-height: 24px;
  color: #246cff;
  text-align: center;
  background-color: #f4f9ff;
  border-radius: 4px;
}

.question-item {
  min-height: 100px;
  font-size: $fz;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 0 12px rgb(0 0 0 / 12%);
  overflow: hidden;

  &.error {
    .header {
      .index {
        background-color: $error-color;
      }
    }

    .error {
      color: $error-color;
    }

    .data {
      border: 1px solid #333;
    }
  }

  $header_h: 48px;

  .content {
    flex: 1;
    display: flex;
    height: $header_h;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
  }

  .header {
    display: flex;
    height: $header_h;
    align-items: center;
    border-bottom: 1px solid #ececec;

    &.operations {
      height: $header_h + 5px;
    }

    .index {
      width: 60px;
      height: $header_h - 1px;
      background-color: #246cff;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
    }

    .chaper-names {
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .divider {
      padding: 0 16px;
      color: #ececec;
    }
    .chaper-names,
    .year,
    .type,
    .difficulty,
    .book-chapter {
      color: #666;
    }

    .knowledge {
      color: #999;
    }
  }

  .middle {
    display: flex;
    flex-direction: column;
    gap: $padding;
    padding: 10px 20px;

    :deep(.latex-text) {
      font-size: $fz;
    }

    .options {
      display: flex;
      flex-direction: column;
      padding: 0 16px;
      gap: 16px;

      &.horizontal {
        flex-direction: row;

        .option {
          flex: 1;
        }
      }

      &.yuedu {
        .option {
          flex-direction: column;
        }
        .index-stem {
          display: flex;
          gap: 10px;
        }
      }

      .option {
        display: flex;
        gap: 10px;

        .index {
          @include index;
        }

        .sub-options {
          display: flex;
          gap: 20px;

          &.vertical {
            flex-direction: column;

            .sub-option {
              width: 100%;
            }
          }

          .sub-option {
            width: 180px;
            display: flex;
            gap: 10px;
            padding-left: 2em;
          }
        }
      }
    }

    .item-section {
      display: flex;
      align-items: flex-start;
      padding-top: 16px;
      border-top: 1px dashed #dcdcdc;

      .item-title {
        width: 86px;
        color: #246cff;
      }

      .item-content {
        flex: 1;
      }
    }

    .data {
      padding: 16px;
    }
  }

  .answer-list {
    display: flex;
    gap: $padding;
    align-items: center;
    flex-wrap: wrap;

    .answer-list-item {
      display: flex;
      gap: 8px;
      align-items: center;

      .sub-answers {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .answer-index {
        @include index;
      }
    }
  }

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

  .right {
    display: flex;
    gap: $padding;
    align-items: center;
  }

  .el-button + .el-button {
    margin-left: 0;
  }
}
</style>
