<script lang="ts" setup>
const {t} = useI18n();
import {EventEnum} from "@/constant/enums";
// 星期选项
const weekDays = [
  {key: 'mon', label: t('pages-user.store-management.index.hours.days.monday'), fullName: 'MONDAY'},
  {key: 'tue', label: t('pages-user.store-management.index.hours.days.tuesday'), fullName: 'TUESDAY'},
  {key: 'wed', label: t('pages-user.store-management.index.hours.days.wednesday'), fullName: 'WEDNESDAY'},
  {key: 'thu', label: t('pages-user.store-management.index.hours.days.thursday'), fullName: 'THURSDAY'},
  {key: 'fri', label: t('pages-user.store-management.index.hours.days.friday'), fullName: 'FRIDAY'},
  {key: 'sat', label: t('pages-user.store-management.index.hours.days.saturday'), fullName: 'SATURDAY'},
  {key: 'sun', label: t('pages-user.store-management.index.hours.days.sunday'), fullName: 'SUNDAY'}
]

// 时间段类型定义
interface TimeSlot {
  id: string
  selectedDays: string[]
  startTime: string
  endTime: string
  is24Hours: boolean
}

// 表单数据
const formData = reactive({
  timeSlots: [
    {
      id: 1,
      selectedDays: [],
      startTime: '',
      endTime: '',
      is24Hours: false
    }
  ] as TimeSlot[]
})

// 生成唯一ID
const generateId = () => Date.now().toString() + Math.random().toString(36).substr(2, 9)

// 切换星期选择
const toggleDay = (slotIndex: number, dayKey: string) => {
  const slot = formData.timeSlots[slotIndex]
  const index = slot.selectedDays.indexOf(dayKey)
  if (index > -1) {
    slot.selectedDays.splice(index, 1)
  } else {
    slot.selectedDays.push(dayKey)
  }
}

// 选择开始时间

const isStartTime = ref(false)
// 选择的时间索引
const selectedTimeIndex = ref('')

const selectStartTime = (slotIndex: number) => {
  // 如果当前时间段已经是24小时营业，则不允许选择开始时间
  if (formData.timeSlots[slotIndex].is24Hours) {
    return
  }
  isStartTime.value = true
  selectedTimeIndex.value = slotIndex
  show.value = true
}

const selectEndTime = (slotIndex: number) => {
  // 如果当前时间段已经是24小时营业，则不允许选择结束时间
  if (formData.timeSlots[slotIndex].is24Hours) {
    return
  }
  isStartTime.value = false
  selectedTimeIndex.value = slotIndex
  show.value = true
}

// 切换24小时营业
const toggle24Hours = (slotIndex: number) => {
  formData.timeSlots[slotIndex].is24Hours = !formData.timeSlots[slotIndex].is24Hours
  // 选中了24小时营业，清空时间
  if (formData.timeSlots[slotIndex].is24Hours) {
    formData.timeSlots[slotIndex].startTime = '0:00'
    formData.timeSlots[slotIndex].endTime = '23:59'
  } else {
    // 如果取消24小时营业，清空时间
    formData.timeSlots[slotIndex].startTime = ''
    formData.timeSlots[slotIndex].endTime = ''
  }
}

// 删除时间段
const removeTimeSlot = (slotIndex: number) => {
  if (formData.timeSlots.length > 1) {
    formData.timeSlots.splice(slotIndex, 1)
  }
}

// 添加时间段
const addTimeSlot = () => {
  const newSlot: TimeSlot = {
    id: generateId(),
    selectedDays: [],
    startTime: '',
    endTime: '',
    is24Hours: false
  }
  formData.timeSlots.push(newSlot)
}

// 生成营业时间字符串
const generateBusinessHoursString = () => {
  const timeSegments: string[] = []

  formData.timeSlots.forEach(slot => {
    if (slot.selectedDays.length > 0) {
      // 获取星期的完整名称
      const dayNames = slot.selectedDays.map(dayKey => {
        const day = weekDays.find(d => d.key === dayKey)
        return day?.fullName || ''
      }).filter(name => name)

      if (dayNames.length > 0) {
        const daysString = dayNames.join('/')

        if (slot.is24Hours) {
          // 24小时营业
          timeSegments.push(`${daysString} 00:00-23:59`)
        } else if (slot.startTime && slot.endTime) {
          // 指定时间营业
          timeSegments.push(`${daysString} ${slot.startTime}-${slot.endTime}`)
        }
      }
    }
  })

  return timeSegments.join(';')
}

// 提交表单
const submitForm = () => {
  // 验证表单
  for (let i = 0; i < formData.timeSlots.length; i++) {
    const slot = formData.timeSlots[i]
    if (slot.selectedDays.length === 0) {
      uni.showToast({
        title: `${t('pages-user.menu.detail.pleaseSelectDays')} ${i + 1}`,
        icon: 'none'
      })
      return
    }

    if (!slot.is24Hours && (!slot.startTime || !slot.endTime)) {
      uni.showToast({
        title: `${t('pages-user.menu.detail.pleaseSetTime')} ${i + 1}`,
        icon: 'none'
      })
      return
    }

    // 验证结束时间不能早于开始时间
    if (!slot.is24Hours && slot.startTime && slot.endTime && slot.endTime <= slot.startTime) {
      uni.showToast({
        title: `${t('pages-user.menu.detail.endTimeError')} ${i + 1}`,
        icon: 'none'
      })
      return
    }
  }

  // 生成营业时间字符串
  const businessHoursString = generateBusinessHoursString()

  uni.$emit(EventEnum.CHOOSE_MENU_TIME, businessHoursString)
  uni.navigateBack()
}

const show = ref(false)
const timeValue = ref()

function handleClose() {
  show.value = false
}

function handleSubmit() {
  console.log(timeValue.value)
  // show.value = false
  if (isStartTime.value) {
    formData.timeSlots[selectedTimeIndex.value].startTime = timeValue.value
  } else {
    formData.timeSlots[selectedTimeIndex.value].endTime = timeValue.value
  }
  show.value = false
}

// 解析回显数据
const parseScheduleTimes = (scheduleTimesStr: string) => {
  if (!scheduleTimesStr) return

  try {
    // 清空现有数据
    formData.timeSlots = []

    // 按分号分割不同的时间段
    const timeSegments = scheduleTimesStr.split(';')

    timeSegments.forEach(segment => {
      const trimmedSegment = segment.trim()
      if (!trimmedSegment) return

      // 查找最后一个空格，分离天数和时间部分
      const lastSpaceIndex = trimmedSegment.lastIndexOf(' ')
      if (lastSpaceIndex === -1) return

      const daysStr = trimmedSegment.substring(0, lastSpaceIndex)
      const timeStr = trimmedSegment.substring(lastSpaceIndex + 1)

      // 解析天数
      const dayNames = daysStr.split('/')
      const selectedDays: string[] = []

      dayNames.forEach(dayName => {
        const trimmedDayName = dayName.trim()
        const weekDay = weekDays.find(day => day.fullName === trimmedDayName)
        if (weekDay) {
          selectedDays.push(weekDay.key)
        }
      })

      if (selectedDays.length === 0) return

      // 解析时间
      const timeParts = timeStr.split('-')
      if (timeParts.length !== 2) return

      const startTime = timeParts[0].trim()
      const endTime = timeParts[1].trim()

      // 判断是否为24小时营业
      const is24Hours = (startTime === '00:00' || startTime === '0:00') && endTime === '23:59'

      // 创建时间段对象
      const timeSlot: TimeSlot = {
        id: generateId(),
        selectedDays,
        startTime: is24Hours ? '0:00' : startTime,
        endTime: is24Hours ? '23:59' : endTime,
        is24Hours
      }

      formData.timeSlots.push(timeSlot)
    })

    // 如果解析后没有任何时间段，添加一个默认的空时间段
    if (formData.timeSlots.length === 0) {
      formData.timeSlots.push({
        id: generateId(),
        selectedDays: [],
        startTime: '',
        endTime: '',
        is24Hours: false
      })
    }

  } catch (error) {
    console.error('解析营业时间字符串失败:', error)
    // 解析失败时，保持默认的空时间段
    formData.timeSlots = [{
      id: generateId(),
      selectedDays: [],
      startTime: '',
      endTime: '',
      is24Hours: false
    }]
  }
}

onLoad((options: any) => {
  // 回显数据
  if (options.scheduleTimes) {
    console.log('接收到的营业时间数据:', options.scheduleTimes)
    parseScheduleTimes(decodeURIComponent(options.scheduleTimes))
  }
})
</script>

<template>
  <view class="menu-detail-page bg-white min-h-100vh">
    <!-- 状态栏 -->
    <navbar/>

    <!-- 页面内容 -->
    <view class="px-30rpx pt-30rpx pb-50rpx">
      <!-- 时间段列表 -->
      <view
          v-for="(slot, slotIndex) in formData.timeSlots"
          :key="slot.id"
          class="mb-24rpx last:mb-0"
      >
        <!-- 时间段容器 -->
        <view class="bg-white border-1rpx border-solid border-#DFDFDF rounded-16rpx px-30rpx pt-34rpx pb-40rpx">
          <!-- 删除按钮 -->
          <view class="flex-center-sb mb-30rpx">
            <!-- 星期选择标题 -->
            <text class="text-36rpx text-#333 block font-500">{{
                t('pages-user.menu.detail.selectDaysAndHours')
              }}
            </text>
            <view
                v-if="formData.timeSlots.length > 1"
                class="w-48rpx h-48rpx"
                @tap="removeTimeSlot(slotIndex)"
            >
              <image class="w-48rpx h-48rpx" src="@img/chef/190.png"></image>
            </view>
          </view>

          <!-- 星期选择器 -->
          <view class="grid grid-cols-4 gap-18rpx gap-y-28rpx mb-52rpx">
            <view
                v-for="day in weekDays"
                :key="day.key"
                :class="slot.selectedDays.includes(day.key) ? 'bg-#333 text-white' : 'bg-white border-1rpx border-solid border-#999 text-#333'"
                class="h-66rpx rounded-16rpx center transition-all duration-300"
                @tap="toggleDay(slotIndex, day.key)"
            >
              <text class="text-28rpx font-bold">{{ day.label }}</text>
            </view>
          </view>

          <!-- 时间选择区域 -->
          <view class="time-selection flex gap-30rpx mb-54rpx">
            <!-- 开始时间 -->
            <view class="time-item flex-1">
              <text class="text-36rpx text-#333 mb-20rpx font-500 block">{{
                  t('pages-user.menu.detail.startTime')
                }}
              </text>
              <view
                  class="bg-#F6F6F6 h-98rpx px-24rpx flex-center-sb rounded-16rpx"
                  @tap="selectStartTime(slotIndex)"
              >
                <text
                    :class="slot.startTime ? 'text-#999' : 'text-#999'"
                    class="text-30rpx"
                >
                  {{ slot.startTime || t('common.select') }}
                </text>
                <!-- 下拉箭头 -->
                <image class="w-26rpx h-26rpx" src="@img/chef/108.png"></image>
              </view>
            </view>

            <!-- 结束时间 -->
            <view class="time-item flex-1">
              <text class="text-36rpx text-#333 mb-20rpx font-500 block">{{
                  t('pages-user.menu.detail.endTime')
                }}
              </text>
              <view
                  class="bg-#F6F6F6 h-98rpx px-24rpx flex-center-sb rounded-16rpx"
                  @tap="selectEndTime(slotIndex)"
              >
                <text
                    :class="slot.endTime ? 'text-#999' : 'text-#999'"
                    class="text-30rpx"
                >
                  {{ slot.endTime || t('common.select') }}
                </text>
                <!-- 下拉箭头 -->
                <image class="w-26rpx h-26rpx" src="@img/chef/108.png"></image>
              </view>
            </view>
          </view>

          <!-- 24小时营业选项 -->
          <view class="flex items-center justify-end">
            <text class="text-36rpx text-#333 font-500 mr-10rpx">{{ t('pages-user.menu.detail.open24Hours') }}</text>
            <!-- 复选框 -->
            <view class="pt-4rpx" @click="toggle24Hours(slotIndex)">
              <image v-if="slot.is24Hours" class="w-32rpx h-32rpx" src="@img/chef/209.png"></image>
              <image v-else class="w-32rpx h-32rpx" src="@img/chef/208.png"></image>
            </view>
          </view>
        </view>
      </view>

      <!-- 添加时间段按钮 -->
      <view
          class="border-1rpx border-solid border-#333 rounded-16rpx h-88rpx center"
          @click="addTimeSlot"
      >
        <text class="text-30rpx text-#333 font-500">{{ t('pages-user.menu.detail.addTimeSlot') }}</text>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <fixed-bottom-large-btn
        :text="t('common.submit')"
        class="z-100"
        fixed
        @click="submitForm"
    />


    <!--选择时间-->
    <wd-popup v-model="show" position="bottom" @close="handleClose">
      <view>
        <view class="flex-center-sb h-102rpx bg-#F7F7F7 px-30rpx">
          <view class="text-30rpx text-#999" @click="handleClose">{{ t('common.cancel') }}</view>
          <view class="text-34rpx text-#333">{{ t('pages-user.menu.detail.dateFilter') }}</view>
          <view class="text-30rpx text-#FF6106" @click="handleSubmit">{{ t('common.confirm') }}</view>
        </view>
        <view class="px-60rpx pt-60rpx">
          <wd-datetime-picker-view v-model="timeValue" type="time"/>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style>
page {
  background-color: #fff;
}
</style>