/**
 * 节假日/特殊营业动作：
 * - 抽屉初始化
 * - 表单字段维护
 * - 新增、编辑、删除
 */
import type { Ref } from 'vue';

import type { HolidayFormState } from '../../types';

import type { HolidayDto } from '#/api/store-hours';

import { message } from 'ant-design-vue';

import {
  deleteHolidayApi,
  HolidayType,
  saveHolidayApi,
} from '#/api/store-hours';

interface HolidayPayload {
  endDate: string;
  endTime?: string;
  id?: string;
  reason: string;
  remark?: string;
  startDate: string;
  startTime?: string;
  type: HolidayType;
}

interface CreateHolidayActionsOptions {
  deletingHolidayId: Ref<string>;
  getTodayDate: () => string;
  holidayDrawerMode: Ref<'create' | 'edit'>;
  holidayForm: HolidayFormState;
  isHolidayDrawerOpen: Ref<boolean>;
  isHolidaySubmitting: Ref<boolean>;
  loadStoreHours: (storeId: string) => Promise<void>;
  parseTimeToMinutes: (time: string) => null | number;
  selectedStoreId: Ref<string>;
  toDateOnly: (value?: string) => string;
  toTimeHHmm: (value?: string) => string;
}

export function createHolidayActions(options: CreateHolidayActionsOptions) {
  // 1. 表单字段 setter。
  function setHolidayType(value: HolidayType) {
    options.holidayForm.type = value;
  }

  function setHolidayDateMode(mode: 'range' | 'single') {
    options.holidayForm.dateMode = mode;
  }

  function setHolidaySingleDate(value: string) {
    options.holidayForm.singleDate = value;
  }

  function setHolidayRangeStart(value: string) {
    options.holidayForm.rangeStart = value;
  }

  function setHolidayRangeEnd(value: string) {
    options.holidayForm.rangeEnd = value;
  }

  function setHolidayStartTime(value: string) {
    options.holidayForm.startTime = value;
  }

  function setHolidayEndTime(value: string) {
    options.holidayForm.endTime = value;
  }

  function setHolidayReason(value: string) {
    options.holidayForm.reason = value;
  }

  function setHolidayRemark(value: string) {
    options.holidayForm.remark = value;
  }

  // 2. 抽屉初始化与回填。
  function resetHolidayForm() {
    const today = options.getTodayDate();
    options.holidayForm.id = '';
    options.holidayForm.type = HolidayType.Closed;
    options.holidayForm.dateMode = 'single';
    options.holidayForm.singleDate = today;
    options.holidayForm.rangeStart = today;
    options.holidayForm.rangeEnd = today;
    options.holidayForm.startTime = '09:00';
    options.holidayForm.endTime = '22:00';
    options.holidayForm.reason = '';
    options.holidayForm.remark = '';
  }

  function openHolidayDrawer(mode: 'create' | 'edit', holiday?: HolidayDto) {
    options.holidayDrawerMode.value = mode;
    if (mode === 'create' || !holiday) {
      resetHolidayForm();
      options.isHolidayDrawerOpen.value = true;
      return;
    }

    const startDate = options.toDateOnly(holiday.startDate);
    const endDate = options.toDateOnly(holiday.endDate || holiday.startDate);

    options.holidayForm.id = holiday.id;
    options.holidayForm.type = holiday.type;
    options.holidayForm.dateMode = startDate === endDate ? 'single' : 'range';
    options.holidayForm.singleDate = startDate;
    options.holidayForm.rangeStart = startDate;
    options.holidayForm.rangeEnd = endDate;
    options.holidayForm.startTime =
      options.toTimeHHmm(holiday.startTime) || '09:00';
    options.holidayForm.endTime =
      options.toTimeHHmm(holiday.endTime) || '22:00';
    options.holidayForm.reason = holiday.reason || '';
    options.holidayForm.remark = holiday.remark || '';

    options.isHolidayDrawerOpen.value = true;
  }

  // 3. 组装提交载荷并进行合法性校验。
  function buildHolidayPayload(): HolidayPayload | null {
    const reason = options.holidayForm.reason.trim();
    if (!reason) {
      message.error('请填写原因');
      return null;
    }

    let startDate = '';
    let endDate = '';

    if (options.holidayForm.dateMode === 'single') {
      if (!options.holidayForm.singleDate) {
        message.error('请选择日期');
        return null;
      }
      startDate = options.holidayForm.singleDate;
      endDate = options.holidayForm.singleDate;
    } else {
      if (!options.holidayForm.rangeStart || !options.holidayForm.rangeEnd) {
        message.error('请完整填写日期范围');
        return null;
      }
      if (options.holidayForm.rangeStart > options.holidayForm.rangeEnd) {
        message.error('开始日期不能晚于结束日期');
        return null;
      }
      startDate = options.holidayForm.rangeStart;
      endDate = options.holidayForm.rangeEnd;
    }

    let startTime: string | undefined;
    let endTime: string | undefined;

    if (options.holidayForm.type === HolidayType.Special) {
      const start = options.toTimeHHmm(options.holidayForm.startTime);
      const end = options.toTimeHHmm(options.holidayForm.endTime);
      const startMinutes = options.parseTimeToMinutes(start);
      const endMinutes = options.parseTimeToMinutes(end);
      if (
        startMinutes === null ||
        endMinutes === null ||
        startMinutes >= endMinutes
      ) {
        message.error('特殊营业时间不合法');
        return null;
      }
      startTime = start;
      endTime = end;
    }

    return {
      id:
        options.holidayDrawerMode.value === 'edit'
          ? options.holidayForm.id || undefined
          : undefined,
      startDate,
      endDate,
      type: options.holidayForm.type,
      startTime,
      endTime,
      reason,
      remark: options.holidayForm.remark.trim() || undefined,
    };
  }

  // 4. 保存与删除动作。
  async function handleHolidaySubmit() {
    if (!options.selectedStoreId.value) return;

    const payload = buildHolidayPayload();
    if (!payload) return;

    options.isHolidaySubmitting.value = true;
    try {
      await saveHolidayApi({
        storeId: options.selectedStoreId.value,
        holiday: payload,
      });
      message.success(
        options.holidayDrawerMode.value === 'edit'
          ? '日期配置已更新'
          : '日期配置已添加',
      );
      options.isHolidayDrawerOpen.value = false;
      await options.loadStoreHours(options.selectedStoreId.value);
    } catch (error) {
      console.error(error);
    } finally {
      options.isHolidaySubmitting.value = false;
    }
  }

  async function handleDeleteHoliday(id: string) {
    if (!options.selectedStoreId.value) return;

    options.deletingHolidayId.value = id;
    try {
      await deleteHolidayApi(id);
      message.success('已删除');
      await options.loadStoreHours(options.selectedStoreId.value);
    } catch (error) {
      console.error(error);
    } finally {
      options.deletingHolidayId.value = '';
    }
  }

  return {
    handleDeleteHoliday,
    handleHolidaySubmit,
    openHolidayDrawer,
    setHolidayDateMode,
    setHolidayEndTime,
    setHolidayRangeEnd,
    setHolidayRangeStart,
    setHolidayReason,
    setHolidayRemark,
    setHolidaySingleDate,
    setHolidayStartTime,
    setHolidayType,
  };
}
