<template>
  <div class="store-page">
    <Breadcrumb />
    <a-card title="抢课批次管理">
      <div class="toolbar">
        <a-button v-if="canManage" type="primary" @click="openModal()">
          <template #icon><icon-plus /></template>
          新建批次
        </a-button>
        <a-button @click="getList()">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
      </div>

      <a-alert type="info" class="info-alert">
        停用批次会自动收回该批次下所有进行中的任务；修改批次 ID 后会自动将已分配任务重新放回待分配队列。
      </a-alert>

      <a-table
        :data="data"
        :bordered="false"
        hoverable
        class="table"
        :loading="loading"
        :pagination="false"
        :scroll="{ x: 980 }"
      >
        <template #columns>
          <a-table-column title="ID" data-index="id" :width="80" />
          <a-table-column title="名称" data-index="name" :width="180" ellipsis tooltip />
          <a-table-column title="批次 ID" data-index="jx0502zbid" :width="260" ellipsis tooltip />
          <a-table-column title="状态" :width="100">
            <template #cell="{ record }">
              <a-tag :color="record.enabled ? 'green' : 'gray'">{{ record.enabled ? '启用' : '停用' }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="更新时间" :width="180">
            <template #cell="{ record }">{{ formatTime(record.update_time) }}</template>
          </a-table-column>
          <a-table-column title="操作" :width="100" :fixed="tableFixed('right')">
            <template #cell="{ record }">
              <a-button v-if="canManage" type="text" size="small" @click="openModal(record)">编辑</a-button>
            </template>
          </a-table-column>
        </template>
        <template #empty>
          <a-empty description="暂无抢课批次" />
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="visible"
      :title="form.id ? '编辑批次' : '新建批次'"
      :width="560"
      @ok="submitBatch"
    >
      <a-form :model="form" layout="vertical">
        <a-form-item label="批次名称" required>
          <a-input v-model="form.name" placeholder="例如：2025春公选课" allow-clear />
        </a-form-item>
        <a-form-item label="批次 ID（jx0502zbid）" required>
          <a-input v-model="form.jx0502zbid" placeholder="教务系统选课批次 ID" allow-clear />
        </a-form-item>
        <a-form-item label="是否启用">
          <a-switch v-model="form.enabled" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { Notification } from '@arco-design/web-vue'
import { IconPlus, IconRefresh } from '@arco-design/web-vue/es/icon'
import { adminQkBatchList, adminQkBatchSave } from '@/api/qk'
import { hasPermission } from '@/utils/permission'
import { useResponsiveTable } from '@/hooks/useResponsiveTable'

const { tableFixed } = useResponsiveTable()
const canManage = computed(() => hasPermission('action.qk.admin.batchManage'))

const data = ref([])
const loading = ref(false)
const visible = ref(false)
const form = reactive({
  id: '',
  name: '',
  jx0502zbid: '',
  enabled: true
})

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(Number(time)).toLocaleString('zh-CN')
}

const resetForm = () => {
  Object.assign(form, {
    id: '',
    name: '',
    jx0502zbid: '',
    enabled: true
  })
}

const openModal = (record) => {
  resetForm()
  if (record) {
    Object.assign(form, {
      id: record.id,
      name: record.name,
      jx0502zbid: record.jx0502zbid,
      enabled: !!record.enabled
    })
  }
  visible.value = true
}

const getList = async () => {
  loading.value = true
  try {
    const res = await adminQkBatchList()
    if (!res || res.code !== 0) {
      Notification.error({ title: '获取批次失败', content: res?.msg || '请稍后再试' })
      return
    }
    data.value = res.data || []
  } catch (error) {
    Notification.error({ title: '获取批次失败', content: error.message || '请稍后再试' })
  } finally {
    loading.value = false
  }
}

const submitBatch = async () => {
  const res = await adminQkBatchSave({
    id: form.id || undefined,
    name: form.name,
    jx0502zbid: form.jx0502zbid,
    enabled: form.enabled
  })
  if (!res || res.code !== 0) {
    Notification.error({ title: '保存失败', content: res?.msg || '请稍后再试' })
    return false
  }
  Notification.success({ title: '保存成功' })
  visible.value = false
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="less">
@import '@/styles/store-theme.less';

.toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
}

.info-alert {
  margin-bottom: 16px;
}

.table {
  margin-top: 4px;
}
</style>
