import { ClockCircleOutlined } from '@ant-design/icons';
import { Select, Space } from 'antd';
import { useCallback, useContext, useMemo, useState } from 'react';
import { useIntl } from 'umi';
import { AppDetailContext } from '../utils/hooks';

export type DayOptionType = {
  label: string;
  value: number;
};

/** 秒转天 */
const second2Day = (s: number) => {
  return s / 24 / 60 / 60;
};

/** 天转秒 */
const day2Second = (d: number) => {
  return d * 24 * 60 * 60;
};

export type CustomDayProps = {
  disabled?: boolean;
  value?: number;
  /** 快捷选项是否受应用详情配置限制 */
  optionLimit?: boolean;
  /** 时长是否受应用详情配置限制 */
  lengthLimit?: boolean;
  onChange?: (val: number) => void;
};

const CustomDay = (props: CustomDayProps) => {
  const { disabled, value, optionLimit = false, lengthLimit = false, onChange } = props;
  const { formatMessage } = useIntl();

  const appDetail = useContext(AppDetailContext);

  const { timeLengthShortcutOption, maxLengthExpirationTime } = appDetail || {};

  /** 判断是否有时长限制 */
  const maxLengthLimit = Boolean(lengthLimit && maxLengthExpirationTime);

  const defaultOptions = useMemo<DayOptionType[]>(() => {
    const defOpts = [
      {
        label: formatMessage({ id: 'component.customDay.0.5', defaultMessage: '0.5' }),
        value: 0.5,
      },
      {
        label: formatMessage({ id: 'component.customDay.7', defaultMessage: '7' }),
        value: 7,
      },
      {
        label: formatMessage({ id: 'component.customDay.30', defaultMessage: '30' }),
        value: 30,
      },
      {
        label: formatMessage({ id: 'component.customDay.90', defaultMessage: '90' }),
        value: 90,
      },
      {
        label: formatMessage({ id: 'component.customDay.180', defaultMessage: '180' }),
        value: 180,
      },
      {
        label: formatMessage({ id: 'component.customDay.365', defaultMessage: '365' }),
        value: 365,
      },
      {
        label: formatMessage({ id: 'component.customDay.730', defaultMessage: '730' }),
        value: 730,
      },
      {
        label: formatMessage({ id: 'component.customDay.1095', defaultMessage: '1095' }),
        value: 1095,
      },
    ].filter((v) => {
      const m = day2Second(v.value); // 转秒
      if (maxLengthLimit) return m <= Number(maxLengthExpirationTime);
      return true;
    });

    if (!optionLimit) return defOpts;

    return (
      timeLengthShortcutOption
        ?.filter((v: number) => {
          if (maxLengthLimit) return v <= Number(maxLengthExpirationTime);
          return true;
        })
        .map((v: number) => {
          const day = second2Day(v); // 转天
          return (
            defOpts.find((sv) => sv.value === day) ?? {
              label: String(day),
              value: day,
            }
          );
        }) ?? []
    );
  }, [
    formatMessage,
    maxLengthExpirationTime,
    maxLengthLimit,
    optionLimit,
    timeLengthShortcutOption,
  ]);

  const [options, setOptions] = useState<DayOptionType[]>(defaultOptions);
  const [searchText, setSearchText] = useState<string>();

  const onSearch = useCallback(
    (val: string) => {
      // 必须是数字
      if (/^[\d]+\.?[\d]*$/.test(val)) {
        if (Number(val) === 0) {
          setSearchText(val);
          return;
        }
        const [index] = val.split('.');
        // 整数部分最大不能超过5位数
        if (index && index.length > 5) {
          return;
        }
        // 小数部分必须是'.5', '100.'正则test返回真，其余数字格式假
        const formatVal = /^[\d]+\.$/.test(val) ? val : val.replace(/\.[\d]+/g, '.5');
        const yxVal =
          maxLengthLimit && second2Day(maxLengthExpirationTime) < Number(formatVal)
            ? second2Day(maxLengthExpirationTime).toString()
            : formatVal;
        setSearchText(yxVal);
        const find = defaultOptions.find((v) => v.value === Number(yxVal));
        const newOpts = [...defaultOptions];
        if (!find) {
          // 没有找到则添加自定义选项
          newOpts.unshift({
            label: Number(yxVal).toString(),
            value: Number(yxVal),
          });
        }
        setOptions(newOpts);
      } else if (val === '') {
        setSearchText('');
      }
    },
    [defaultOptions, maxLengthExpirationTime, maxLengthLimit],
  );

  return (
    <Space
      onClick={(e) => {
        e.preventDefault(); // 阻止默认行为（如链接跳转等）
        e.stopPropagation();
      }}
    >
      <Select
        disabled={disabled}
        style={{ width: 203 }}
        suffixIcon={<ClockCircleOutlined />}
        searchValue={searchText}
        options={options}
        allowClear={false}
        value={value}
        onChange={onChange}
        showSearch
        filterOption={(input, option) => {
          const { label, value: optVal } = option ?? {};
          return (
            label?.toLowerCase().includes(input.toLowerCase()) || String(optVal) === input.trim()
          );
        }}
        onSearch={onSearch}
      />
      {formatMessage({ id: 'public.const.Day' })}
    </Space>
  );
};

export default CustomDay;
