import NewSteps from '@/pages/weComTask/components/newSteps';
import { App, Button, Card, Form, Select } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import '../../global.less';
import { welcomeContentData } from '../../const';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons'
import MaterialNoTextMould from './materialNoTextMould';
import MaterialMould from '@/pages/weComTask/components/materialMould';

/**
 * 群发内容
 * @param param0 
 * @returns 
 */
const Content = forwardRef(({ massSendingStrategy, value, onChange }: TASK_CREATE.ContentProps, ref: React.ForwardedRef<{ handleOk: (type: string) => void }>) => {

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

    const [stepsList, setStepsList] = useState<any>([])
    /****************************************/

    useImperativeHandle(ref, () => ({
        handleOk(type) {
            handleOk(type)
        }
    }));

    // 回填
    useEffect(() => {
        if (!massSendingStrategy?.strategySettings) {
            message.error('请先设置群发策略')
            return
        }

        if (value && Object.keys(value).length) {
            filedUpdateChange(value)
            form.setFieldsValue(value)
        } else {
            const data = {
                massSendingContentDTO: massSendingStrategy.strategySettings.map(item => {
                    return {
                        sendContentDto: item.sendData.map(() => ({ contentDTO: [undefined], sendMode: undefined }))
                    }
                })
            }
            filedUpdateChange(data)
            form.setFieldsValue(data)
        }
    }, [value, massSendingStrategy])

    const handleOk = (type: string) => {
        form.validateFields().then((values) => {
            console.log(values)
            onChange(values, type)
        }).catch(() => {
            form.submit()
        });
    };

    const filedUpdateChange = ({ massSendingContentDTO }: { massSendingContentDTO: { sendContentDto: any }[] }) => {
        const stepsData = massSendingContentDTO.map((item, index) => {

            const children = item.sendContentDto.map((ci, c_index) => {

                const content = ci?.contentDTO?.map((i, i_index) => {
                    return { title: `内容${i_index + 1}`, checked: i?.length > 0, id: 'clientId' + '_' + index + '_' + c_index + 'contentDTO' }
                })

                const contentChildren = [
                    { title: '发送模式', checked: ci?.sendMode || ci?.sendMode === 0, id: 'clientId' + '_' + index + '_' + c_index + 'sendMode' },
                    ...content
                ]

                return {
                    title: `发送对象 ${c_index + 1}`,
                    id: 'clientId' + '_' + index + '_' + c_index,
                    children: contentChildren,
                    checked: (ci?.sendMode || ci?.sendMode === 0) && contentChildren?.every(item => item.checked)
                }
            })

            return {
                title: '策略' + (index + 1),
                id: 'clientId' + '_' + index,
                children: [
                    ...children,
                    { title: '完成', checked: children?.every(item => item.checked) }
                ],
                checked: children?.every(item => item.checked)
            }
        })

        setStepsList([
            ...stepsData,
            { title: '完成', checked: stepsData?.every(item => item.checked) }
        ])
    }

    return <>
        <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="gjnewContent"
                labelAlign='left'
                labelCol={{ span: 5 }}
                colon={false}
                scrollToFirstError={{
                    behavior: 'smooth',
                    block: 'center'
                }}
                onFinishFailed={({ errorFields }) => {
                    message.error(errorFields?.[0]?.errors?.[0])
                }}
                onFinish={handleOk}
                initialValues={{ massSendingContentDTO: [undefined] }}
                onFieldsChange={() => {
                    console.log(form.getFieldsValue())
                    filedUpdateChange(form.getFieldsValue())
                }}
                preserve={true}
            >
                <Form.List name='massSendingContentDTO'>
                    {(fields) => (
                        <>
                            {fields.map(({ key, name, ...restField }, index) => {
                                return <Card key={index} title={<strong>策略名称：{massSendingStrategy?.strategySettings?.[index]?.strategyName || '<空>'}</strong>} style={{ background: '#fff', marginBottom: 10 }} id={'clientId' + '_' + index}>
                                    <Form.List {...restField} name={[name, 'sendContentDto']}>
                                        {(fields) => (
                                            <>
                                                {fields.map(({ key, name, ...restField }, i) => {
                                                    return <Card
                                                        key={i}
                                                        title={<strong>发送对象{i + 1} 内容配置</strong>}
                                                        style={{ background: '#fff', marginBottom: 10 }}
                                                        id={'clientId' + '_' + index + '_' + i}
                                                    >
                                                        <div id={'clientId' + '_' + index + '_' + i + 'sendMode'}>
                                                            <Form.Item
                                                                {...restField}
                                                                label={<strong>内容组发送模式</strong>}
                                                                name={[name, 'sendMode']}
                                                                rules={[{ required: true, message: '请选择内容组发送模式!' }]}
                                                            >
                                                                <Select
                                                                    showSearch
                                                                    style={{ width: 358 }}
                                                                    allowClear
                                                                    placeholder="请选择内容组发送模式"
                                                                    filterOption={(input, option) =>
                                                                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                                                                    }
                                                                    options={welcomeContentData}
                                                                />
                                                            </Form.Item>
                                                        </div>
                                                        <div id={'clientId' + '_' + index + '_' + i + 'contentDTO'}>
                                                            <Form.List {...restField} name={[name, 'contentDTO']} >
                                                                {(fields, { add, remove }) => {
                                                                    return <>
                                                                        {fields.map(({ key, name, ...restField }, index) => {
                                                                            return <div key={index}>
                                                                                <h3 style={{ display: 'flex', justifyContent: 'space-between', margin: 0 }}>内容{index + 1}
                                                                                    {fields?.length > 1 && <Button
                                                                                        type="dashed"
                                                                                        danger
                                                                                        onClick={() => remove(index)}
                                                                                        icon={<MinusOutlined />}
                                                                                        size='small'
                                                                                    >
                                                                                        移除内容
                                                                                    </Button>}
                                                                                </h3>
                                                                                <Form.Item
                                                                                    {...restField}
                                                                                    name={name}
                                                                                    rules={[{
                                                                                        validator: (_, value) => {
                                                                                            if (!value || value?.length === 0) {
                                                                                                return Promise.reject('请填写内容或上传附件');
                                                                                            }
                                                                                            return Promise.resolve();
                                                                                        }
                                                                                    }]}
                                                                                >
                                                                                    <MaterialMould dataNum={1} />
                                                                                </Form.Item>
                                                                            </div>
                                                                        })}
                                                                        <Form.Item noStyle>
                                                                            <Button type="dashed" onClick={() => add()} style={{ width: '100%' }} icon={<PlusOutlined />}>
                                                                                新增内容
                                                                            </Button>
                                                                        </Form.Item>
                                                                    </>
                                                                }}
                                                            </Form.List>
                                                        </div>
                                                    </Card>
                                                })}
                                            </>
                                        )}
                                    </Form.List>
                                </Card>
                            })}
                        </>
                    )}
                </Form.List>
            </Form>
        </div>
    </>
});

export default React.memo(Content);