<script setup lang="ts">
import type { ExperimentItem, ClassItem } from '../types'
import { ElMessage } from 'element-plus'
import { getExperimentClassList, experimentAddClass } from '../api'

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const detail = $ref(inject('detail') as ExperimentItem)

// 列表配置
const listOptions = {
  filters: [{ type: 'input', label: '班级名称', prop: 'name' }],
  remote: {
    httpRequest: getExperimentClassList,
    params: { experiment_id: detail?.id },
  },
  columns: [
    { type: 'selection' },
    { label: '序号', type: 'index', width: 60 },
    { label: '班级代码', prop: 'code' },
    { label: '班级名称', prop: 'name' },
    { label: '所属部门/学校', prop: 'organ_id_name' },
    { label: '人数', prop: 'student_nums' },
    { label: '专业', prop: 'specialty_id_name' },
  ],
}

let multipleSelection = $ref<ClassItem[]>([])
function handleSelectionChange(selection: ClassItem[]) {
  multipleSelection = selection
}

function handleSubmit() {
  const classes_id = multipleSelection.map((item) => item.id).join(',')
  experimentAddClass({ experiment_id: detail.id, classes_id, type: 'add' }).then(() => {
    ElMessage({ message: '关联成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>
<template>
  <el-dialog title="关联班级" @update:modelValue="(value) => $emit('update:modelValue', value)">
    <p style="text-align: right">所属机构/学校：{{ detail.organ_id_name }}</p>
    <AppList v-bind="listOptions" @selection-change="handleSelectionChange"></AppList>
    <el-row justify="center">
      <el-button type="primary" round :disabled="!multipleSelection.length" @click="handleSubmit"
        >关联选择班级</el-button
      >
      <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
    </el-row>
  </el-dialog>
</template>
