import { App, Button, Card, Form, Input, Modal } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import '../../../../businessPlan/create/global.less'
import NewSteps from '@/pages/weComTask/components/newSteps';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import SendTimeSet from '@/pages/weComTask/components/sendTimeSet';
import dayjs from 'dayjs';

/**
 * 群聊创建策略配置
 * @param param0 
 * @returns 
 */
const SettingsStrategy: React.FC<GROUP_CHAT_CREATE.FoundationProps<any>> = ({ visible, onClose, value, onChange }) => {

    /************************************/
    const { message } = App.useApp()
    const ref1 = useRef<HTMLDivElement>(null)
    const [form] = Form.useForm();
    const strategyList = Form.useWatch('strategyList', form)

    const [stepsList, setStepsList] = useState<any>([
        // { title: '群聊创建配置', description: '任务名称', id: 'basicInfo' },
        { title: '策略配置', children: [{ title: `策略${1}`, id: 'strategy_1' }] },
        { title: '完成' }
    ])
    /************************************/

    // 回填
    useEffect(() => {
        if (value && Object.keys(value).length) {
            const data = {
                ...value, strategyList: value?.strategyList?.map(item => {
                    const { sendTime, startTime, endTime, sendDay, timeRepeatType } = item
                    if (timeRepeatType === 'TIME_TYPE_SINGLE_PLACE') {
                        const data = {
                            ...item,
                            timeRepeatType,
                            sendDay: sendDay ? dayjs(sendDay + ' ' + sendTime) : undefined
                        }
                        delete data?.sendTime
                        return data
                    }
                    return {
                        ...item,
                        timeRepeatType,
                        sendTime: sendTime ? dayjs('2025-04-25 ' + sendTime) : undefined,
                        startTime: startTime ? dayjs(startTime) : undefined,
                        endTime: endTime ? dayjs(endTime) : undefined,
                        sendDay: sendDay ? dayjs(sendDay) : undefined
                    }
                })
            }
            console.log('=================>', data)
            filedUpdateChange(data)
            form.setFieldsValue(data)
        }
    }, [value])

    const handleOk = () => {
        form.validateFields().then((values) => {
            const data = {
                ...values,
                strategyList: values?.strategyList?.map(item => {
                    const { startTime, endTime, sendDay, sendTime, timeRepeatType, repeatArray, ...rest } = item
                    const data = { ...rest, timeRepeatType }
                    if (timeRepeatType === 'TIME_TYPE_SINGLE_PLACE') {
                        // 定时发送
                        data.sendDay = dayjs(sendDay).format('YYYY-MM-DD')
                        data.sendTime = dayjs(sendDay).format('HH:mm:ss')
                    } else if (timeRepeatType === 'TIME_TYPE_REPEAT_DAY') {
                        // 每日循环
                        data.startTime = dayjs(startTime).format('YYYY-MM-DD')
                        if (endTime) {
                            data.endTime = dayjs(endTime).format('YYYY-MM-DD')
                        }
                        data.sendTime = dayjs(sendTime).format('HH:mm:ss')
                    } else if (timeRepeatType === 'TIME_TYPE_REPEAT_WEEK' || timeRepeatType === 'TIME_TYPE_REPEAT_MONTH') {
                        // 每周循环、每月循环
                        data.startTime = dayjs(startTime).format('YYYY-MM-DD')
                        data.sendTime = dayjs(sendTime).format('HH:mm:ss')
                        if (endTime) {
                            data.endTime = dayjs(endTime).format('YYYY-MM-DD')
                        }
                        data.repeatArray = repeatArray
                    }
                    return data
                })
            }
            onChange(data)
        }).catch(() => {
            form.submit()
        });
    };

    const filedUpdateChange = ({ strategyList }: any) => {
        const strategyChildren = strategyList?.map((item, index) => {
            const { strategyName, timeRepeatType, sendDay, startTime, sendTime, repeatArray } = item
            const sendTimeChecked =
                timeRepeatType === "TIME_TYPE_SINGLE_TIMELY" ||
                (timeRepeatType === "TIME_TYPE_SINGLE_PLACE" && sendDay) ||
                (timeRepeatType === "TIME_TYPE_REPEAT_DAY" && startTime && sendTime) ||
                ((timeRepeatType === "TIME_TYPE_REPEAT_WEEK" || timeRepeatType === "TIME_TYPE_REPEAT_MONTH") && startTime && sendTime && repeatArray)
            return { title: `策略${index + 1}`, description: `策略名称、执行时间`, id: `strategy_${index + 1}`, checked: sendTimeChecked && strategyName }
        })
        const stepsData = [
            { title: '策略配置', children: strategyChildren, checked: strategyChildren.some(item => item.checked) },
            {
                title: '完成', checked: strategyChildren.some(item => item.checked)
            }
        ]
        setStepsList(stepsData)
    }

    return <Modal
        title={<strong>群聊创建策略配置  &nbsp;&nbsp;&nbsp;<span style={{ color: 'red' }}>对于执行时间冲突的策略，按照策略的排序执行</span></strong>}
        open={visible}
        onCancel={onClose}
        width={850}
        onOk={handleOk}
        className={`settingsModal`}
    >
        <div className={`body_steps`}>
            <NewSteps
                items={stepsList}
                onChange={(e) => {
                    if (e?.id)
                        ref1.current?.querySelector('#' + e?.id)?.scrollIntoView({ behavior: 'smooth' })
                }}
            />
        </div>
        <div className={`body_content`} ref={ref1}>
            <Form
                form={form}
                name="newGroupChatStrategy"
                labelAlign='left'
                labelCol={{ span: 5 }}
                colon={false}
                scrollToFirstError={{
                    behavior: 'smooth',
                    block: 'center'
                }}
                onFinishFailed={({ errorFields }) => {
                    message.error(errorFields?.[0]?.errors?.[0])
                }}
                onFinish={handleOk}
                initialValues={{
                    strategyList: [{ id: Date.now() }]
                }}
                onFieldsChange={() => {
                    filedUpdateChange(form.getFieldsValue())
                }}
                preserve={true}
            >
                <Form.List name="strategyList">
                    {(fields, { add, remove }) => (
                        <>
                            {fields.map(({ key, name, ...restField }, index) => {
                                const timeRepeatType = strategyList?.[index]?.timeRepeatType
                                return <Card
                                    key={key}
                                    title={<strong>策略{index + 1} 配置</strong>}
                                    style={{ background: '#fff', marginBottom: 10 }}
                                    extra={strategyList?.length > 1 && <div style={{ color: 'red', cursor: 'pointer' }} onClick={() => remove(name)}>
                                        <MinusCircleOutlined />
                                    </div>}
                                    id={`strategy_${index + 1}`}
                                >
                                    <Form.Item
                                        {...restField}
                                        name={[name, 'strategyName']}
                                        label={<strong>策略名称</strong>}
                                        rules={[{ required: true, message: '请输入策略名称!' }]}
                                    >
                                        <Input placeholder='请输入策略名称' allowClear style={{ width: 358 }} />
                                    </Form.Item>
                                    <SendTimeSet active='all' form={form} restField={restField} name={name} timeRepeatType={timeRepeatType} />
                                </Card>
                            })}
                            <Form.Item>
                                <Button type="dashed" onClick={() => add({ id: Date.now() })} block icon={<PlusOutlined />}>
                                    新增策略
                                </Button>
                            </Form.Item>
                        </>
                    )}
                </Form.List>
            </Form>
        </div>
    </Modal>
};

export default React.memo(SettingsStrategy);