<script setup lang="ts">
import type { ExperimentItem, ClassItem } from '../types'
import { CirclePlus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AppList from '@/components/base/AppList.vue'

import { getExperiment, experimentAddClass } from '../api'
import { useAppConfig } from '@/composables/useAppConfig'
const appConfig = useAppConfig()

const SelectClassDialog = defineAsyncComponent(() => import('../components/SelectClassDialog.vue'))
const StudentGroupDialog = defineAsyncComponent(() => import('../components/StudentGroupDialog.vue'))
const StudentListDialog = defineAsyncComponent(() => import('../components/StudentListDialog.vue'))
const ViewGradeRules = defineAsyncComponent(() => import('../components/ViewGradeRules.vue'))
const ViewReportRules = defineAsyncComponent(() => import('../components/ViewReportRules.vue'))
const ViewExam = defineAsyncComponent(() => import('../components/ViewExam.vue'))
const CopyDialog = defineAsyncComponent(() => import('../components/CopyDialog.vue'))
const DMLFormDialog = defineAsyncComponent(() => import('../components/DMLFormDialog.vue'))
const GradeRulesDialog = defineAsyncComponent(() => import('../components/GradeRulesDialog.vue'))

interface Props {
  id: string
}
const props = defineProps<Props>()

let detail = $ref<ExperimentItem | null>(null)
provide('detail', $$(detail))

const teacherText = $computed(() => {
  if (!detail) return ''
  return detail.teacher.map((item) => item.name).join('、')
})

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = {
  remote: {
    httpRequest: getExperiment,
    params: { experiment_id: props.id },
    callback(data: { total: number; list: ClassItem[]; info: ExperimentItem }) {
      const { total, list, info } = data
      detail = info
      return { list, total }
    },
  },
  columns: [
    { label: '序号', type: 'index', width: 60 },
    { label: '专业名称', prop: 'specialty_id_name' },
    { label: '班级名称', prop: 'name' },
    { label: '学生人数', prop: 'student_nums' },
    { label: '已完成人数', prop: 'complete_nums' },
    { label: '未完成人数', prop: 'not_complete_nums' },
    { label: '更新时间', prop: 'updated_time' },
    { label: '操作', slots: 'table-x', width: 300 },
  ],
}
// 刷新
function handleRefetch() {
  appList?.refetch()
}

let rowData = $ref<ClassItem | null>(null)

// 关联班级
const selectClassVisible = $ref(false)

// 查看学生
let studentListVisible = $ref(false)
function handleViewStudent(row: ClassItem) {
  rowData = row
  studentListVisible = true
}
// 学生分组
let studentGroupVisible = $ref(false)
function handleStudentGroup(row: ClassItem) {
  rowData = row
  studentGroupVisible = true
}
// 移除班级
function handleRemoveClass(row: ClassItem) {
  ElMessageBox.confirm('确定要移除吗？', '提示').then(() => {
    experimentAddClass({ experiment_id: props.id, classes_id: row.id, type: 'delete' }).then(() => {
      ElMessage({ message: '移除成功', type: 'success' })
      appList?.refetch()
    })
  })
}
const gradeRulesVisible = $ref(false)
const reportRulesVisible = $ref(false)
const dmlURL = computed(() => {
  return `${appConfig.dmlURL || import.meta.env.VITE_DML_URL}?experiment_id=${props.id}`
})
const biURL = computed(() => {
  return `${import.meta.env.VITE_SAAS_BI_URL}?experiment_id=${props.id}`
})
const aiURL = computed(() => {
  return `${import.meta.env.VITE_SAAS_AI_URL}?experiment_id=${props.id}`
})

// 复制
let copyDialogVisible = $ref(false)
async function handleCopy() {
  copyDialogVisible = true
}

// 配置数字营销实验
let dmlDialogVisible = $ref(false)
function handleUpdateDML() {
  dmlDialogVisible = true
}

let gradeRulesDialogVisible = $ref(false)
function handleUpdateGradeRules() {
  gradeRulesDialogVisible = true
}
</script>

<template>
  <AppCard title="实验管理">
    <template #header>
      <div>
        <h2 class="app-card-hd__title">实验管理</h2>
        <div class="btn-all" style="margin-bottom: 15px">
          <el-button type="primary" v-if="detail?.type === '4'">
            <a :href="dmlURL" target="_blank">进入实验平台</a>
          </el-button>
          <el-button type="primary" v-if="detail?.type === '5'">
            <a :href="biURL" target="_blank">进入BI实验平台</a>
          </el-button>
          <el-button type="primary" v-if="detail?.type === '6'">
            <a :href="aiURL" target="_blank">进入AI实验平台</a>
          </el-button>
          <el-button type="primary" @click="gradeRulesVisible = true">查看成绩规则</el-button>
          <el-button type="primary" @click="reportRulesVisible = true">查看报告规则</el-button>
          <el-button type="primary" @click="handleCopy()">复制实验</el-button>
          <el-button type="primary" @click="handleUpdateDML()" v-if="detail?.type === '4'">配置数字营销</el-button>
          <el-button type="primary">
            <router-link
              :to="{ path: '/admin/lab/score', query: { course_id: detail?.course_id, experiment_id: detail?.id } }"
              target="_blank"
              >实验评分</router-link
            >
          </el-button>
          <template v-if="!detail?.stu_commit_count">
            <el-button type="primary" @click="handleUpdateGradeRules()">编辑成绩规则</el-button>
            <el-button type="primary">
              <router-link :to="`/admin/lab/experiment/report/${detail?.id}`" target="_blank">编辑报告规则</router-link>
            </el-button>
          </template>
        </div>
      </div>
    </template>
    <el-descriptions title="基本信息" v-if="detail">
      <!-- <template #extra>
        <el-button type="primary" v-if="detail.type === '4'">
          <a :href="dmlURL" target="_blank">进入实验平台</a>
        </el-button>
        <el-button type="primary" @click="gradeRulesVisible = true">查看成绩规则</el-button>
        <el-button type="primary" @click="reportRulesVisible = true">查看报告规则</el-button>
      </template> -->
      <el-descriptions-item :span="3" label="实验名称：">{{ detail.name }}</el-descriptions-item>
      <el-descriptions-item label="实验课程：">{{ detail.course_name }}</el-descriptions-item>
      <el-descriptions-item label="所属机构/学校：">{{ detail.organ_id_name }}</el-descriptions-item>
      <el-descriptions-item label="实验总成绩：">{{ detail.score }}</el-descriptions-item>
      <el-descriptions-item label="实验类型：">{{ detail.type_name }}</el-descriptions-item>
      <el-descriptions-item :span="2" label="实验学时：">{{ detail.length }}学时</el-descriptions-item>
      <el-descriptions-item :span="3" label="指导教师：">{{ teacherText }}</el-descriptions-item>
      <el-descriptions-item :span="3" label="实验目的：">{{ detail.purpose }}</el-descriptions-item>
      <el-descriptions-item :span="3" label="实验要求：">{{ detail.requirements }}</el-descriptions-item>
      <el-descriptions-item :span="3" label="实验内容及原理：">{{ detail.content }}</el-descriptions-item>
      <el-descriptions-item :span="3" label="实验步骤及过程：">{{ detail.procedure }}</el-descriptions-item>
    </el-descriptions>
    <el-divider />
    <AppList v-bind="listOptions" ref="appList">
      <template #header-buttons>
        <el-button
          type="primary"
          :icon="CirclePlus"
          @click="selectClassVisible = true"
          v-permission="'v1-backend-experiment-class-add'"
          >关联班级</el-button
        >
      </template>
      <template #table-x="{ row }">
        <el-button
          type="primary"
          round
          @click="handleViewStudent(row)"
          v-permission="'v1-backend-experiment-class-students'"
          >查看学生</el-button
        >
        <el-button
          type="primary"
          round
          @click="handleStudentGroup(row)"
          v-permission="'v1-backend-experiment-class-teams'"
          >学生分组</el-button
        >
        <el-button type="primary" round @click="handleRemoveClass(row)" v-permission="'v1-backend-experiment-class-add'"
          >移除</el-button
        >
      </template>
    </AppList>
  </AppCard>
  <AppCard :title="detail?.exam_status === '0' ? '训练考试' : '理论考试'">
    <ViewExam v-if="detail" :id="id" :type="detail?.exam_status === '0' ? '2' : '1'"></ViewExam>
  </AppCard>
  <!-- 关联班级 -->
  <SelectClassDialog v-model="selectClassVisible" @update="handleRefetch" v-if="selectClassVisible"></SelectClassDialog>
  <!-- 学生分组 -->
  <StudentGroupDialog
    v-model="studentGroupVisible"
    :data="rowData"
    v-if="studentGroupVisible && rowData"></StudentGroupDialog>
  <!-- 查看学生 -->
  <StudentListDialog
    v-model="studentListVisible"
    :data="rowData"
    :experimentId="id"
    v-if="studentListVisible && rowData"></StudentListDialog>
  <ViewGradeRules v-model="gradeRulesVisible" :data="detail" v-if="gradeRulesVisible && detail"></ViewGradeRules>
  <ViewReportRules v-model="reportRulesVisible" :experiment_id="id" v-if="reportRulesVisible"></ViewReportRules>
  <CopyDialog v-model="copyDialogVisible" :data="detail" v-if="copyDialogVisible && detail"></CopyDialog>
  <!-- 配置数字营销实验 -->
  <DMLFormDialog v-model="dmlDialogVisible" :data="detail" v-if="dmlDialogVisible && detail"></DMLFormDialog>
  <!-- 编辑实验成绩规则 -->
  <GradeRulesDialog
    v-model="gradeRulesDialogVisible"
    :data="detail"
    v-if="gradeRulesDialogVisible && detail"></GradeRulesDialog>
</template>
