import New1Radio from "@/pages/launchSystemV3/components/New1Radio"
import TextAideInput from "@/pages/launchSystemV3/components/TextAideInput"
import { txtLength } from "@/utils/utils"
import { Button, Card, Form, Modal, Popconfirm, Space, message } from "antd"
import React, { useEffect, useState } from "react"
import { TextTypeList } from "../../const"
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons"


interface Props {
    textData: any,
    dynamicMaterialDTos: any,
    value?: any,
    visible?: boolean
    onClose?: () => void
    onChange?: (value: any) => void
}

/**
 * 创意文案
 * @param param0 
 * @returns 
 */
const NewText: React.FC<Props> = ({ visible, onClose, onChange, value, textData, dynamicMaterialDTos }) => {

    /*************************************/
    const [form] = Form.useForm();
    const type = Form.useWatch('type', form)
    const textDto = Form.useWatch('textDto', form)

    const [textList, setTextList] = useState<PULLIN.TextDtoProps[]>([])
    /*************************************/

    const handleOk = (values: any) => {
        console.log(values)
        const { type, textDto } = values
        onChange?.({
            type,
            dynamicCreativesTextDetailDTOList: textDto.map((item: any) => {
                let data: any = {}
                Object.keys(item).forEach(key => {
                    data[key] = [item[key]]
                })
                return data
            })
        })
    }

    useEffect(() => {
        console.log('创意文案--->', value)
        if (value && Object.keys(value).length) {
            const { type, dynamicCreativesTextDetailDTOList } = value
            form.setFieldsValue({
                type, textDto: dynamicCreativesTextDetailDTOList.map((item: any) => {
                    let data: any = {}
                    Object.keys(item).forEach(key => {
                        data[key] = item[key]?.[0]
                    })
                    return data
                })
            })
        }
    }, [value])

    useEffect(() => {
        if (textData && Object.keys(textData)) {
            let data = Object.values(textData).map((item: any) => {
                let content = item.children.content
                return { label: content.description, restriction: content.restriction, value: item.name, required: item.required }
            })
            setTextList(data)
        }
    }, [textData])

    return <Modal
        title={<strong style={{ fontSize: 20 }}>创意文案</strong>}
        visible={visible}
        onCancel={onClose}
        footer={null}
        width={800}
        className={`modalResetCss`}
        bodyStyle={{ padding: '0 0 40px', position: 'relative', borderRadius: '0 0 8px 8px' }}
        maskClosable={false}
    >
        <Form
            form={form}
            name="newText"
            labelAlign='left'
            labelCol={{ span: 5 }}
            colon={false}
            style={{ backgroundColor: '#f1f4fc', maxHeight: 650, overflow: 'hidden', overflowY: 'auto', padding: '0 10px 10px', borderRadius: '0 0 8px 8px' }}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            initialValues={{
                type: 0,
                textDto: [{}]
            }}
            onFinish={handleOk}
        >
            <Card className="cardResetCss" style={{ marginTop: 10 }}>
                <Form.Item name="type" label={<strong>文案分配规则</strong>} style={{ marginBottom: 0 }} rules={[{ required: true, message: '请选择营销目的!' }]}>
                    <New1Radio
                        data={TextTypeList}
                        onChange={(value) => {
                            let count = dynamicMaterialDTos.dynamicGroup.length
                            let oldtextDto: PULLIN.TextDtoProps[] = JSON.parse(JSON.stringify(textDto))
                            let length = oldtextDto.length
                            if (value === 0) {
                                oldtextDto = [textDto[0] || {}]
                            } else if (value === 1) {
                                if (count > length) {
                                    oldtextDto = oldtextDto.concat(Array(count - length).fill({}))
                                } else {
                                    oldtextDto = oldtextDto.slice(0, count)
                                }
                            } else if (value === 2) {
                                if (count < length) {
                                    oldtextDto = oldtextDto.slice(0, count)
                                }
                            }
                            form.setFieldsValue({ textDto: oldtextDto })
                        }}
                    />
                </Form.Item>
            </Card>

            <Form.List name="textDto">
                {(fields, { add, remove }) => (<>
                    {fields.map(({ key, name, ...restField }, num) => (
                        <Card
                            title={type === 1 ? <strong style={{ fontSize: 14 }}>创意组{num + 1}</strong> : type === 0 ? null : <strong style={{ fontSize: 14 }}>文案组{num + 1}</strong>}
                            className="cardResetCss"
                            style={{ marginTop: 10 }}
                            key={key}
                        >
                            <Space style={{ display: 'flex' }} align="baseline">
                                <Space style={{ width: '100%' }} direction="vertical" size={10}>
                                    {textList.map(item => {
                                        return <Form.Item
                                            {...restField}
                                            label={<strong>{item.label}</strong>}
                                            name={[name, item.value]}
                                            key={key}
                                            style={{ marginBottom: 0 }}
                                            rules={[{
                                                required: item.required, message: '请输入正确的' + item.label, validator: (rule, value) => {
                                                    if (!value) {
                                                        return Promise.reject()
                                                    } else if (!value.match(RegExp(item.restriction.textRestriction.textPattern))) {
                                                        return Promise.reject()
                                                    } else if (txtLength(value) > item.restriction.textRestriction.maxLength) {
                                                        return Promise.reject()
                                                    }
                                                    return Promise.resolve()
                                                }
                                            }]}
                                        >
                                            <TextAideInput placeholder={'请输入' + item.label} style={{ width: 450 }} maxTextLength={item.restriction.textRestriction.maxLength} />
                                        </Form.Item>
                                    })}
                                </Space>
                                
                                {([3,2].includes(type) && textDto?.length > 1) && <Popconfirm
                                    title="你确定删除当前文案组?"
                                    onConfirm={() => remove(name)}
                                >
                                    <MinusCircleOutlined style={{ marginLeft: 20, color: 'red' }} />
                                </Popconfirm>}
                            </Space>

                        </Card>
                    ))}
                    {[3,2].includes(type) && !(type === 2 && textDto.length >= dynamicMaterialDTos.dynamicGroup.length) && <Form.Item style={{ marginTop: 10, marginBottom: 0 }}>
                        <Button type="dashed" onClick={() => add({})} block icon={<PlusOutlined />} disabled={type === 3 && textDto.length >= 30}>
                            新增
                        </Button>
                    </Form.Item>}
                </>)}
            </Form.List>
            <Form.Item className="submit_pull">
                <Space>
                    <Button onClick={onClose}>取消</Button>
                    <Button type="primary" htmlType="submit" className="modalResetCss">
                        确定
                    </Button>
                </Space>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(NewText)