<script setup lang="ts" name="stage-mgr">
import type { MjFormProps, MjGridProps } from '#/components/mj/mj-table'

import { useUserStore } from '@vben/stores'

import { questionResourceService } from '#/api/service/question-bank/question-resource'
import MjTable, { mj_form_select } from '#/components/mj/mj-table'
import { router } from '#/router'
import hud from '#/utils/hud'
import num from '#/utils/num'
import obj from '#/utils/obj'

// 解析状态
const status_ing = 0
const status_analysis = 1
const status_db = 2
const status_db_done = 3
const status_error = 4
const statusOptions = [
  {
    label: '解析中',
    value: status_ing,
  },
  {
    label: '已解析',
    value: status_analysis,
  },
  {
    label: '正在入库',
    value: status_db,
  },
  {
    label: '入库完成',
    value: status_db_done,
  },
  {
    label: '解析错误',
    value: status_error,
  },
]
const statusMap = obj.options2map(statusOptions)
// 用户
const { userInfo } = storeToRefs(useUserStore())

// 表格
const gridRef = ref()
const grid = {
  columns: [
    { type: 'seq' },
    {
      title: '教师',
      field: 'createUserName',
    },
    {
      title: '教材',
      field: 'name',
    },
    {
      title: '章节',
      field: 'chapterName',
    },
    {
      title: '试卷模板',
      field: 'paperTemplate',
      formatter({ cellValue }) {
        return cellValue === 1 ? '是' : '否'
      },
    },
    {
      field: 'status',
      title: '状态',
      formatter({ cellValue }) {
        return statusMap[cellValue]
      },
    },
    {
      title: '期望题数',
      field: 'totalNum',
    },
    {
      title: '解析题数',
      field: 'analysisNum',
    },
    {
      title: '入库进度',
      field: 'progress',
      formatter({ row }) {
        const num1 = row.generateNum || 0
        const num2 = row.totalNum || 0
        return `${num.toPercent(num1 / num2)}（${num1}/${num2}）`
      },
    },
    // {
    //   title: '完整度',
    //   field: 'displayScore',
    // },
    {
      title: '操作',
      fixed: 'right',
      slots: {
        default: 'operation',
      },
    },
  ],
  cellClassName({ row, column }: any) {
    // 解析题数
    if (column.field === 'status') {
      if (row.status === status_db_done) {
        return 'progress-100'
      }
      if (row.status === status_db) {
        return 'progress-80'
      }
      if (row.status === status_analysis) {
        return 'progress-60'
      }
      if (row.status === status_error) {
        return 'progress-1'
      }
      return 'progress-0'
    }
    // 解析题数
    if (column.field === 'analysisNum') {
      return row.analysisNum === row.totalNum ? '' : 'progress-60'
    }
    // 入库题数、题库入库进度
    if (['generateNum', 'progress'].includes(column.field)) {
      const progress = (Number(row.generateNum) || 0) / Number(row.totalNum)
      if (progress === 1) {
        return 'progress-100'
      }
      if (progress >= 0.8) {
        return 'progress-80'
      }
      if (progress >= 0.6) {
        return 'progress-60'
      }
      if (progress > 0) {
        return 'progress-1'
      }
      return 'progress-0'
    }
  },
  beforeRemove(records: any) {
    if (userInfo.value.isSuperAdmin) return true
    for (const item of records) {
      // if (item.status === status_db_done) {
      //   hud.error('不能删除已入库成功的数据')
      //   return false
      // }
      if (item.createUserId !== userInfo.value.id) {
        hud.error('不能删除其他教师的数据')
        return false
      }
    }
    return true
  },
} as MjGridProps

const searchForm = {
  items: [
    {
      title: '状态',
      field: 'status',
      itemRender: {
        name: mj_form_select,
        options: [
          {
            label: '入库完成',
            value: status_db_done,
          },
          {
            label: '解析错误',
            value: status_error,
          },
        ],
        props: { clearable: true },
        events: {
          change: () => {
            gridRef.value?.reload()
          },
        },
      },
    },
  ],
  data: {},
} as MjFormProps

// 新增
function add() {
  router.push('/question-bank/question-resource-add')
}

// 查看
function view(row: any) {
  router.push({
    path: '/question-bank/question-resource-detail',
    query: {
      id: row.id,
    },
  })
}

// 查看题目列表
function showQuestions(row: any) {
  router.push({
    path: '/question-bank/question-mgr',
    query: {
      resourceId: row.id,
    },
  })
}

// 生成题目
// function generate(row: any) {
//   hud.load({
//     task: async () => {
//       await questionResourceService.generateExam(row.id)
//     },
//   })
// }

function fixAll() {
  hud.confirm({
    content: '确定要修复全部数据吗？',
    onConfirm: async () => {
      questionResourceService.fixAll()
    },
  })
}
async function auditFun(row: any) {
  hud.load({
    task: async () => {
      // 请求成功之后拿paperId 跳转到question-bank/paper-mgr页面，打开handlePaperQuestions函数
      const res = await questionResourceService.audit(row.id)
      if (res?.paperId) {
        router.push({
          path: '/question-bank/paper-mgr',
          query: {
            paperId: res.paperId,
          },
        })
      }
    },
  })
}

onActivated(() => {
  gridRef.value?.reload()
})
</script>

<template>
  <div class="question-import g-container">
    <MjTable
      ref="gridRef"
      :search-form="searchForm"
      :grid="grid"
      :service="questionResourceService"
    >
      <template #toolbarButtonsExtra>
        <el-button v-if="userInfo.isSuperAdmin" type="primary" @click="fixAll">
          修复全部
        </el-button>
        <el-button type="primary" @click="add"> 新增 </el-button>
      </template>
      <template #operation="{ row }">
        <el-button type="primary" @click="view(row)"> 查看 </el-button>
        <el-button
          :disabled="row.status !== status_db_done"
          type="success"
          @click="showQuestions(row)"
        >
          题目列表
        </el-button>
        <!-- 如果是试卷模板，才有生成试卷按钮 -->
        <el-button
          v-if="row.paperTemplate === 1"
          type="primary"
          @click="auditFun(row)"
        >
          生成试卷
        </el-button>
        <!-- <el-button
          v-if="row.status === 1"
          type="primary"
          @click="generate(row)"
        >
          生成题目
        </el-button> -->
      </template>
    </MjTable>
  </div>
</template>

<style lang="scss" scoped></style>
