import BaseModel from '@/components/Base/BaseModel';
import { _createAdvertise, _putBusinessPrice } from '@/services/setting';
import { PlusSquareOutlined } from '@ant-design/icons';
import {
  ProForm,
  ProFormDatePicker,
  ProFormDigit,
  ProFormInstance,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  ProFormTimePicker,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { Button, message, Modal } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useRef } from 'react';

const weekDays = [
  { label: '星期一', value: 'mon' },
  { label: '星期二', value: 'tue' },
  { label: '星期三', value: 'wed' },
  { label: '星期四', value: 'thu' },
  { label: '星期五', value: 'fri' },
  { label: '星期六', value: 'sat' },
  { label: '星期日', value: 'sun' },
  { label: '特殊日期', value: 'special' },
];
const timeToMinutes = (time: string): number => {
  const [hours, minutes] = time.split(':').map(Number);
  return hours * 60 + minutes;
};
// 时段冲突检查
const checkTimeConflict = (timeRanges: API.TimePrice[], newRange: API.TimePrice) => {
  const newStart = timeToMinutes(newRange.from);
  const newEnd = timeToMinutes(newRange.to);

  return timeRanges.some((range) => {
    const existingStart = timeToMinutes(range.from);
    const existingEnd = timeToMinutes(range.to);

    return (
      (newStart >= existingStart && newStart <= existingEnd) ||
      (newEnd >= existingStart && newEnd <= existingEnd) ||
      (existingStart >= newStart && existingStart <= newEnd) ||
      (existingEnd >= newStart && existingEnd <= newEnd)
    );
  });
};

export default function DetailModal({
  initData,
  mainTableReload,
}: {
  mainTableReload: () => Promise<void> | undefined;

  initData?: API.PriceEvent;
}) {
  const formRef = useRef<ProFormInstance>();
  const handleTimeRangeChange = async (day: string, field: 'from' | 'to', value: string) => {
    try {
      const values = await formRef.current?.getFieldsValue();
      const currentDayRange = {
        from: field === 'from' ? value : values[day].from,
        to: field === 'to' ? value : values[day].to,
        price: values[day].price,
      };

      // 获取所有其他时段的时间范围
      const otherRanges = Object.entries(values)
        .filter(([key]) => key !== day && weekDays.some((d) => d.value === key))
        .map(([, value]) => value as API.TimePrice);

      if (checkTimeConflict(otherRanges, currentDayRange)) {
        message.warning('時段設置存在重疊，請檢查');
      }
    } catch (error) {
      console.error('验证失败:', error);
    }
  };
  useEffect(() => {
    if (initData && formRef.current) {
      // 转换 Unix 时间戳为 dayjs 对象
      formRef.current.setFieldsValue(initData);
    }
  }, [initData]);
  return (
    <BaseModel
      title="時段設定"
      modalFormProps={{
        formRef: formRef,
        initialValues: initData,
        grid: true,
        onFinish: async (values: API.PriceEvent) => {
          console.log('values', values);
          return new Promise<boolean>((resolve) => {
            Modal.confirm({
              title: '请确保時段沒有重复？',
              centered: true,
              onOk: async () => {
                try {
                  await _putBusinessPrice({
                    ...values,
                    id: initData?.id as string,
                  });
                  message.success('更新成功');
                  mainTableReload?.();
                  resolve(true); // 成功时返回 true
                } catch (error) {
                  console.log('error', error);
                  message.error('更新失敗');
                  resolve(false); // 失败时返回 false
                }
              },
              onCancel: () => {
                resolve(false); // 取消时返回 false
              },
            });
          });
        },
      }}
      submit={() => {
        formRef.current?.submit();
        return true;
      }}
    >
      <ProFormText
        name="event_name"
        label="時段名稱"
        rules={[{ required: true }]}
        colProps={{ span: 12 }}
      />
      <ProFormSwitch name="is_active" label="是否啟用" colProps={{ span: 12 }} />
      <ProFormDatePicker
        name="expire_date"
        label="到期日期"
        rules={[{ required: true }]}
        transform={(value) => (value ? dayjs(value).unix() : undefined)}
        colProps={{ span: 12 }}
      />
      {weekDays.map(({ label, value }) => (
        <ProForm.Group key={value} title={label} collapsible>
          <ProFormTimePicker
            name={[value, 'from']}
            label="開始時間"
            rules={[{ required: true }]}
            fieldProps={{
              format: 'HH:mm',
              onChange: (_, timeString: any) => handleTimeRangeChange(value, 'from', timeString),
            }}
            colProps={{ span: 6 }}
          />
          <ProFormTimePicker
            name={[value, 'to']}
            label="結束時間"
            colProps={{ span: 6 }}
            rules={[{ required: true }]}
            fieldProps={{
              format: 'HH:mm',
              onChange: (_, timeString: any) => handleTimeRangeChange(value, 'to', timeString),
            }}
          />
          <ProFormDigit
            name={[value, 'price']}
            label="價格(HKD/kWh)"
            colProps={{ span: 6 }}
            rules={[{ required: true }]}
            min={0}
            fieldProps={{
              precision: 2,
            }}
          />
        </ProForm.Group>
      ))}
    </BaseModel>
  );
}
export function CreateModal({
  mainTableReload,
}: {
  mainTableReload: () => Promise<void> | undefined;
}) {
  const formRef = useRef<ProFormInstance>();

  return (
    <BaseModel
      allowUpdate={false}
      readOnly={false}
      modalFormProps={{
        grid: true,
        trigger: <Button icon={<PlusSquareOutlined />} type="text" />,
        submitter: {
          searchConfig: {
            resetText: '重置',
            submitText: '確認',
          },
        },
        onFinish: async (value) => {
          console.log('onFinish', value);
          value.image_url = value.image_url[0].originFileObj;
          value.is_show = true;
          value.is_main = false;
          await _createAdvertise(value as API.CreateAdvertisement);
          message.success('創建成功');
          mainTableReload?.();
          return true;
        },
      }}
      title="创建广告"
    >
      <ProFormText
        name="title"
        label="广告名称"
        rules={[{ required: true }]}
        colProps={{ span: 12 }}
      />

      <ProFormUploadButton
        name="image_url"
        label="广告图片"
        colProps={{ span: 8, offset: 3 }}
        fieldProps={{
          accept: '.jpg,.jpeg,.png',
        }}
      />
      <ProFormTextArea name="text" label="广告内容" colProps={{ span: 12 }} />
    </BaseModel>
  );
}
