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

import { IconifyIcon } from '@vben/icons'
import { useUserStore } from '@vben/stores'

import {
  difficulty_map,
  questionService,
  status_approving,
  status_draft,
  status_map,
  status_options,
  status_reviewed,
  status_reviewing,
} from '#/api/service/question-bank/question'
import MjTable, { mj_form_select } from '#/components/mj/mj-table'
import { router } from '#/router'
import hud from '#/utils/hud'

const { userInfo } = storeToRefs(useUserStore())
const bookOptions = userInfo.value.personConfig?.books?.map((item: any) => ({
  label: item.title,
  value: item.id,
}))

// 搜索表单
const searchItems = [
  // {
  //   title: '题型',
  //   field: 'type',
  //   span: 6,
  //   itemRender: {
  //     name: mj_form_select,
  //     options: type_options,
  //     props: { clearable: true },
  //   },
  // },
  {
    title: '状态',
    field: 'status',
    span: 6,
    itemRender: {
      name: mj_form_select,
      options: status_options,
      props: { clearable: true },
    },
  },
] as any
if (bookOptions?.length) {
  searchItems.push({
    title: '教材',
    field: 'textBookIds',
    span: 6,
    itemRender: {
      name: mj_form_select,
      options: bookOptions,
      props: { clearable: true },
    },
  })
}
const searchForm = {
  items: searchItems,
  data: {},
} as MjFormProps

// 表格
const gridRef = ref()
const grid = {
  columns: [
    { type: 'seq' },
    {
      title: '题干',
      slots: {
        default: 'stem',
      },
      width: 250,
    },
    {
      title: '题型',
      field: 'typeName',
    },
    {
      title: '难度',
      field: 'difficulty',
      formatter({ cellValue }) {
        return difficulty_map[cellValue]
      },
    },
    {
      title: '教材',
      formatter({ row }) {
        return row.configJson?.textbookTitle
      },
    },
    {
      field: 'creator',
      title: '创建',
    },
    {
      field: 'approver',
      title: '审核',
    },
    {
      field: 'reviewer',
      title: '复核',
    },
    {
      title: '状态',
      slots: {
        default: 'status',
      },
    },
    {
      title: '操作',
      slots: {
        default: 'operation',
      },
    },
  ],
  afterLoadData(data) {
    countStats.value = data.countVo
    for (const item of data.pageResult.rows) {
      if (typeof item.configJson === 'string') {
        item.configJson = JSON.parse(item.configJson)
      }
    }
    return data.pageResult
  },
} as MjGridProps

// 审核统计
const countStats = ref({
  total: 0, // 总数
  draft: 0, // 草稿
  approving: 0, // 待审核
  reviewed: 0, // 审核通过
  reviewing: 0, // 待复核
  rejected: 0, // 拒绝
})

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

// 下一步
function next(row: any) {
  router.push({
    path: '/question-bank/question-add',
    query: {
      id: row.id,
    },
  })
}
function nextButtonText(row: any) {
  if (questionService.isReadonly(row, userInfo.value.id)) {
    return '查看'
  }
  if (row.status === status_approving) {
    return '审核'
  }
  if (row.status === status_reviewing) {
    return '复核'
  }
  if (row.status === status_draft) {
    return '编辑'
  }
  return '查看'
}

function tagType(row: any) {
  if (row.status === status_approving) {
    return 'warning'
  }
  if (row.status === status_reviewing) {
    return 'danger'
  }
  if (row.status === status_draft) {
    return 'primary'
  }
  if (row.status === status_reviewed) {
    return 'success'
  }
  return undefined
}

function nextButtonType(row: any) {
  if (questionService.isReadonly(row, userInfo.value.id)) {
    return undefined
  }
  return tagType(row)
}

function reloadStatus(status: any = undefined) {
  gridRef.value.updateSearchFormData({
    status,
  })
  gridRef.value.reload()
}

function canShowRemove(row: any) {
  // 如果是题目的创建者，且还没有复审通过，都可以删除
  // eslint-disable-next-line unicorn/prefer-ternary
  if (row.status === status_reviewed) {
    // 如果是审核通过的题目，只有复审人员可以删除
    return row.reviewerId === userInfo.value.id
  } else {
    return row.creatorId === userInfo.value.id
  }
}
// 删除题目
function remove(row: any) {
  hud.confirmLoad('确定要删除这道题目么？', {
    task: async () => {
      await questionService.remove(row.id)
      gridRef.value.reload()
    },
    option: '删除',
  })
}
</script>

<template>
  <div class="chapter-mgr g-container">
    <!-- 审核统计 -->
    <div class="stats-cards">
      <el-card class="stats-card" @click="reloadStatus()">
        <div class="stats-content">
          <div class="stats-number">{{ countStats.total || 0 }}</div>
          <div class="stats-label">总题目数</div>
        </div>
        <IconifyIcon icon="mdi:book-open-page-variant" class="stats-icon" />
      </el-card>
      <el-card class="stats-card draft" @click="reloadStatus(status_draft)">
        <div class="stats-content">
          <div class="stats-number">{{ countStats.draft || 0 }}</div>
          <div class="stats-label">草稿</div>
        </div>
        <IconifyIcon icon="ri:draft-fill" class="stats-icon" />
      </el-card>
      <el-card
        class="stats-card pending"
        @click="reloadStatus(status_approving)"
      >
        <div class="stats-content">
          <div class="stats-number">{{ countStats.approving || 0 }}</div>
          <div class="stats-label">待审核</div>
        </div>
        <IconifyIcon icon="mdi:clock-outline" class="stats-icon" />
      </el-card>
      <el-card
        class="stats-card rejected"
        @click="reloadStatus(status_reviewing)"
      >
        <div class="stats-content">
          <div class="stats-number">{{ countStats.reviewing || 0 }}</div>
          <div class="stats-label">待复审</div>
        </div>
        <IconifyIcon
          icon="material-symbols:rate-review-outline"
          class="stats-icon"
        />
      </el-card>
      <el-card
        class="stats-card approved"
        @click="reloadStatus(status_reviewed)"
      >
        <div class="stats-content">
          <div class="stats-number">{{ countStats.reviewed || 0 }}</div>
          <div class="stats-label">已通过</div>
        </div>
        <IconifyIcon icon="mdi:check-circle" class="stats-icon" />
      </el-card>
    </div>
    <div class="table-box">
      <MjTable
        ref="gridRef"
        :grid="grid"
        :search-form="searchForm"
        :service="questionService"
        hide-remove
      >
        <template #toolbarButtonsExtra>
          <el-button type="primary" @click="add"> 新增 </el-button>
        </template>
        <template #stem="{ row }">
          <span class="td-text" v-html="row.stem"></span>
        </template>
        <template #analysis="{ row }">
          <span class="td-text" v-html="row.analysis"></span>
        </template>
        <template #operation="{ row }">
          <el-button :type="nextButtonType(row)" @click="next(row)">
            {{ nextButtonText(row) }}
          </el-button>
          <el-button
            v-if="canShowRemove(row)"
            type="danger"
            @click="remove(row)"
          >
            删除
          </el-button>
        </template>
        <template #status="{ row }">
          <el-tag :type="tagType(row)">
            {{ status_map[row.status] }}
          </el-tag>
        </template>
      </MjTable>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chapter-mgr {
  display: flex;
  flex-direction: column;
  height: 100% !important;

  .table-box {
    flex: 1;
  }

  .stats-cards {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 16px;
    margin-bottom: 16px;

    .stats-card {
      position: relative;
      overflow: hidden;
      cursor: pointer;

      .stats-content {
        .stats-number {
          margin-bottom: 4px;
          font-size: 28px;
          font-weight: 600;
          color: #303133;
        }

        .stats-label {
          font-size: 14px;
          color: #606266;
        }
      }

      .stats-icon {
        position: absolute;
        top: 50%;
        right: 16px;
        font-size: 32px;
        opacity: 0.3;
        transform: translateY(-50%);
      }

      &.draft {
        .stats-number {
          color: #409eff;
        }

        .stats-icon {
          color: #409eff;
        }
      }

      &.pending {
        .stats-number {
          color: #e6a23c;
        }

        .stats-icon {
          color: #e6a23c;
        }
      }

      &.approved {
        .stats-number {
          color: #67c23a;
        }

        .stats-icon {
          color: #67c23a;
        }
      }

      &.rejected {
        .stats-number {
          color: #f56c6c;
        }

        .stats-icon {
          color: #f56c6c;
        }
      }
    }
  }
}
</style>
