<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { useUserStore } from '@vben/stores'

import { storeToRefs } from 'pinia'

import { taskMgrService } from '#/api/service/question-bank/task-mgr'
import Filter from '#/components/Filter'
import hud from '#/utils/hud'

import Knowledge from './components/Knowledge.vue'
import Student from './components/Student.vue'
import Whole from './components/whole.vue'

const route = useRoute()
const router = useRouter()
const { resourceId } = route.query as any
const paperDetail = ref<any>({})
const { userInfo } = storeToRefs(useUserStore())

const explainDialogVisible = ref(false)
const classInfoRawList = ref<any[]>([])
const selectedClassId = ref('')

function openExplainDialog() {
  if (!classInfoRawList.value.length) {
    hud.warning('暂无班级数据')
    return
  }
  selectedClassId.value =
    classInfoRawList.value.length === 1 ? classInfoRawList.value[0]!.id : ''
  explainDialogVisible.value = true
}

function confirmExplain() {
  if (!selectedClassId.value) {
    hud.warning('请选择讲解的班级')
    return
  }
  explainDialogVisible.value = false
  router.push({
    path: '/question-bank/task-mgr/paper-explain',
    query: {
      classId: selectedClassId.value,
      resourceId,
    },
  })
}

const situationType = ref('whole')
const wholeRef = ref()
const studentList = ref<any[]>([])

const filterData = ref<any>({
  classId: '',
  status: '',
})
const classOptions = ref<any[]>([])
const filterConfig = computed(() => {
  const cfg = [
    {
      comName: 'el-select',
      label: '班级',
      prop: 'classId',
      clearable: true,
      filterable: true,
      collapseTags: true,
      collapseTagsTooltip: true,
      multiple: false,
      options: classOptions.value,
      selectConfig: {
        key: 'id',
        label: 'name',
        value: 'id',
      },
    },
  ]
  // if (situationType.value === 'student') {
  //   cfg.unshift({
  //     comName: 'el-select',
  //     label: '状态',
  //     prop: 'status',
  //     clearable: true,
  //     filterable: true,
  //     multiple: false,
  //     options: statusOptions.value,
  //     selectConfig: {
  //       key: 'value',
  //       label: 'name',
  //       value: 'value',
  //     },
  //   } as any)
  // }
  return cfg
})

function onFilterAction(action: any) {
  switch (action.value) {
    case 'reset': {
      break
    }
    case 'search': {
      if (situationType.value === 'whole') {
        wholeRef.value?.getWholeSituationFun?.(filterData.value.classId)
      } else if (situationType.value === 'student') {
        getStudentInfoFun()
      }
      break
    }
  }
}

function onSelectChange(_: any) {}

async function loadClassOptions() {
  const condition: any = {}
  if (userInfo.value.isOnlyStaff) {
    condition.schoolId = userInfo.value.schoolId
  }
  const res = await taskMgrService.getClassInfo(resourceId)
  const list = Array.isArray(res) ? res : []
  classInfoRawList.value = list
  classOptions.value = list.map((item: any) => ({
    id: item.id,
    name: item.name,
  }))
}

// 获取试卷详情
async function getPaperDetail() {
  const res = await taskMgrService.getpaperReleaseRecordDetail(resourceId)
  return res || {}
}

onMounted(async () => {
  paperDetail.value = await getPaperDetail()
  await loadClassOptions()
})

async function getStudentInfoFun() {
  const res = await taskMgrService.getStudentInfo(
    resourceId,
    filterData.value.classId,
    filterData.value.status,
  )
  const list = Array.isArray(res) ? res : (res?.rows ?? res?.data ?? [])
  studentList.value = list || []
}

watch(
  () => situationType.value,
  (v) => {
    if (v === 'student') {
      getStudentInfoFun()
    }
  },
)
</script>

<template>
  <div style="background-color: #fff">
    <div class="top-actions">
      <el-button
        v-if="classInfoRawList.length"
        type="primary"
        @click="openExplainDialog"
      >
        讲解试卷
      </el-button>
    </div>

    <el-dialog
      v-model="explainDialogVisible"
      title="选择讲解班级"
      width="480px"
      align-center
    >
      <el-select
        v-model="selectedClassId"
        placeholder="请选择班级"
        filterable
        style="width: 100%"
      >
        <el-option
          v-for="item in classInfoRawList"
          :key="item.id"
          :label="`${item.gradeName || ''} ${item.name}`"
          :value="item.id"
        />
      </el-select>
      <template #footer>
        <el-button @click="explainDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmExplain">确定</el-button>
      </template>
    </el-dialog>

    <el-card shadow="never" class="detail-card">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="学校名称">
          {{ paperDetail?.schoolName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="作业名称">
          {{ paperDetail?.name || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ paperDetail?.startTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="截止时间">
          {{ paperDetail?.endTime || '-' }}
        </el-descriptions-item>

        <el-descriptions-item label="学生人数">
          {{ paperDetail?.number ?? '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="完成人数">
          {{ paperDetail?.completeNumber ?? '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="作业摘要">
          {{ paperDetail?.remark || '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <!-- 整体情况、学生情况、知识点 -->
    <div class="title">
      <p>整体情况</p>
      <el-radio-group v-model="situationType" size="large" fill="#409eff">
        <el-radio-button label="整体情况" value="whole" />
        <el-radio-button label="学生情况" value="student" />
        <el-radio-button label="知识点" value="knowledge" />
      </el-radio-group>
    </div>
    <div class="filter">
      <Filter
        v-model="filterData"
        :config="filterConfig"
        @handle-action="onFilterAction"
        @select-change="onSelectChange"
      />
    </div>

    <!-- 整体情况 -->
    <Whole
      ref="wholeRef"
      :resource-id="resourceId"
      :class-id="filterData.classId"
      :paper-id="paperDetail?.paperId"
      v-if="situationType === 'whole'"
    />

    <!-- 学生情况 -->
    <Student
      :resource-id="resourceId"
      :class-id="filterData.classId"
      :students="studentList"
      @refresh="getStudentInfoFun"
      v-if="situationType === 'student'"
    />

    <!-- 知识点 -->
    <Knowledge
      :resource-id="resourceId"
      :class-id="filterData.classId"
      v-if="situationType === 'knowledge'"
    />
  </div>
</template>

<style scoped>
.top-actions {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px 0;
}

.title {
  width: 100%;
  margin-top: 24px;
  margin-bottom: 16px;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}
</style>
