import NewSteps from '@/pages/weComTask/components/newSteps';
import { App, Button, Card, Form, Input, Modal, Radio } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import '../../global.less';
import SendTimeSet from '@/pages/weComTask/components/sendTimeSet';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import style from '../massSending/index.less'
import FilterUser from '@/pages/weComTask/components/filterUser';
import dayjs from 'dayjs';

/**
 * 客户继承
 * @param param0 
 * @returns 
 */
const SettingsUserInherit: React.FC<TASK_CREATE.UserInheritProps<any>> = ({ value, visible, onClose, onChange }) => {

    /***************************************************/
    const ref1 = useRef<HTMLDivElement>(null)
    const { message } = App.useApp()
    const [form] = Form.useForm();
    const schedulingStrategyDTO = Form.useWatch('schedulingStrategyDTO', form)
    const [stepsList, setStepsList] = useState<any>([
        { title: '客户继承配置', description: '标题', id: 'basicInfo' },
        {
            title: '策略1', d: `strategy_0`, children: [
                { title: '发送时间', id: `strategy_0_sendTime` },
                {
                    title: '继承转移1', id: `strategy_0_0_inheritDto`, children: [
                        { title: '智能标签', id: `strategy_0_0_inheritDto_sendMsgTag` },
                        { title: '转移对象', id: `strategy_0_0_inheritDto_object`, description: '对象筛选，人群包，文本消息' }
                    ]
                },
                { title: '完成' }
            ]
        },
        { title: '完成' }
    ])
    /***************************************************/

    // 回填
    useEffect(() => {
        if (value && Object.keys(value).length) {
            const data = {
                ...value, schedulingStrategyDTO: value?.schedulingStrategyDTO?.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
                    }
                })
            }
            filedUpdateChange(data)
            form.setFieldsValue(data)
        }
    }, [value])

    const handleOk = () => {
        form.validateFields().then((values) => {
            const data = {
                ...values,
                schedulingStrategyDTO: values?.schedulingStrategyDTO?.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
                })
            }
            console.log(values)
            onChange(data)
        }).catch(() => {
            form.submit()
        });
    };

    const filedUpdateChange = ({ taskName, schedulingStrategyDTO }: any) => {
        const content = schedulingStrategyDTO?.map((item, index) => {

            const { timeRepeatType, sendDay, startTime, sendTime, repeatArray, inheritDto } = 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)

            const contentChildren = inheritDto?.map((ii, ni) => {
                const objectChecked = ii?.transferType === 'all' ? true : ii?.transferUserDto && Object.values(ii?.transferUserDto).every(item => item)
                return {
                    title: '继承转移' + (ni + 1),
                    id: `strategy_${index}_${ni}_inheritDto`,
                    checked: objectChecked,
                    children: [
                        { title: '转移对象', description: '对象筛选，人群包', id: `strategy_${index}_${ni}_inheritDto_object`, checked: objectChecked }
                    ]
                }
            })
            return {
                title: `策略${index + 1}`,
                id: `strategy_${index}`,
                checked: sendTimeChecked && contentChildren.every(i => i.checked),
                children: [
                    { title: '发送时间', checked: sendTimeChecked, id: `strategy_${index}_sendTime` },
                    ...contentChildren,
                    { title: '完成', checked: sendTimeChecked && contentChildren.every(i => i.checked) }
                ]
            }
        })
        const stepsData = [
            { title: '客户继承配置', description: '标题', checked: taskName, id: 'basicInfo' },
            ...content,
            { title: '完成', checked: taskName && content.every(i => i.checked) }
        ]
        setStepsList(stepsData)
    }

    return <Modal
        title={<strong>客户继承模板配置</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="newUserInherit"
                labelAlign='left'
                labelCol={{ span: 5 }}
                colon={false}
                scrollToFirstError={{
                    behavior: 'smooth',
                    block: 'center'
                }}
                onFinishFailed={({ errorFields }) => {
                    message.error(errorFields?.[0]?.errors?.[0])
                }}
                onFinish={handleOk}
                initialValues={{
                    schedulingStrategyDTO: [{ inheritDto: [{ transferType: 'specify' }] }],
                }}
                onFieldsChange={() => {
                    filedUpdateChange(form.getFieldsValue())
                }}
                preserve={true}
            >
                <Card title={<strong>基础信息配置</strong>} hoverable style={{ background: '#fff', marginBottom: 10 }} id='basicInfo'>
                    <Form.Item label={<strong>客户继承标题</strong>} name="taskName" rules={[{ required: true, message: '请输入标题!' }]}>
                        <Input placeholder="请输入标题" style={{ width: 358 }} allowClear />
                    </Form.Item>
                </Card>

                <Form.List name="schedulingStrategyDTO">
                    {(fields, { add, remove }) => (
                        <>
                            {fields.map(({ key, name, ...restField }, index) => {
                                const timeRepeatType = schedulingStrategyDTO?.[index]?.timeRepeatType
                                const inheritDto = schedulingStrategyDTO?.[index]?.inheritDto

                                return <Card
                                    key={key}
                                    title={<strong>策略{index + 1}配置</strong>}
                                    style={{ background: '#fff', marginBottom: 10 }}
                                    hoverable
                                    id={`strategy_${index}`}
                                    extra={schedulingStrategyDTO?.length > 1 ? <Button icon={<DeleteOutlined />} type='link' style={{ color: 'red' }} onClick={() => remove(name)}></Button> : null}
                                >
                                    <div className={style.strategy_item} id={`strategy_${index}_strategyName`}>
                                        <Form.Item
                                            {...restField}
                                            label={<strong>策略名称</strong>}
                                            name={[name, 'strategyName']}
                                            rules={[{ required: false, message: '请输入策略名称!' }]}
                                        >
                                            <Input placeholder="请输入标题" style={{ width: 358 }} allowClear />
                                        </Form.Item>
                                        <div id={`strategy_${index}_sendTime`}>
                                            <SendTimeSet active='all' form={form} restField={restField} name={name} timeRepeatType={timeRepeatType} />
                                        </div>

                                        <Form.List name={[name, 'inheritDto']}>
                                            {(fields, { add, remove }) => (
                                                <>
                                                    {fields.map(({ key, name, ...restField }, i) => {
                                                        return <Card
                                                            key={i}
                                                            title={<strong>策略{index + 1} 继承转移{i + 1}</strong>}
                                                            extra={inheritDto?.length > 1 ? <Button icon={<DeleteOutlined />} type='link' style={{ color: 'red' }} onClick={() => remove(name)}></Button> : null}
                                                            id={`strategy_${index}_${i}_inheritDto`}
                                                            style={{ background: '#fff', marginBottom: 10 }}
                                                        >
                                                            <div id={`strategy_${index}_${i}_inheritDto_object`}>
                                                                <Form.Item
                                                                    label={<strong>转移对象</strong>}
                                                                    required
                                                                >
                                                                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
                                                                        <Form.Item
                                                                            {...restField}
                                                                            name={[name, 'transferType']}
                                                                            rules={[{ required: true, message: '请选择转移对象!' }]}
                                                                            noStyle
                                                                        >
                                                                            <Radio.Group options={[{ label: '全部', value: 'all' }, { label: '指定', value: 'specify' }]} />
                                                                        </Form.Item>
                                                                        {inheritDto?.[i]?.transferType === 'specify' && <div style={{ marginTop: 8, width: '100%' }}>
                                                                            <Form.Item
                                                                                {...restField}
                                                                                name={[name, 'transferUserDto']}
                                                                                rules={[{ required: true, message: '请选择人群包!' }]}
                                                                                noStyle
                                                                            >
                                                                                <FilterUser configType='USER_GROUP' />
                                                                            </Form.Item>
                                                                        </div>}
                                                                    </div>
                                                                </Form.Item>
                                                            </div>
                                                            <Form.Item {...restField} name={[name, 'transferSuccessMsg']} label={<strong>文本消息</strong>} >
                                                                <Input.TextArea placeholder={`客户转移成功后发给客户的消息，最多200个字符，不填则使用默认文案`} rows={2} />
                                                            </Form.Item>
                                                        </Card>
                                                    })}
                                                    <Form.Item>
                                                        <Button type="dashed" onClick={() => add({ transferType: 'specify' })} block icon={<PlusOutlined />}>
                                                            新增继承转移
                                                        </Button>
                                                    </Form.Item>
                                                </>
                                            )}
                                        </Form.List>
                                    </div>
                                </Card>
                            })}
                            <Form.Item>
                                <Button type="primary" onClick={() => add({ inheritDto: [{ transferType: 'specify' }] })} block icon={<PlusOutlined />}>
                                    新增策略组
                                </Button>
                            </Form.Item>
                        </>
                    )}
                </Form.List>
            </Form>
        </div>
    </Modal>
};

export default SettingsUserInherit;