import { Checkbox, DatePicker, Form, FormInstance, Select, Space, Tooltip } from "antd"
import { RangePickerProps } from "antd/es/date-picker"
import React from "react"
import dayjs from 'dayjs'
import { QuestionCircleOutlined } from '@ant-design/icons';
import { WEEK_SERIRES } from "../../page/businessPlan/create/const"

export enum TimeType1Enum {
    TIME_TYPE_SINGLE_TIMELY = '立即发送',
    TIME_TYPE_SINGLE_PLACE = '定时发送'
}
export enum TimeType4Enum {
    TIME_TYPE_SINGLE_TIMELY = '立即发送',
    TIME_TYPE_SINGLE_PLACE = '定时发送',
    TIME_TYPE_REPEAT_DAY = '每日循环',
}
export enum TimeType2Enum {
    TIME_TYPE_REPEAT_DAY = '每日循环',
    TIME_TYPE_REPEAT_WEEK = '每周循环',
    TIME_TYPE_REPEAT_MONTH = '每月循环'
}
export enum TimeType3Enum {
    TIME_TYPE_REPEAT_DAY = '每日循环'
}
export enum TimeTypeAllEnum {
    TIME_TYPE_SINGLE_TIMELY = '立即发送',
    TIME_TYPE_SINGLE_PLACE = '定时发送',
    TIME_TYPE_REPEAT_DAY = '每日循环',
    TIME_TYPE_REPEAT_WEEK = '每周循环',
    TIME_TYPE_REPEAT_MONTH = '每月循环'
}

interface Props {
    active: string, // 2 单次  3 循环 all
    form: FormInstance<any>
    timeRepeatType: string
    disabled?: boolean
    restField?: {
        fieldKey?: number;
    },
    name?: number
    isShow?: boolean
    restFieldChange?: (value?: any) => void
}
/**
 * 发送时间设置
 * @param param0 
 */
const SendTimeSet: React.FC<Props> = ({ active, form, timeRepeatType, disabled, restField, name, isShow, restFieldChange }) => {

    /***********************************/
    const startTime = Form.useWatch('startTime', form)
    const endTime = Form.useWatch('endTime', form)
    /***********************************/

    const disabledDate: RangePickerProps['disabledDate'] = (current) => {
        // Can not select days before today and today
        return current && (current < dayjs().startOf('day') || current > dayjs().add(30, 'day').endOf('day'));
    };

    const disabledStartDate: RangePickerProps['disabledDate'] = (current) => {
        // Can not select days before today and today
        if (endTime) {
            return current && (current < dayjs().startOf('day') || current > dayjs(endTime).endOf('day'));
        }
        return current && (current < dayjs().startOf('day') || current > dayjs().add(30, 'day').endOf('day'));
    };

    const disabledEndDate: RangePickerProps['disabledDate'] = (current) => {
        // Can not select days before today and today
        if (startTime) {
            return current && (current < dayjs(startTime).startOf('day') || current > dayjs().add(30, 'day').endOf('day'));
        }
        return current && (current < dayjs().startOf('day') || current > dayjs().add(30, 'day').endOf('day'));
    };

    const disabledRangeTime = (current: any) => {
        let upDate = dayjs(current).format('YYYY-MM-DD')//选中的年月日
        let upHours = dayjs(current).format('HH')//选中的时
        let upMinutes = dayjs(current).format('mm')//选中的分
        let atDate = dayjs(new Date()).format('YYYY-MM-DD')//今天的年月日
        let atHours = dayjs(new Date()).format('HH')//现在的时
        let atMinutes = dayjs(new Date()).format('mm')//现在的分
        let atSeconds = dayjs(new Date()).format('ss')//现在的秒
        let range = (num: number, at: string) => {
            if (upDate == atDate) {//假如选中时间的今天
                let arr: number[] = []
                Array(num).fill('').forEach((a, b) => { if (b < Number(at)) { arr.push(b) } })
                return arr
            } else {
                return []
            }
        }
        let minutes = (num: number, at: string) => {
            if (upDate == atDate) {//假如选中时间的今天
                let arr: number[] = []
                if (upHours == atHours) {
                    Array(num).fill('').forEach((a, b) => { if (b < Number(at) + 5) { arr.push(b) } })
                }
                return arr
            } else {
                return []
            }
        }
        let seconds = (num: number, at: string) => {
            if (upDate == atDate) {//假如选中时间的今天
                let arr: number[] = []
                if (upHours == atHours) {
                    Array(num).fill('').forEach((a, b) => {
                        if (Number(upMinutes) - Number(atMinutes) > 5) {
                        } else {
                            if (b < Number(at) + 5) { arr.push(b) }
                        }
                    })
                }
                return arr
            } else {
                return []
            }
        }
        return {
            disabledHours: () => range(24, atHours),
            disabledMinutes: () => minutes(60, atMinutes),
            disabledSeconds: () => seconds(60, atSeconds),
        }
    };


    return <>
        <Form.Item
            name={name || typeof name === 'number' ? [name, 'timeRepeatType'] : 'timeRepeatType'}
            {...(restField ? { ...restField } : {})}
            label={<strong>执行类型</strong>}
            rules={isShow ? undefined : [{ required: true, message: '请设置执行类型!' }]}
        >
            <Select
                showSearch
                allowClear
                disabled={disabled}
                placeholder="执行类型"
                filterOption={(input, option) =>
                    ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                }
                style={isShow ? undefined : { width: 358 }}
                onChange={(e) => { restFieldChange?.(e) }}
                options={(active === 'all' ? 
                    Object.keys(TimeTypeAllEnum).map(key => ({ label: TimeTypeAllEnum[key as keyof typeof TimeTypeAllEnum], value: key })) : 
                    active === '2' ? Object.keys(TimeType1Enum).map(key => ({ label: TimeType1Enum[key as keyof typeof TimeType1Enum], value: key })) : 
                    active === '4' ? Object.keys(TimeType4Enum).map(key => ({ label: TimeType4Enum[key as keyof typeof TimeType4Enum], value: key })) : 
                    Object.keys(TimeType2Enum).map(key => ({ label: TimeType2Enum[key as keyof typeof TimeType2Enum], value: key }))) as any}
            />
        </Form.Item>
        {timeRepeatType === 'TIME_TYPE_SINGLE_PLACE' && <Form.Item
            name={name || typeof name === 'number' ? [name, 'sendDay'] : 'sendDay'}
            {...(restField ? { ...restField } : {})}
            label={<strong>执行日期</strong>}
            rules={isShow ? undefined : [{ required: true, message: '请设置执行日期!' }]}
        >
            <DatePicker disabledDate={disabledDate} disabled={disabled} showTime={{ defaultValue: dayjs(dayjs().add(5, 'minute').format('HH:mm:ss'), 'HH:mm:ss') }} disabledTime={disabledRangeTime} />
        </Form.Item>}
        {(timeRepeatType === 'TIME_TYPE_REPEAT_DAY' || timeRepeatType === 'TIME_TYPE_REPEAT_WEEK' || timeRepeatType === 'TIME_TYPE_REPEAT_MONTH') && <Form.Item
            label={<strong>
                执行日期
                {!isShow && <Tooltip title="开始日期必填">
                    <QuestionCircleOutlined style={{ marginLeft: 2 }} />
                </Tooltip>}
            </strong>}
            required={!isShow}
        >
            <Space>
                <Form.Item
                    name={name || typeof name === 'number' ? [name, 'startTime'] : 'startTime'}
                    {...(restField ? { ...restField } : {})}
                    noStyle
                    rules={isShow ? undefined : [{ required: true, message: '请设置开始日期!' }]}
                >
                    <DatePicker placeholder="开始日期" disabled={disabled} disabledDate={disabledStartDate} disabledTime={disabledRangeTime} />
                </Form.Item>
                <span>-</span>
                <Form.Item
                    name={name || typeof name === 'number' ? [name, 'endTime'] : 'endTime'}
                    {...(restField ? { ...restField } : {})}
                    noStyle
                >
                    <DatePicker placeholder="结束日期" disabled={disabled} disabledDate={disabledEndDate} disabledTime={disabledRangeTime} />
                </Form.Item>
            </Space>
        </Form.Item>}
        {timeRepeatType === 'TIME_TYPE_REPEAT_WEEK' && <Form.Item
            name={name || typeof name === 'number' ? [name, 'repeatArray'] : 'repeatArray'}
            {...(restField ? { ...restField } : {})}
            label={<strong>每周执行天数</strong>}
            rules={isShow ? undefined : [{ required: true, message: '请设置每周发送天数!' }]}
        >
            <Checkbox.Group disabled={disabled}>
                <Space wrap>{WEEK_SERIRES.map(item => <Checkbox value={item.value} key={item.value}>{item.label}</Checkbox>)}</Space>
            </Checkbox.Group>
        </Form.Item>}
        {timeRepeatType === 'TIME_TYPE_REPEAT_MONTH' && <Form.Item
            name={name || typeof name === 'number' ? [name, 'repeatArray'] : 'repeatArray'}
            {...(restField ? { ...restField } : {})}
            label={<strong>每月执行天数</strong>}
            rules={isShow ? undefined : [{ required: true, message: '请设置每周发送天数!' }]}
        >
            <Select
                showSearch
                allowClear
                disabled={disabled}
                mode="multiple"
                placeholder="每月执行天数"
                maxLength={8}
                style={{ width: isShow ? '100%' : 358 }}
                options={Array(31).fill('').map((item, index) => ({ label: index + 1 + '号', value: index + 1 }))}
            />
        </Form.Item>}
        {(timeRepeatType === 'TIME_TYPE_REPEAT_DAY' || timeRepeatType === 'TIME_TYPE_REPEAT_WEEK' || timeRepeatType === 'TIME_TYPE_REPEAT_MONTH') && <Form.Item
            name={name || typeof name === 'number' ? [name, 'sendTime'] : 'sendTime'}
            {...(restField ? { ...restField } : {})}
            label={<strong>执行时间</strong>}
            rules={isShow ? undefined : [{ required: true, message: '请设置执行时间!' }]}
        >
            <DatePicker disabled={disabled} picker="time" allowClear={false} showNow={false} />
        </Form.Item>}
    </>
}

export default React.memo(SendTimeSet)