<template>
  <div class="store-page">
    <Breadcrumb />

    <a-card title="占座规则">
      <div class="buttonGroup">
        <a-button type="primary" @click="openModal()">
          <template #icon><icon-plus /></template>
          添加占座规则
        </a-button>
        <a-button @click="loadList">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
      </div>

      <a-alert closable style="margin-bottom: 16px">
        占座将在每晚 22:30 开始，请在每天 22:20 前修改占座规则及志愿，否则修改可能无效。
      </a-alert>

      <a-table row-key="id" :data="data" :loading="loading" :pagination="false" :scroll="{ x: 900 }">
        <template #columns>
          <a-table-column title="规则名" data-index="name" :width="160" />
          <a-table-column title="占座模式" :width="140">
            <template #cell="{ record }">{{ RULE_MODE_MAP[record.mode] || record.mode }}</template>
          </a-table-column>
          <a-table-column title="执行次数" :width="120">
            <template #cell="{ record }">{{ record.loop === 0 ? '单次' : '每周循环' }}</template>
          </a-table-column>
          <a-table-column title="执行星期" :width="180">
            <template #cell="{ record }">
              <span v-for="(day, index) in record.day_of_week || []" :key="day">
                <span v-if="index">、</span>{{ getWeekdayLabel(day) }}
              </span>
            </template>
          </a-table-column>
          <a-table-column title="预约时间" :width="140">
            <template #cell="{ record }">{{ record.beginTime }}~{{ record.endTime }}</template>
          </a-table-column>
          <a-table-column title="参与账号" :width="180" ellipsis tooltip>
            <template #cell="{ record }">{{ (record.users || []).join('、') }}</template>
          </a-table-column>
          <a-table-column title="是否启用" :width="100">
            <template #cell="{ record }">
              <a-switch
                :model-value="record.state === 1"
                :loading="toggleLoading === record.id"
                @change="() => toggleRule(record)"
              />
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="140" fixed="right">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="openModal(record)">编辑</a-button>
                <a-popconfirm content="删除后无法恢复，确认删除？" @ok="handleDelete(record)">
                  <a-button type="text" status="danger" size="small">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="visible"
      :title="form.id ? '编辑占座规则' : '添加占座规则'"
      width="640px"
      @before-ok="handleSave"
      :ok-loading="saving"
      draggable
      esc-to-close
    >
      <a-form :model="form" layout="vertical">
        <a-form-item label="规则名称" required>
          <a-input v-model="form.name" placeholder="仅供识别使用" />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="开始时间" required>
              <a-time-picker v-model="form.beginTime" format="HH:mm" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束时间" required>
              <a-time-picker v-model="form.endTime" format="HH:mm" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="执行次数" required>
          <a-radio-group v-model="form.loop">
            <a-radio :value="0">单次执行</a-radio>
            <a-radio :value="1">每周循环</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item v-if="form.loop === 1" label="执行星期" required>
          <a-checkbox-group v-model="form.day_of_week">
            <a-checkbox v-for="item in WEEKDAY_OPTIONS" :key="item.value" :value="item.value">
              {{ item.label }}
            </a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="执行模式" required>
          <a-select v-model="form.mode" placeholder="请选择执行模式">
            <a-option v-for="item in RULE_MODE_OPTIONS" :key="item.value" :value="item.value">
              {{ item.label }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="参与账号" required>
          <a-select v-model="form.users" multiple placeholder="请选择参与账号">
            <a-option v-for="item in accounts" :key="item.username" :value="item.username">
              {{ item.username }}({{ item.realname || '未知' }})
            </a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Notification } from '@arco-design/web-vue'
import { getJwAccount } from '@/api/jwAccount'
import { getRule, saveRule, deleteRule } from '@/api/ic'
import { RULE_MODE_MAP, RULE_MODE_OPTIONS, WEEKDAY_OPTIONS, getWeekdayLabel } from '@/utils/icTime'

const loading = ref(false)
const saving = ref(false)
const visible = ref(false)
const toggleLoading = ref(null)
const data = ref([])
const accounts = ref([])

const defaultForm = () => ({
  id: undefined,
  name: '',
  beginTime: undefined,
  endTime: undefined,
  loop: 0,
  day_of_week: [],
  mode: 0,
  users: [],
  state: 0
})

const form = reactive(defaultForm())

const parseTime = (timeStr) => {
  if (!timeStr) return undefined
  const [h, m, s = '0'] = timeStr.split(':')
  const d = new Date()
  d.setHours(+h, +m, +s, 0)
  return d
}

const formatTime = (date) => {
  if (!date) return ''
  const d = date instanceof Date ? date : new Date(date)
  const h = String(d.getHours()).padStart(2, '0')
  const m = String(d.getMinutes()).padStart(2, '0')
  return `${h}:${m}:00`
}

const validateTime = (beginTime, endTime) => {
  const begin = new Date(`1970-01-01T${beginTime}`)
  const end = new Date(`1970-01-01T${endTime}`)
  if (begin >= end) throw new Error('开始时间不得晚于结束时间')
  const diffMin = (end - begin) / 60000
  if (diffMin < 60 || diffMin > 880) throw new Error('预约时长应在 60~880 分钟内')
  if (begin.getHours() < 8 || begin.getHours() > 22 || end.getHours() < 8 || end.getHours() > 22) {
    throw new Error('预约时间必须在 8:00~22:00 之间')
  }
}

const loadAccounts = async () => {
  const res = await getJwAccount()
  if (res?.code === 0) {
    accounts.value = (res.data || []).filter((item) => item.state === 1)
  }
}

const loadList = async () => {
  loading.value = true
  try {
    const res = await getRule()
    if (res?.code !== 0) {
      Notification.error({ title: '获取占座规则失败', content: res?.msg })
      return
    }
    data.value = res.data || []
  } finally {
    loading.value = false
  }
}

const openModal = (record) => {
  Object.assign(form, defaultForm())
  if (record) {
    Object.assign(form, {
      id: record.id,
      name: record.name,
      beginTime: parseTime(record.beginTime),
      endTime: parseTime(record.endTime),
      loop: record.loop,
      day_of_week: [...(record.day_of_week || [])],
      mode: record.mode,
      users: [...(record.users || [])],
      state: record.state
    })
  }
  visible.value = true
}

const handleSave = async () => {
  if (!form.name?.trim()) {
    Notification.error({ title: '请填写规则名称' })
    return false
  }
  if (!form.beginTime || !form.endTime) {
    Notification.error({ title: '请选择预约时间' })
    return false
  }
  if (!form.users?.length) {
    Notification.error({ title: '请选择参与账号' })
    return false
  }
  saving.value = true
  try {
    const beginTime = formatTime(form.beginTime)
    const endTime = formatTime(form.endTime)
    validateTime(beginTime, endTime)
    const res = await saveRule({
      id: form.id,
      name: form.name.trim(),
      beginTime,
      endTime,
      loop: form.loop,
      mode: form.mode,
      users: form.users,
      state: form.state,
      day_of_week: form.loop === 1 ? form.day_of_week : []
    })
    if (res?.code !== 0) {
      Notification.error({ title: '保存失败', content: res?.msg })
      return false
    }
    Notification.success({ title: '保存成功' })
    await loadList()
    return true
  } catch (error) {
    Notification.error({ title: '保存失败', content: error.message })
    return false
  } finally {
    saving.value = false
  }
}

const toggleRule = async (record) => {
  toggleLoading.value = record.id
  try {
    const payload = { ...record, state: record.state === 0 ? 1 : 0 }
    const res = await saveRule(payload)
    if (res?.code !== 0) {
      Notification.error({ title: '更改失败', content: res?.msg })
      return
    }
    Notification.success({
      title: `${payload.state === 1 ? '启用' : '禁用'}成功`,
      content: payload.state === 1 ? '该规则将在预定时间执行' : '当前规则将不被执行'
    })
    loadList()
  } finally {
    toggleLoading.value = null
  }
}

const handleDelete = async (record) => {
  const res = await deleteRule({ id: record.id })
  if (res?.code !== 0) {
    Notification.error({ title: '删除失败', content: res?.msg })
    return
  }
  Notification.success({ title: '删除成功' })
  loadList()
}

onMounted(async () => {
  await loadAccounts()
  await loadList()
})
</script>

<style scoped>
.buttonGroup {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}
</style>
