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

import { useUserStore } from '@vben/stores'

import { paperService } from '#/api/service/question-bank/paper'
import {
  getXkwAuthorizeUrl,
  schoolBookService,
} from '#/api/service/question-bank/school-book'
import {
  mj_form_select,
  mj_form_text,
  mj_form_tree_select,
} from '#/components/mj/mj-table'
import { grade_map, subject_map } from '#/store/basic-data'
import obj from '#/utils/obj'

import { useRoute, useRouter } from 'vue-router'

import {
  pdf_upload_status_map,
  pdf_upload_status_tag_type,
  status_options,
  type_map,
  type_options,
  usePaperStore,
} from '.'
import { useSearchSchoolAndBook } from '../hooks/search'
import TaskMgr from '../task-mgr/home.vue'
import EditPaperQuestions from './edit-paper-questions/index.vue'

defineOptions({ name: 'PaperMgr' })

const props = defineProps<{
  fixedSchool?: any
  fixedTextBook?: any
  schoolId?: any
  schoolName?: any
  textBookId?: any
  textBookName?: any
}>()

const route = useRoute()
const router = useRouter()

const { setPaper } = usePaperStore()

const gridRef = ref()
const taskMgrRef = ref()
const taskMgrVisible = ref(false)
const { userInfo } = storeToRefs(useUserStore())

const chapterOptions = ref<any[]>([])

function loadChapterTree(textBookId: any, keepChapterId = false) {
  if (!textBookId) {
    chapterOptions.value = []
    return
  }
  if (!keepChapterId) {
    const data = gridRef.value?.getEditFormData()
    if (data) data.chapterId = undefined
  }
  schoolBookService.getChapterTreeOptions(textBookId).then((res: any) => {
    chapterOptions.value = res
  })
}

const { schoolRender, bookRender } = useSearchSchoolAndBook(
  {
    prepare: { gridRef, props, fixedName: 'school' },
  },
  {
    prepare: { gridRef, props, fixedName: 'textBook' },
  },
)

watch(
  () => gridRef.value?.getSearchFormData()?.textBookId,
  (newVal) => {
    loadChapterTree(newVal)
  },
)

if (userInfo.value.isOnlyStaff) {
  schoolRender.props.disabled = true
  schoolRender.props.selectedItems = {
    id: userInfo.value.schoolId,
    name: userInfo.value.schoolName,
  }
  bookRender.props.disabled = false
  bookRender.props.cmpProps = {
    ...bookRender.props.cmpProps,
    fixedSchool: true,
  }
}

const refresh = () => {
  gridRef.value.reload()
}

const searchEvents = {
  change() {
    refresh()
  },
}

// 表单
const editForm = {
  modal: {
    width: 900,
  },
  form: {
    titleWidth: 100,
    items: obj.joinObjs<any>(
      {
        required: true,
        field: 'schoolName',
        title: '学校',
        span: 12,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: schoolRender,
          },
        },
      },
      {
        required: true,
        field: 'textBookName',
        title: '教材',
        span: 12,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: bookRender,
          },
        },
      },
      {
        field: 'chapterId',
        title: '章节',
        span: 12,
        itemRender: {
          name: mj_form_tree_select,
          options: chapterOptions,
        },
      },
      {
        required: true,
        field: 'type',
        title: '类型',
        span: 12,
        itemRender: {
          name: mj_form_select,
          props: { clearable: true },
          options: type_options,
        },
      },
      // {
      //   required: true,
      //   field: 'name',
      //   title: '名称',
      //   span: 12,
      //   itemRender: {
      //     name: mj_form_input,
      //   },
      // },
    ),
    data: {},
  },
  addFields: ['name', 'textBookId', 'type', 'chapterId'],
  updateFields: ['id', 'name', 'type', 'chapterId'],
  beforeEditFormShow(data, edit) {
    const fields = ['schoolName', 'textBookName']
    if (edit) {
      gridRef.value.hideEditFormItems(fields)
      if (data.textBookId) {
        loadChapterTree(data.textBookId, true)
      }
    } else {
      gridRef.value.showEditFormItems(fields)
    }
    return data
  },
} as MjEditFormProps

async function onEditFormVisibleChanged(visible: boolean, edit: boolean) {
  if (!visible || edit) return
  await nextTick()
  await nextTick()
  const data = gridRef.value?.getEditFormData()
  const schoolId = data?.schoolId
  if (!schoolId || data?.textBookId) return
  const res = await schoolBookService.findPage(1, 100, { schoolId })
  if (res.rows?.length === 1) {
    const book = res.rows[0]
    const textBookId = book.id ?? book.textbookId
    const textBookName = book.textbookName ?? book.name
    gridRef.value?.update?.({ textBookId, textBookName })
    bookRender.props._methods?.setSelectedItems?.({
      items: { id: textBookId, name: textBookName },
    })
    loadChapterTree(textBookId)
  }
}

// 搜索表单
const searchForm = {
  items: obj.joinObjs<any>(
    {
      title: '学校',
      field: 'schoolId',
      span: 6,
      itemRender: schoolRender,
    },
    {
      title: '教材',
      field: 'textBookId',
      span: 6,
      itemRender: bookRender,
    },
    {
      title: '章节',
      field: 'chapterId',
      span: 6,
      itemRender: {
        name: mj_form_tree_select,
        props: { clearable: true },
        options: chapterOptions,
        events: searchEvents,
      },
    },
    {
      title: '类型',
      field: 'type',
      span: 6,
      itemRender: {
        name: mj_form_select,
        props: { clearable: true },
        options: type_options,
        events: searchEvents,
      },
    },
    {
      title: '状态',
      field: 'status',
      span: 6,
      itemRender: {
        name: mj_form_select,
        props: { clearable: true },
        options: status_options,
        events: searchEvents,
      },
    },
  ),
  data: userInfo.value.isOnlyStaff
    ? {
        schoolId: userInfo.value.schoolId,
        schoolName: userInfo.value.schoolName,
      }
    : {},
} as any

// 表格
const grid = {
  columns: [
    {
      title: '年级',
      field: 'gradeId',
      formatter: ({ cellValue }) => grade_map[cellValue],
    },
    {
      title: '学科',
      field: 'subjectId',
      formatter: ({ cellValue }) => subject_map[cellValue],
    },
    {
      title: '教师',
      field: 'teacherName',
    },
    {
      title: '教材',
      field: 'textBookName',
    },
    {
      title: '章节',
      field: 'chapterName',
    },
    {
      title: '名称',
      field: 'name',
    },
    {
      title: '总分',
      field: 'totalScore',
    },
    {
      field: 'status',
      title: '状态',
      slots: {
        default: 'status',
      },
    },
    {
      field: 'type',
      title: '类型',
      formatter: ({ cellValue }) => type_map[cellValue],
    },
    {
      field: 'uploadStatus',
      title: '文件状态',
      slots: {
        default: 'uploadStatus',
      },
    },
    {
      title: '操作',
      minWidth: 380,
      slots: {
        default: 'operation',
      },
    },
  ],
  beforeLoadData(params) {
    if (userInfo.value.isOnlyStaff) {
      params.schoolId = userInfo.value.schoolId
    }
    return params
  },
} as MjGridProps

// 跳转学科网题目页面
const openXkwQuestions = async (row: any) => {
  try {
    const res = await getXkwAuthorizeUrl({
      targetPaperId: row.id,
      chapterId: row.chapterId,
      courseId: row.courseId,
      textbookId: row.textBookId,
    })
    const url = res?.authorizeUrl
    if (!url) {
      ElMessage.error('返回数据中缺少 authorizeUrl')
      return
    }
    window.location.href = url
  } catch {
    // 拦截器已统一处理错误提示
  }
}

// 处理试卷的题目
const handlePaperQuestions = (row: any) => {
  setPaper(row)
  paperQuestionsVisible.value = true
}
const paperQuestionsVisible = ref(false)

// 状态改变
const statusChange = async (row: any) => {
  const oldFlag = !row.status
  paperService.updateStatus(row.id, row.status).catch(() => {
    row.status = oldFlag
  })
}

// 创建任务
const createTask = async (row: any) => {
  setPaper(row)
  const data = {
    schoolId: row.schoolId,
    schoolName: row.schoolName,
    textBookId: row.textBookId,
    textBookName: row.textBookName,
    paperId: row.id,
    paperName: row.name,
    paperType: row.type,
  }
  taskMgrVisible.value = true
  await nextTick()
  taskMgrRef.value?.openAddTask?.(data)
}

const onTaskCreated = () => {
  taskMgrVisible.value = false
  router.push('/question-bank/task-mgr')
}
// 删除试卷
const deletePaper = (row: any) => {
  ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    paperService.delete(row.id).then(() => {
      refresh()
    })
  })
}

// 上传PDF试题
const uploadPdfInputRef = ref<HTMLInputElement | null>(null)
const uploadingPaperId = ref<any>(null)

const triggerUploadPdf = (row: any) => {
  uploadingPaperId.value = row.id
  uploadPdfInputRef.value?.click()
}

const handlePdfFileChange = async (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) return
  input.value = ''
  try {
    await paperService.uploadPdf(uploadingPaperId.value, file)
    ElMessage.success('提交成功，题目正在解析中，请过三分钟后再来查看')
    refresh()
  } catch {
    // 拦截器已统一处理错误提示
  }
}

onMounted(() => {
  //  如果路由里面带有paperId，就调用handlePaperQuestions函数
  const paperId = route.query.paperId
  if (paperId) {
    handlePaperQuestions({ id: paperId })
  }
})
</script>

<template>
  <div class="paper-mgr g-container">
    <MjTable
      ref="gridRef"
      hide-remove
      :edit-form="editForm"
      :grid="grid"
      :service="paperService"
      :search-form="searchForm"
      v-bind="$attrs"
      @edit-form-visible-changed="onEditFormVisibleChanged"
    >
      <template #status="{ row }">
        <el-switch v-model="row.status" @click="statusChange(row)" />
      </template>
      <template #uploadStatus="{ row }">
        <el-tag
          :type="
            (pdf_upload_status_tag_type[row.uploadStatus] ?? 'info') as any
          "
        >
          {{ pdf_upload_status_map[row.uploadStatus] ?? '未上传文件' }}
        </el-tag>
      </template>
      <template #operation="{ row }">
        <div class="operation-btns">
          <el-button
            size="small"
            type="primary"
            @click="handlePaperQuestions(row)"
          >
            查看
          </el-button>
          <el-button size="small" type="warning" @click="openXkwQuestions(row)">
            组卷
          </el-button>
          <el-button size="small" type="success" @click="createTask(row)">
            布置作业
          </el-button>
          <el-button
            v-if="row.uploadStatus !== 1"
            size="small"
            type="info"
            @click="triggerUploadPdf(row)"
          >
            上传试题
          </el-button>
          <el-button size="small" type="danger" @click="deletePaper(row)">
            删除试卷
          </el-button>
        </div>
      </template>
    </MjTable>
    <input
      ref="uploadPdfInputRef"
      type="file"
      accept=".pdf"
      hidden
      @change="handlePdfFileChange"
    />
    <EditPaperQuestions v-model="paperQuestionsVisible" @refresh="refresh" />
    <TaskMgr
      ref="taskMgrRef"
      v-show="taskMgrVisible"
      @visible-change="(v: boolean) => (taskMgrVisible = v)"
      @success="onTaskCreated"
    />
  </div>
</template>

<style lang="scss" scoped>
.paper-mgr {
  height: 100% !important;
}

.operation-btns {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: flex-start;

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