import { Button, Card, Form, Radio, Space, Tooltip } 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";
import { PAGE_TYPE_ENUM } from "../../const";


/**
 * 创意内容
 * @returns 
 */
const CreativeTemplateContent: React.FC<{ automaticSiteEnabled: boolean, putInType?: 'NOVEL' | 'GAME' }> = ({ automaticSiteEnabled, putInType }) => {

    /******************************************/
    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 creativeTemplateId = Form.useWatch('creativeTemplateId', form)
    const linkNameTypeOld = Form.useWatch(['textLink', 'value', 'linkNameType'], form)
    const buttonTextOld = Form.useWatch(['actionButton', 'value', 'buttonText'], 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", "PAGE_TYPE_WECHAT_CHANNELS_PROFILE"]
                    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", "PAGE_TYPE_OFFICIAL", "PAGE_TYPE_WECHAT_MINI_PROGRAM", "PAGE_TYPE_WECHAT_MINI_GAME"].includes(item.value) }))
                    break
            }
        })

        if (!pageTypeList.some(item => item.value === "PAGE_TYPE_OFFICIAL") && creativeTemplateId !== 910 && putInType !== 'GAME') {
            pageTypeList.push({ label: "灵鹊落地页", value: "PAGE_TYPE_OFFICIAL", disabled: false })
        }

        return <>
            {brand && <Form.Item style={{ marginBottom: 0 }}>
                <Form.Item name={['jumpInfo', 'pageType']} label={<strong>品牌形象跳转</strong>} rules={[{ required: true, message: '请选择品牌形象跳转!' }]} tooltip="品牌形象将在各流量版位下广告外层创意展示。此外，朋友圈广告在此基础上支持跳转，点击品牌形象可跳转到品牌简介页或搜一搜品牌主页">
                    <New1Radio data={enumeration} onChange={() => form.setFieldsValue({ brand: undefined, creativeFirstReplyDTO: undefined })} />
                </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 }, index) => (
                                <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: '请选择跳转类型!' }]}
                                            help={'注意"灵鹊落地页（官方落地页）"该类型需要申请权限'}
                                            validateStatus="warning"
                                        >
                                            <New1Radio
                                                data={pageTypeList}
                                                onChange={(pageType) => {
                                                    let pageSpecNew: any = []
                                                    if (pageType === 'PAGE_TYPE_WECHAT_CANVAS') {
                                                        pageSpecNew = pageSpec.map(() => ({ pageType, overrideCanvasHeadOption: 'OPTION_CREATIVE_OVERRIDE_CANVAS' }))
                                                    } else {
                                                        pageSpecNew = pageSpec.map(() => ({ pageType }))
                                                    }
                                                    form.setFieldsValue({ pageSpec: pageSpecNew })
                                                    let values: any = {}
                                                    Object.keys(creativeComponents).forEach(key => {
                                                        switch (key) {
                                                            case 'text_link':// 朋友圈文字链
                                                                let textLink = creativeComponents[key]
                                                                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 }))
                                                                values.textLink = {
                                                                    value: {
                                                                        linkNameType: linkNameTypeOld || linkNameEnumeration?.[0]?.value,
                                                                        jumpInfo: {
                                                                            pageType: pageType
                                                                        }
                                                                    }
                                                                }
                                                                break
                                                            case 'action_button':
                                                                let actionButton = creativeComponents[key]
                                                                let buttonText = actionButton.children.button_text
                                                                let butttonTextEnumeration = (buttonText.enumProperty.enumeration as { value: string }[]).map(item => ({ label: item.value, value: item.value }))
                                                                let enumeration = actionButton.children?.page_type?.enumProperty?.enumeration
                                                                let jumpInfo: any = {}
                                                                if (enumeration) {
                                                                    if (enumeration.some((item: { value: any; }) => item.value === pageType)) {
                                                                        jumpInfo = {
                                                                            pageType: pageType
                                                                        }
                                                                    } else {
                                                                        jumpInfo = {
                                                                            pageType: 'PAGE_TYPE_WECHAT_FOCUS_DAILOG'
                                                                        }
                                                                    }
                                                                }
                                                                values.actionButton = {
                                                                    value: {
                                                                        buttonText: buttonTextOld || butttonTextEnumeration?.[0]?.value,
                                                                        jumpInfo
                                                                    }
                                                                }
                                                                if (actionButton.required) {
                                                                    values.actionButtonShow = true
                                                                }
                                                                break
                                                        }
                                                    })
                                                    form.setFieldsValue(values)
                                                }}
                                            />
                                        </Form.Item>
                                        {(((deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' ? siteSet?.some((name: string) => name === 'SITE_SET_MOMENTS') : true) || automaticSiteEnabled) && pageSpec?.[index]?.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 value="OPTION_KEEP_DIFFERENT">不替换原生推广页顶部素材</Radio>
                                                    <Radio 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>
                                {pageSpec?.[0]?.pageType === "PAGE_TYPE_WECHAT_MINI_GAME" ? <Tooltip placement="top" title={`「${PAGE_TYPE_ENUM[pageSpec?.[0]?.pageType as keyof typeof PAGE_TYPE_ENUM]}」仅支持单独使用，如需添加多组，请修改跳转类型。`}>
                                    <Button type="dashed" disabled block icon={<PlusOutlined />}>
                                        还可以添加 {jumpInfoNumber - pageSpec?.length} 组
                                    </Button>
                                </Tooltip> : <Button type="dashed" onClick={() => add({ pageId: null, pageType: pageSpec?.[0]?.pageType || 'PAGE_TYPE_WECHAT_CANVAS', overrideCanvasHeadOption: pageSpec?.[0]?.overrideCanvasHeadOption || 'OPTION_CREATIVE_OVERRIDE_CANVAS' })} block icon={<PlusOutlined />}>
                                    还可以添加 {jumpInfoNumber - pageSpec?.length} 组
                                </Button>}
                            </Form.Item>}
                        </>
                    )}
                </Form.List>
            </Form.Item>
        </>
    }, [creativeComponents, pageType, pageSpec, siteSet, creativeTemplateId, putInType])

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


export default React.memo(CreativeTemplateContent)