import { Button, Card, Form, Radio, Space } from "antd"
import React, { useContext, useMemo } from "react"
import { DispatchDynamic } from "./newDynamic";
import New1Radio from "@/pages/launchSystemV3/components/New1Radio";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import BrandImage from "@/pages/launchSystemV3/components/BrandImage";
import { SelectProfiles } from "@/pages/launchSystemV3/tencenTasset/profiles";


/**
 * 创意内容
 * @returns 
 */
const CreativeTemplateContent: React.FC<{ automaticSiteEnabled: boolean }> = ({ automaticSiteEnabled }) => {

    /******************************************/
    const { creativeComponents, form, adgroups: { siteSet } } = useContext(DispatchDynamic)!;
    const pageType = Form.useWatch(['jumpInfo', 'pageType'], form)
    const pageSpec = Form.useWatch('pageSpec', form)
    const deliveryMode = Form.useWatch('deliveryMode', form)
    const linkName = Form.useWatch(['textLink', 'value', 'linkName'], form)
    /******************************************/

    const content = useMemo(() => {
        let brand;
        let enumeration: PULLIN.DataType[] = []
        let pageTypeList: PULLIN.DataType[] = []
        let jumpInfoNumber = 1
        Object.keys(creativeComponents).forEach(key => {
            switch (key) {
                case 'brand':
                    brand = creativeComponents[key]
                    let page_type = brand.children.page_type
                    let typeList = ["PAGE_TYPE_WECHAT_OFFICIAL_ACCOUNT_DETAIL", "PAGE_TYPE_H5_PROFILE", "PAGE_TYPE_NOT_USED"]
                    enumeration = (page_type.enumProperty.enumeration as { value: string, description: string }[]).filter((item: { value: string; }) => typeList.includes(item.value)).map(item => ({ label: item.value === 'PAGE_TYPE_NOT_USED' ? '品牌形象' : item.description, value: item.value }))
                    break
                case 'jump_info':
                    let jump_info = creativeComponents[key]
                    jumpInfoNumber = jump_info?.arrayProperty?.maxNumber || 1
                    let jumpInfoPageType = jump_info.children.page_type
                    pageTypeList = (jumpInfoPageType.enumProperty.enumeration as { value: string, description: string }[]).filter(item => !["PAGE_TYPE_WECHAT_CANVAS_MINI_PROGRAM", "PAGE_TYPE_H5", "PAGE_TYPE_WECHAT_SIMPLE_CANVAS", "PAGE_TYPE_APP_DEEP_LINK"].includes(item.value)).map(item => ({ label: item.description, value: item.value, disabled: "PAGE_TYPE_WECHAT_CANVAS" !== item.value }))
                    break
            }
        })

        return <>
            {brand && <Form.Item style={{ marginBottom: 0 }}>
                <Form.Item name={['jumpInfo', 'pageType']} label={<strong>品牌形象跳转</strong>} rules={[{ required: true, message: '请选择品牌形象跳转!' }]} tooltip="品牌形象将在各流量版位下广告外层创意展示。此外，朋友圈广告在此基础上支持跳转，点击品牌形象可跳转到品牌简介页或搜一搜品牌主页">
                    <New1Radio data={enumeration} />
                </Form.Item>
                {['PAGE_TYPE_H5_PROFILE'].includes(pageType) ? <div style={{ margin: '0 0 10px', backgroundColor: '#fafafb', padding: '8px 16px 8px', borderRadius: 8 }}>
                    <Form.Item name='brand' style={{ marginBottom: 0 }} rules={[{ required: true, message: '请选择一个头像及昵称跳转页，与广告创意一起展示' }]}>
                        <SelectProfiles />
                    </Form.Item>
                </div> : ["PAGE_TYPE_NOT_USED"].includes(pageType) && <div style={{ margin: '0 0 10px', backgroundColor: '#fafafb', padding: '8px 16px 8px', borderRadius: 8 }}>
                    <Form.Item name='brand' style={{ marginBottom: 0 }} rules={[{ required: true, message: '请选择一个品牌形象，与广告创意一起展示' }]}>
                        <BrandImage />
                    </Form.Item>
                </div>}
            </Form.Item>}
            <Form.Item style={{ marginBottom: 0 }} label={<strong>跳转类型（{pageSpec?.length || 1}/{jumpInfoNumber}）</strong>}>
                <Form.List name="pageSpec">
                    {(fields, { add, remove }) => (
                        <>
                            {fields.map(({ key, name, ...restField }) => (
                                <Space key={key} style={{ display: 'flex', marginBottom: 8, width: '100%' }} align="baseline">
                                    <Space direction="vertical" style={{ width: '100%' }}>
                                        <Form.Item
                                            {...restField}
                                            name={[name, 'pageType']}
                                            style={{ marginBottom: 0 }}
                                            rules={[{ required: true, message: '请选择跳转类型!' }]}
                                        >
                                            <New1Radio
                                                data={pageTypeList}
                                                onChange={(pageType) => {
                                                    form.setFieldsValue({ pageSpec: pageSpec.map((item: any) => ({ ...item, pageType })) })
                                                    if (Object.keys(creativeComponents).includes('text_link')) {
                                                        let textLink = creativeComponents['text_link']
                                                        let linkNameType = textLink?.children?.link_name_type
                                                        let linkNameEnumeration = (linkNameType?.enumProperty?.enumeration as { value: string, description: string }[]).map(item => ({ label: item.description, value: item.value + '_' + item.description }))
                                                        form.setFieldsValue({
                                                            textLink: {
                                                                value: {
                                                                    linkName: linkName || linkNameEnumeration?.[0]?.value,
                                                                    jump_info: {
                                                                        pageType: pageType
                                                                    }
                                                                }
                                                            }
                                                        })
                                                    }
                                                }}
                                            />
                                        </Form.Item>
                                        {((siteSet?.some((name: string) => name === 'SITE_SET_MOMENTS') || automaticSiteEnabled) && pageSpec?.[key]?.pageType === 'PAGE_TYPE_WECHAT_CANVAS') && <div style={{ margin: 0, backgroundColor: '#fafafb', padding: '8px 16px 8px', borderRadius: 8 }}>
                                            <Form.Item
                                                name={[name, 'overrideCanvasHeadOption']}
                                                style={{ marginBottom: 0 }}
                                            >
                                                <Radio.Group>
                                                    {deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' && <Radio value="OPTION_KEEP_DIFFERENT">不替换原生推广页顶部素材</Radio>}
                                                    <Radio disabled={deliveryMode === 'DELIVERY_MODE_COMPONENT'} value="OPTION_CREATIVE_OVERRIDE_CANVAS">使用外层创意素材替换原生推广页顶部素材</Radio>
                                                </Radio.Group>
                                            </Form.Item>
                                        </div>}
                                    </Space>
                                    {pageSpec?.length > 1 && <MinusCircleOutlined onClick={() => remove(name)} />}
                                </Space>
                            ))}
                            {pageSpec?.length < jumpInfoNumber && <Form.Item>
                                <Button type="dashed" disabled onClick={() => add({ pageType: pageSpec?.[0]?.pageType || 'PAGE_TYPE_WECHAT_CANVAS', overrideCanvasHeadOption: 'OPTION_CANVAS_OVERRIDE_CREATIVE' })} block icon={<PlusOutlined />}>
                                    还可以添加 {jumpInfoNumber - pageSpec?.length} 组
                                </Button>
                            </Form.Item>}
                        </>
                    )}
                </Form.List>
            </Form.Item>


        </>
    }, [creativeComponents, pageType, pageSpec, siteSet])

    return <Card
        title={<strong style={{ fontSize: 18 }}>创意内容</strong>}
        className="cardResetCss"
    >
        {content}
    </Card>
}


export default React.memo(CreativeTemplateContent)