import { App, Button, Card, Form, Input, Modal, Select, Space } from 'antd';
import React, { useEffect, useState } from 'react';
import '../../global.less';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import MaterialMould from '@/pages/weComTask/components/materialMould';
import style from './index.less'
import MindTags from '@/pages/weComTask/components/mindTags';
import NewSteps from '@/pages/weComTask/components/newSteps';
import { welcomeContentData } from '../../const';

/**
 * 欢迎语配置
 * @param param0 
 * @returns 
 */
const SettingsWelcome: React.FC<TASK_CREATE.WelcomeProps<any>> = ({ visible, onClose, value, onChange, isEditSc }) => {

    /***************************************************/
    const { message } = App.useApp()
    const [form] = Form.useForm();
    const mediaContent = Form.useWatch('mediaContentList', form);
    const [step, setStep] = useState<number>(0)
    const [stepsList, setStepsList] = useState<any>([
        { title: '欢迎语配置', description: '欢迎语类型、标题、适用产品' },
        { title: '智能标签配置' },
        {
            title: '欢迎语内容', children: [{ title: `内容${1}` }]
        },
        { title: '完成' }
    ])
    /***************************************************/

    // 回填
    useEffect(() => {
        if (value && Object.keys(value).length) {
            setStepsList([
                { title: '欢迎语配置', description: '欢迎语类型、标题、适用产品', checked: true },
                { title: '智能标签配置', checked: true },
                {
                    title: '欢迎语内容', children: value?.mediaContentList?.map((item, index) => {
                        return { title: `内容${index + 1}`, checked: true }
                    })
                },
                { title: '完成', checked: true }
            ])
            // setStep(1)
            form.setFieldsValue(value)
        }
    }, [value])

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

    const filedUpdateChange = () => {
        const { welcomeName, welcomeMsgTagDTO, sendMode, mediaContentList } = form.getFieldsValue()
        const content = mediaContentList?.map((item, index) => {
            return { title: `内容${index + 1}`, checked: item?.length }
        })
        const stepsData = [
            { title: '欢迎语配置', description: '欢迎语类型、标题、适用产品', checked: welcomeName },
            { title: '智能标签配置', checked: welcomeMsgTagDTO && Object.values(welcomeMsgTagDTO).some(item => item) },
            {
                title: '欢迎语内容', children: content, checked: content?.every(item => item.checked) && (sendMode || sendMode === 0)
            },
            {
                title: '完成', checked: welcomeName && (welcomeMsgTagDTO && Object.values(welcomeMsgTagDTO).some(item => item)) && content?.every(item => item.checked) && (sendMode || sendMode === 0)
            }
        ]
        setStepsList(stepsData)
    }


    const isDisabled = () => {
        return step !== 0
    }

    return <Modal
        title={<strong>欢迎语模板配置</strong>}
        open={visible}
        onCancel={onClose}
        width={850}
        onOk={handleOk}
        className={`settingsModal`}
        footer={<Space>
            <Button onClick={onClose}>取消</Button>
            {step === 0 ? <Button type="primary" onClick={() => {
                form.validateFields().then((values) => {
                    setStep(1)
                }).catch(() => {
                    form.submit()
                });
            }}>下一步</Button> : <>
                <Button onClick={() => {
                    setStep(0)
                }}>上一步</Button>
                <Button type="primary" onClick={handleOk}>确定</Button>
            </>}
        </Space>}
    >
        <div className={`body_steps`}>
            <NewSteps
                items={stepsList}
            />
        </div>
        <div className={`body_content`}>
            <Form
                form={form}
                name="newWelcome"
                labelAlign='left'
                labelCol={{ span: 5 }}
                colon={false}
                scrollToFirstError={{
                    behavior: 'smooth',
                    block: 'center'
                }}
                onFinishFailed={({ errorFields }) => {
                    message.error(errorFields?.[0]?.errors?.[0])
                }}
                onFinish={handleOk}
                initialValues={{
                    mediaContentList: [undefined]
                }}
                onFieldsChange={() => {
                    filedUpdateChange()
                }}
                preserve={true}
            >
                <Card title={<strong>基础信息配置</strong>} style={{ background: '#fff', marginBottom: 10 }} id='basicInfo'>
                    <Form.Item label={<strong>欢迎语标题</strong>} name="welcomeName" rules={[{ required: true, message: '请输入标题!' }]}>
                        <Input placeholder="请输入标题" style={{ width: 358 }} allowClear disabled={isDisabled()} />
                    </Form.Item>
                </Card>

                <Card title={<strong>智能标签配置</strong>} style={{ background: '#fff', marginBottom: 10, display: step === 1 ? 'none' : 'block' }} styles={{ body: { padding: '6px 0 6px 16px' } }} id='intelligentLabel'>
                    <Form.Item name="welcomeMsgTagDTO" rules={[{ required: true, message: '请选择智能标签!' }]} style={{ marginBottom: 0 }}>
                        <MindTags disabled={isEditSc} />
                    </Form.Item>
                </Card>

                <Card title={<strong>内容配置</strong>} style={{ background: '#fff', display: step === 0 ? 'none' : 'block' }} id='contentConfig'>
                    <Form.Item label={<strong>内容组发送模式</strong>} name="sendMode" rules={[{ required: step === 0 ? false : true, message: '请选择内容组发送模式!' }]}>
                        <Select
                            showSearch
                            style={{ width: 358 }}
                            allowClear
                            placeholder="请选择内容组发送模式"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                            }
                            options={welcomeContentData}
                        />
                    </Form.Item>
                    <Form.List name="mediaContentList">
                        {(fields, { add, remove }) => (
                            <>
                                {fields.map(({ key, name, ...restField }, index) => {
                                    const mediaContentList = mediaContent?.[index]
                                    let noShowType = []
                                    if (mediaContentList?.find((i: { mediaType: string; }) => i.mediaType === 'text')) {
                                        noShowType = ['text']
                                    } else {
                                        noShowType = []
                                    }
                                    return <div key={key} className={style.content_col}>
                                        <Form.Item
                                            {...restField}
                                            name={name}
                                            rules={[{ required: step === 0 ? false : true, message: '请完善内容!' }]}
                                        >
                                            <MaterialMould noShowType={noShowType} disabledAdd={isEditSc}/>
                                        </Form.Item>
                                        {(mediaContent?.length > 1 && !isEditSc) && <div className={style.remove} onClick={() => remove(name)}>
                                            <MinusCircleOutlined />
                                        </div>}
                                    </div>
                                })}
                                <Form.Item>
                                    <Button type="dashed" onClick={() => add()} block disabled={isEditSc} icon={<PlusOutlined />}>
                                        新增内容组
                                    </Button>
                                </Form.Item>
                            </>
                        )}
                    </Form.List>
                </Card>
            </Form>
        </div>
    </Modal>;
};

export default React.memo(SettingsWelcome);