<template>
  <div class="exam-batch-list g-container">
    <MjTable
      ref="gridRef"
      :grid="grid"
      :service="examBatchService"
      :search-form="searchForm"
      :edit-form="editForm"
      hide-edit
      hide-remove
      add-button-text="新增批次"
    >
      <template #operation="{ row }">
        <el-button type="primary" size="small" @click="gridRef.edit(row)">
          编辑
        </el-button>
        <el-button type="primary" size="small" @click="handleImport(row)">
          导入成绩
        </el-button>
        <el-button size="small" @click="handleDetails(row)">查看详情</el-button>
        <el-button type="danger" size="small" @click="handleDelete(row)">
          删除
        </el-button>
      </template>
      <template #status="{ row }">
        <el-switch
          v-model="row.status"
          :active-value="0"
          :inactive-value="1"
          active-text="正常"
          inactive-text="禁用"
          @change="handleStatusChange(row)"
        />
      </template>
    </MjTable>

    <!-- Import Dialog -->
    <el-dialog
      v-model="importVisible"
      title="导入成绩"
      width="500px"
      append-to-body
    >
      <el-upload
        action="#"
        :auto-upload="false"
        multiple
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :file-list="fileList"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">请上传表格文件，支持多文件上传</div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="importLoading"
            @click="confirmImport"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Details Dialog -->
    <el-dialog
      v-model="detailsVisible"
      title="查看详情"
      width="80%"
      append-to-body
    >
      <div style="height: 70vh">
        <MjTable
          ref="detailsGridRef"
          :grid="detailsGrid"
          :service="examScoreService"
          :search-form="detailsSearchForm"
          :search-params="detailsSearchParams"
          :edit-form="detailsEditForm"
          hide-add
          hide-edit
          delete-button-text="批量删除"
        >
          <template #detailOperation="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="detailsGridRef.edit(row)"
            >
              编辑
            </el-button>
          </template>
        </MjTable>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

import { ElMessage } from 'element-plus'

import { examBatchService } from '#/api/service/exam/exam-batch'
import { examScoreService } from '#/api/service/exam/exam-score'
import MjTable, {
  mj_form_date,
  mj_form_input,
  mj_form_switch,
} from '#/components/mj/mj-table'
import type {
  MjEditFormProps,
  MjFormProps,
  MjGridProps,
} from '#/components/mj/mj-table'

import hud from '#/utils/hud'

// --- Batch List Configuration ---
const gridRef = ref()

const searchForm: MjFormProps = {
  items: [
    {
      field: 'name',
      title: '批次名称',
      itemRender: {
        name: mj_form_input,
        props: { clearable: true },
      },
    },
  ],
}

const editForm: MjEditFormProps = {
  addForm: {
    items: [
      {
        field: 'name',
        title: '批次',
        required: true,
        span: 24,
        itemRender: {
          name: mj_form_input,
          props: { clearable: true },
        },
      },
      {
        field: 'deadline',
        title: '截止日期',
        span: 24,
        itemRender: {
          name: mj_form_date,
          props: {
            type: 'datetime',
          },
        },
      },
      {
        field: 'status',
        title: '状态',
        span: 24,
        itemRender: {
          name: mj_form_switch,
          props: {
            openValue: 0,
            closeValue: 1,
            openLabel: '正常',
            closeLabel: '禁用',
          },
        },
      },
    ],
  },
  updateForm: {
    items: [
      {
        field: 'name',
        title: '批次',
        required: true,
        span: 24,
        itemRender: {
          name: mj_form_input,
          props: { clearable: true },
        },
      },
      {
        field: 'deadline',
        title: '截止日期',
        span: 24,
        itemRender: {
          name: mj_form_date,
          props: {
            type: 'datetime',
          },
        },
      },
      {
        field: 'status',
        title: '状态',
        span: 24,
        itemRender: {
          name: mj_form_switch,
          props: {
            openValue: 0,
            closeValue: 1,
            openLabel: '正常',
            closeLabel: '禁用',
          },
        },
      },
    ],
  },
  form: {
    titleWidth: 100,
    data: { name: '', deadline: '', status: 0 },
    rules: {
      name: [{ required: true, message: '请输入批次名称', trigger: 'blur' }],
    },
  },
  addFields: ['name', 'deadline', 'status'],
  updateFields: ['id', 'name', 'deadline', 'status'],
}

const grid: MjGridProps = {
  columns: [
    { type: 'seq' },
    {
      field: 'name',
      title: '批次',
    },
    {
      field: 'deadline',
      title: '截止日期',
    },
    {
      field: 'status',
      title: '状态',
      slots: { default: 'status' },
    },
    {
      title: '操作',
      width: 360,
      slots: { default: 'operation' },
      fixed: 'right',
    },
  ],
}

// --- Import ---
const importVisible = ref(false)
const importLoading = ref(false)
const fileList = ref<any[]>([])
const currentBatchId = ref<null | number>(null)

const handleImport = (row: any) => {
  currentBatchId.value = row.id
  importVisible.value = true
  fileList.value = []
}

const handleFileChange = (_file: any, files: any[]) => {
  fileList.value = files
}

const handleFileRemove = (_file: any, files: any[]) => {
  fileList.value = files
}

const confirmImport = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择文件')
    return
  }
  importLoading.value = true
  try {
    const files = fileList.value.map((f) => f.raw)
    await examScoreService.importScores(files, currentBatchId.value)
    // ElMessage.success('导入成功')
    importVisible.value = false
    hud.success('导入成功')
  } catch (error) {
    console.error(error)
  } finally {
    importLoading.value = false
  }
}

const handleDelete = (row: any) => {
  hud.confirmLoad(`确定要删除批次${hud.highlight(row.name)}吗？`, {
    option: '删除',
    task: async () => {
      await examBatchService.delete(row.id)
      gridRef.value?.reload()
    },
  })
}

const handleStatusChange = async (row: any) => {
  const oldStatus = row.status === 0 ? 1 : 0
  try {
    await examBatchService.saveOrUpdate({
      id: row.id,
      name: row.name,
      deadline: row.deadline,
      status: row.status,
    })
  } catch (error) {
    row.status = oldStatus
    console.error(error)
  }
}

// --- Details Configuration ---
const detailsVisible = ref(false)
const detailsGridRef = ref()
const detailsSearchParams = ref({})

const detailsSearchForm: MjFormProps = {
  items: [
    {
      field: 'keyword',
      title: '关键字',
      itemRender: {
        name: mj_form_input,
        props: { clearable: true, placeholder: '姓名/身份证/学号/班级' },
      },
    },
  ],
}

const detailsGrid: MjGridProps = {
  columns: [
    { type: 'seq' },
    { field: 'name', title: '学生姓名' },
    { field: 'cardNo', title: '身份证号' },
    { field: 'classNo', title: '学号' },
    { field: 'className', title: '班级名称' },
    { field: 'extraDataJson', title: '成绩数据', showOverflow: true },
    {
      title: '操作',
      width: 100,
      slots: { default: 'detailOperation' },
      fixed: 'right',
    },
  ],
}

const detailsEditForm: MjEditFormProps = {
  updateForm: {
    items: [
      {
        field: 'name',
        title: '学生姓名',
        required: true,
        span: 24,
        itemRender: {
          name: mj_form_input,
          props: { clearable: true },
        },
      },
      {
        field: 'cardNo',
        title: '身份证号',
        span: 24,
        itemRender: {
          name: mj_form_input,
          props: { clearable: true },
        },
      },
      {
        field: 'classNo',
        title: '学号',
        span: 24,
        itemRender: {
          name: mj_form_input,
          props: { clearable: true },
        },
      },
      {
        field: 'className',
        title: '班级名称',
        span: 24,
        itemRender: {
          name: mj_form_input,
          props: { clearable: true },
        },
      },
      {
        field: 'extraDataJson',
        title: '成绩数据',
        span: 24,
        itemRender: {
          name: mj_form_input,
          props: { clearable: true },
        },
      },
    ],
  },
  form: {
    titleWidth: 100,
    data: {
      name: '',
      cardNo: '',
      classNo: '',
      className: '',
      extraDataJson: '',
      examBatchId: 0,
    },
    rules: {
      name: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
    },
  },
  updateFields: [
    'id',
    'name',
    'cardNo',
    'classNo',
    'className',
    'extraDataJson',
    'examBatchId',
  ],
}

const handleDetails = (row: any) => {
  detailsVisible.value = true
  detailsSearchParams.value = { examBatchId: row.id }
  // Reload details table if it's already mounted, otherwise it will load on mount
  if (detailsGridRef.value) {
    // We need to wait for the dialog to open and component to be available if it's v-if/v-show logic
    // But since it's just setting searchParams, next tick reload should work
    setTimeout(() => {
      detailsGridRef.value.reload()
    }, 100)
  }
}
</script>

<style scoped>
.exam-batch-list {
  height: 100% !important;
}
</style>
