import { App, Button, Card, Form, Modal, Select } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import MaterialNoTextMould from '@/pages/weComTask/page/businessPlan/create/components/massSending/materialNoTextMould';
import { welcomeContentData } from '@/pages/weComTask/page/businessPlan/create/const';
import NewSteps from '@/pages/weComTask/components/newSteps';

/**
 * 官方 群聊群发内容配置
 * @param param0 
 * @returns 
 */
const SettingsContent: React.FC<GROUP_CHAT_CREATE.FoundationProps<any>> = ({ visible, onClose, value, onChange, isEditSc }) => {

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

    const [stepsList, setStepsList] = useState<any>([
        {
            title: `策略${1}`,
            id: 'strategy_1',
            children: [{
                title: `发送群对象${1}`,
                id: 'strategy_1_sendData_1'
            }]
        },
        { title: '完成' }
    ])
    /***********************************************/

    useEffect(() => {
        if (value) {
            console.log(value)
            const valueS = {
                ...value,
                strategyList: value?.strategyList?.map(str => {
                    return {
                        ...str,
                        sendData: str?.sendData?.map(item => {
                            return {
                                ...item,
                                contentDTO: item?.contentDTO || [{}]
                            }
                        })
                    }
                })
            }
            filedUpdateChange(valueS)
            form.setFieldsValue(valueS)
        }
    }, [value])

    const handleOk = () => {
        form.validateFields().then((values) => {
            onChange(values)
        }).catch(() => {
            form.submit()
        });
    };

    const filedUpdateChange = ({ strategyList }: any) => {
        const strategyChildren = strategyList?.map((item, index) => {
            const { sendData } = item

            const children = sendData?.map((sd, sdIndex) => {

                const content = sd?.contentDTO?.map((i, i_index) => {
                    return { 
                        title: `内容${i_index + 1}`, 
                        checked: (i?.attachmentList?.length || i?.text?.content), 
                        id: `strategy_${index + 1}_sendData_${sdIndex + 1}_content_${i_index + 1}`
                    }
                })

                return {
                    title: `发送群对象${sdIndex + 1}`, id: `strategy_${index + 1}_sendData_${sdIndex + 1}`, checked: content.every(item => item.checked) && (sd?.sendMode || sd?.sendMode === 0),
                    children: [
                        { title: `内容组发送模式`, id: `strategy_${index + 1}_sendData_${sdIndex + 1}_sendMode`, checked: sd?.sendMode || sd?.sendMode === 0 },
                        ...content
                    ]
                }
            })
            return {
                title: `策略${index + 1}`,
                id: `strategy_${index + 1}`,
                children,
                checked: children.every(item => item.checked)
            }
        })
        const stepsData = [
            ...strategyChildren,
            {
                title: '完成', checked: strategyChildren.every(item => item.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="newGroupChatSendCnotent"
                labelAlign='left'
                labelCol={{ span: 5 }}
                colon={false}
                scrollToFirstError={{
                    behavior: 'smooth',
                    block: 'center'
                }}
                onFinishFailed={({ errorFields }) => {
                    message.error(errorFields?.[0]?.errors?.[0])
                }}
                onFinish={handleOk}
                onFieldsChange={() => {
                    filedUpdateChange(form.getFieldsValue())
                }}
                preserve={true}
            >
                <Form.List name="strategyList">
                    {(fields) => (
                        <>
                            {fields.map(({ key, name, ...restField }, index) => {
                                const strategyItem = strategyList[index]
                                return <Card
                                    key={key}
                                    title={<strong>策略 {strategyItem.strategyName} 配置</strong>}
                                    style={{ background: '#fff', marginBottom: 10 }}
                                    id={`strategy_${index + 1}`}
                                >
                                    <Form.List name={[name, 'sendData']} {...restField}>
                                        {(fields) => (
                                            <>
                                                {fields.map(({ key, name, ...restField }, i) => {
                                                    const sendDataItem = strategyItem?.sendData?.[i];

                                                    return <Card
                                                        key={i}
                                                        title={<strong>发送群对象 {sendDataItem.sendGroupName} 配置</strong>}
                                                        style={{ background: '#fff', marginBottom: 10 }}
                                                        id={`strategy_${index + 1}_sendData_${i + 1}`}
                                                    >
                                                        <div id={`strategy_${index + 1}_sendData_${i + 1}_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 }, c_index) => {
                                                                            return <div key={c_index} id={`strategy_${index + 1}_sendData_${i + 1}_content_${c_index + 1}`}>
                                                                                <h3 style={{ display: 'flex', justifyContent: 'space-between', margin: 0 }}>内容{c_index + 1}
                                                                                    {fields?.length > 1 && <Button
                                                                                        type="dashed"
                                                                                        danger
                                                                                        onClick={() => remove(c_index)}
                                                                                        icon={<MinusOutlined />}
                                                                                        size='small'
                                                                                        disabled={isEditSc}
                                                                                    >
                                                                                        移除内容
                                                                                    </Button>}
                                                                                </h3>
                                                                                <Form.Item
                                                                                    {...restField}
                                                                                    name={name}
                                                                                    rules={[{
                                                                                        validator: (_, value) => {
                                                                                            if ((value && !(value?.text?.content || value?.attachmentList?.length)) || !value) {
                                                                                                return Promise.reject('请填写内容或上传附件');
                                                                                            }
                                                                                            return Promise.resolve();
                                                                                        }
                                                                                    }]}
                                                                                >
                                                                                    <MaterialNoTextMould disabledAdd={isEditSc} />
                                                                                </Form.Item>
                                                                            </div>
                                                                        })}
                                                                        <Form.Item noStyle>
                                                                            <Button type="dashed" disabled={isEditSc} onClick={() => add()} style={{ width: '100%' }} icon={<PlusOutlined />}>
                                                                                新增内容
                                                                            </Button>
                                                                        </Form.Item>
                                                                    </>
                                                                }}
                                                            </Form.List>
                                                        </div>
                                                    </Card>
                                                })}
                                            </>
                                        )}
                                    </Form.List>
                                </Card>
                            })}
                        </>
                    )}
                </Form.List>
            </Form>
        </div>
    </Modal>;
};

export default SettingsContent;