<template>
  <div class="space-y-4">
    <div class="flex flex-wrap items-center justify-between gap-2">
      <div class="text-sm text-gray-500">{{ t('store.businessHours.tip') }}</div>
      <div class="flex items-center gap-2">
        <ElButton @click="loadHours">{{ t('store.action.refresh') }}</ElButton>
        <ElButton type="primary" @click="handleAdd">{{
          t('store.businessHours.action.add')
        }}</ElButton>
        <ElButton type="success" :loading="saving" @click="handleSave">
          {{ t('store.businessHours.action.save') }}
        </ElButton>
      </div>
    </div>

    <ElTable :data="hours" border stripe v-loading="loading" class="w-full">
      <ElTableColumn
        :label="t('store.businessHours.table.dayOfWeek')"
        min-width="100"
        align="center"
      >
        <template #default="{ row }">
          <ElSelect v-model="row.dayOfWeek" class="w-full">
            <ElOption
              v-for="option in dayOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </template>
      </ElTableColumn>
      <ElTableColumn
        :label="t('store.businessHours.table.hourType')"
        min-width="120"
        align="center"
      >
        <template #default="{ row }">
          <ElSelect v-model="row.hourType" class="w-full">
            <ElOption
              v-for="option in hourTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </template>
      </ElTableColumn>
      <ElTableColumn
        :label="t('store.businessHours.table.startTime')"
        min-width="120"
        align="center"
      >
        <template #default="{ row }">
          <ElTimePicker
            v-model="row.startTime"
            format="HH:mm"
            value-format="HH:mm:ss"
            :placeholder="t('common.startTime')"
            class="!w-full"
            :clearable="false"
          />
        </template>
      </ElTableColumn>
      <ElTableColumn :label="t('store.businessHours.table.endTime')" min-width="120" align="center">
        <template #default="{ row }">
          <ElTimePicker
            v-model="row.endTime"
            format="HH:mm"
            value-format="HH:mm:ss"
            :placeholder="t('common.endTime')"
            class="!w-full"
            :clearable="false"
          />
        </template>
      </ElTableColumn>
      <ElTableColumn
        :label="t('store.businessHours.table.capacityLimit')"
        min-width="120"
        align="center"
      >
        <template #default="{ row }">
          <ElInputNumber
            v-model="row.capacityLimit"
            class="!w-full"
            :min="0"
            controls-position="right"
            :placeholder="t('common.unlimited')"
          />
        </template>
      </ElTableColumn>
      <ElTableColumn :label="t('store.businessHours.table.notes')" min-width="200">
        <template #default="{ row }">
          <ElInput
            v-model="row.notes"
            :placeholder="t('store.businessHours.table.notesPlaceholder')"
            maxlength="50"
            show-word-limit
          />
        </template>
      </ElTableColumn>
      <ElTableColumn :label="t('common.action')" width="80" fixed="right" align="center">
        <template #default="{ $index }">
          <ElButton link type="danger" @click="handleRemove($index)">
            {{ t('store.action.delete') }}
          </ElButton>
        </template>
      </ElTableColumn>
    </ElTable>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElButton,
    ElInput,
    ElInputNumber,
    ElMessage,
    ElOption,
    ElSelect,
    ElTable,
    ElTableColumn,
    ElTimePicker
  } from 'element-plus'
  import { fetchBatchUpdateBusinessHours, fetchStoreBusinessHours } from '@/api/store'
  import { BusinessHourType } from '@/enums/BusinessHourType'

  defineOptions({ name: 'BusinessHoursPanel' })

  interface BusinessHourFormItem {
    dayOfWeek: number
    hourType: BusinessHourType
    startTime: string
    endTime: string
    capacityLimit?: number
    notes?: string
  }

  // 1. 基础输入
  const props = defineProps<{ storeId: string }>()
  const { t } = useI18n()

  // 2. 时段数据
  const loading = ref(false)
  const saving = ref(false)
  const hours = ref<BusinessHourFormItem[]>([])

  // 3. 选项配置
  const dayOptions = [
    { value: 0, label: t('store.businessHours.days.sunday') },
    { value: 1, label: t('store.businessHours.days.monday') },
    { value: 2, label: t('store.businessHours.days.tuesday') },
    { value: 3, label: t('store.businessHours.days.wednesday') },
    { value: 4, label: t('store.businessHours.days.thursday') },
    { value: 5, label: t('store.businessHours.days.friday') },
    { value: 6, label: t('store.businessHours.days.saturday') }
  ]
  const hourTypeOptions = [
    { value: BusinessHourType.Normal, label: t('store.businessHours.hourType.normal') },
    {
      value: BusinessHourType.ReservationOnly,
      label: t('store.businessHours.hourType.reservation')
    },
    { value: BusinessHourType.PickupOrDelivery, label: t('store.businessHours.hourType.pickup') },
    { value: BusinessHourType.Closed, label: t('store.businessHours.hourType.closed') }
  ]

  // 4. 数据加载
  const loadHours = async () => {
    if (!props.storeId) {
      hours.value = []
      return
    }
    loading.value = true
    try {
      const list = await fetchStoreBusinessHours(props.storeId)
      hours.value = list.map((item) => ({
        dayOfWeek: item.dayOfWeek,
        hourType: item.hourType,
        startTime: item.startTime,
        endTime: item.endTime,
        capacityLimit: item.capacityLimit ?? undefined,
        notes: item.notes ?? ''
      }))
    } finally {
      loading.value = false
    }
  }

  watch(
    () => props.storeId,
    () => {
      loadHours()
    },
    { immediate: true }
  )

  // 5. 交互处理
  const handleAdd = () => {
    hours.value.push({
      dayOfWeek: 1,
      hourType: BusinessHourType.Normal,
      startTime: '09:00:00',
      endTime: '18:00:00',
      capacityLimit: undefined,
      notes: ''
    })
  }
  const handleRemove = (index: number) => {
    hours.value.splice(index, 1)
  }
  const handleSave = async () => {
    if (!props.storeId) {
      return
    }
    saving.value = true
    try {
      await fetchBatchUpdateBusinessHours(props.storeId, { items: hours.value })
      ElMessage.success(t('store.message.updateSuccess'))
      loadHours()
    } finally {
      saving.value = false
    }
  }
</script>
