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

import { getExperimentGroup, experimentGroupAddStudent } from '../api'

const SelectStudentDialog = defineAsyncComponent(() => import('../components/SelectStudentDialog.vue'))

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

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

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = {
  remote: {
    httpRequest: getExperimentGroup,
    params: { team_id: props.id },
    callback(data: { total: number; list: StudentItem[]; info: GroupItem }) {
      const { total, list, info } = data
      detail = info
      return { list, total }
    }
  },
  columns: [
    { label: '序号', type: 'index', width: 60 },
    {
      label: '小组名称',
      computed() {
        return detail?.name || '-'
      }
    },
    { label: '班级名称', prop: 'class_id_name' },
    { label: '姓名', prop: 'name' },
    { label: '学号', prop: 'id_number' },
    { label: '操作', slots: 'table-x', width: 100 }
  ]
}
// 刷新
function handleRefetch() {
  appList?.refetch()
}

// 关联学生
const selectStudentVisible = $ref(false)

// 移除班级
function handleRemoveStudent(row: StudentItem) {
  ElMessageBox.confirm('确定要移除吗？', '提示').then(() => {
    experimentGroupAddStudent({ team_id: props.id, students_id: row.id, type: 'delete' }).then(() => {
      ElMessage({ message: '移除成功', type: 'success' })
      appList?.refetch()
    })
  })
}
</script>

<template>
  <AppCard title="实验管理">
    <el-descriptions class="descriptions-box" :column="2" v-if="detail">
      <el-descriptions-item label="实验名称：">{{ detail.experiment_name }}</el-descriptions-item>
      <el-descriptions-item label="实验课程：">{{ detail.course_name }}</el-descriptions-item>
      <el-descriptions-item label="小组名称：">{{ detail.name }}</el-descriptions-item>
      <el-descriptions-item label="班级名称：">{{ detail.class_name }}</el-descriptions-item>
    </el-descriptions>
    <AppList v-bind="listOptions" ref="appList">
      <template #header-buttons>
        <el-button
          type="primary"
          round
          :icon="CirclePlus"
          @click="selectStudentVisible = true"
          v-permission="'v1-backend-experiment-team-add-student'"
          >添加小组成员</el-button
        >
      </template>
      <template #table-x="{ row }">
        <el-button
          type="primary"
          round
          @click="handleRemoveStudent(row)"
          v-permission="'v1-backend-experiment-team-add-student'"
          >移除</el-button
        >
      </template>
    </AppList>
  </AppCard>
  <!-- 添加小组成员 -->
  <SelectStudentDialog
    v-model="selectStudentVisible"
    @update="handleRefetch"
    v-if="selectStudentVisible"
  ></SelectStudentDialog>
</template>
