<script setup lang="ts">
import { getGenerateEventsStudentList, generateStudentEvents, clearMemberEvents } from '../api'
import AppList from '@/components/base/AppList.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

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

const detail = ref()

const appList = $ref<InstanceType<typeof AppList> | null>(null)

// 列表配置
const listOptions = $computed(() => {
  return {
    remote: {
      httpRequest: getGenerateEventsStudentList,
      params: { experiment_id: props.id },
      callback(data: { total: number; list: any; info: any }) {
        const { total, list, info } = data
        detail.value = info
        return { list, total }
      }
    },
    columns: [
      { label: '序号', type: 'index', width: 60 },
      { label: '班级', prop: 'class_name' },
      { label: '学号', prop: 'sno_number' },
      { label: '姓名', prop: 'name' },
      { label: '状态', prop: 'generate_status_name' },
      { label: '数据量', prop: 'generate_total' },
      { label: '开始时间', prop: 'begin_time' },
      { label: '完成时间', prop: 'end_time' },
      { label: '操作', slots: 'table-x', width: 270 }
    ]
  }
})

// 清空事件数据
function clearEventData(row: any) {
  ElMessageBox.confirm(
    '该操作将会清空该实验所有学生对应的用户事件数据，且该操作不可逆！请慎重！确定要清空数据吗？',
    '清空用户事件数据'
  ).then(() => {
    clearMemberEvents({ experiment_id: props.id, student_id: row.student_id }).then(() => {
      handleRefresh()
      ElMessage({ type: 'success', message: '清空成功' })
    })
  })
}

// 生成实验数据
function handleGenerate() {
  generateStudentEvents({ experiment_id: props.id }).then(() => {
    handleRefresh()
    ElMessage({ type: 'success', message: '操作成功' })
  })
}

// 刷新
function handleRefresh() {
  appList?.refetch()
}
// 关闭
function handleClose() {
  window.close()
}
</script>

<template>
  <AppCard title="生成实验数据">
    <el-descriptions :column="4" v-if="detail">
      <el-descriptions-item label="实验名称：">{{ detail.experiment_name }}</el-descriptions-item>
      <el-descriptions-item label="实验类型：">{{ detail.experiment_type_name }}</el-descriptions-item>
      <el-descriptions-item label="用户旅程模板：">{{ detail.itinerary_name }}</el-descriptions-item>
      <el-descriptions-item label="模板类型：">
        {{ detail.itinerary_type_name }}
      </el-descriptions-item>
    </el-descriptions>
    <AppList v-bind="listOptions" ref="appList">
      <template #table-x="{ row }">
        <el-button type="primary" text>
          <router-link :to="`/admin/lab/experiment/ed/view/${id}?student_id=${row.student_id}`" target="_blank"
            >查看事件数据
          </router-link>
        </el-button>
        <el-button type="primary" text @click="clearEventData(row)">清空事件数据</el-button>
      </template>
    </AppList>
    <el-row justify="center">
      <el-button type="primary" @click="handleGenerate">生成实验数据</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button @click="handleClose">关闭</el-button>
    </el-row>
  </AppCard>
</template>
