import React, { useContext, useEffect, useState } from "react"
import style from '../index.less'
import { Button, Space, Tag } from "antd"
import { EditOutlined } from "@ant-design/icons"
import { DispatchAddelivery } from ".."
import NewDynamic from "./newDynamic"
import { AD_STATUS_ENUM, CONVERSION_DATA_ENUM, CONVERSION_TARGET_ENUM, DELIVERY_MODE_ENUM, FLOATING_ZONE_TYPE_ENUM, PAGE_TYPE_ENUM, TEXT_LINK_TYPE_ENUM } from "../../const"
import { getProfilesApi } from "@/services/adqV3/global"
import { useAjax } from "@/Hook/useAjax"

/**
 * 创意
 * @returns 
 */
const Dynamic: React.FC<{ creativeTemplateAppellation?: string, creativeTemplateStyle?: string }> = ({ creativeTemplateAppellation, creativeTemplateStyle }) => {

    /***************************************/
    const { addelivery, setAddelivery, clearData, setAccountCreateLogs, accountCreateLogs, putInType, setIsDqSubmit } = useContext(DispatchAddelivery)!;
    const { adgroups, dynamic: dynamicData } = addelivery;
    const { deliveryMode, creativeTemplateId, dynamicCreativeName, creativeComponents, configuredStatus } = dynamicData
    const { textLink, actionButton, showData, brand, mainJumpInfo, floatingZoneComponent, creativeLabelDTOS, creativeBarrageDTOS, creativeFirstReplyDTO } = creativeComponents || {}
    const [newVisible, setNewVisible] = useState<boolean>(false);
    const [profileData, setprofileData] = useState<any>()

    const getProfiles = useAjax((params) => getProfilesApi(params))
    /***************************************/

    useEffect(() => {
        if (['PAGE_TYPE_H5_PROFILE'].includes(brand?.[0]?.value?.jumpInfo?.pageType)) {
            getProfiles.run({}).then(res => {
                if (res) {
                    setprofileData(res?.find((item: { id: any }) => item.id === brand?.[0]?.value?.profileId))
                }
            })
        }
    }, [brand])

    return <div className={`${style.settingsBody_content_row} ${style.row3}`}>
        <div className={style.title}>
            <span>创意信息</span>
        </div>
        <div className={style.detail}>
            <div className={style.detail_body}>
                {dynamicData && Object.keys(dynamicData).length > 0 && <>
                    <p style={{ fontWeight: 'bold', color: configuredStatus === 'AD_STATUS_NORMAL' ? '#52c41a' : '#FF4D4F' }}>创意状态：{AD_STATUS_ENUM[configuredStatus as keyof typeof AD_STATUS_ENUM]}</p>
                    <p>创意名称：{dynamicCreativeName}</p>
                    <p style={{ fontWeight: 'bold', color: '#000' }}>投放模式：{DELIVERY_MODE_ENUM[deliveryMode as keyof typeof DELIVERY_MODE_ENUM]}</p>
                    <p>{((creativeTemplateId && creativeTemplateAppellation) || creativeTemplateId) && `创意形式：${creativeTemplateAppellation || creativeTemplateId}`}</p>
                    {brand?.length > 0 && <>
                        <p style={{ fontWeight: 'bold', color: '#000' }}>品牌形象跳转：{PAGE_TYPE_ENUM[brand?.[0]?.value?.jumpInfo?.pageType as keyof typeof PAGE_TYPE_ENUM]}</p>
                        {['PAGE_TYPE_H5_PROFILE'].includes(brand?.[0]?.value?.jumpInfo?.pageType) ? <>
                            {profileData ? <>
                                <Space>
                                    <img src={profileData?.headImageUrl} alt="" width={20} style={{ display: 'block' }} />
                                    <span style={{ fontWeight: 'bold', color: '#000', fontSize: 12 }}>{profileData?.profileName}</span>
                                </Space>
                                <p>详细描述：{profileData?.description}</p>
                            </> : <span style={{ color: 'red', fontWeight: 'bold', fontSize: 12 }}>{getProfiles.loading ? '' : '当前头像昵称跳转页被删除'} </span>}
                        </> : ['PAGE_TYPE_NOT_USED'].includes(brand?.[0]?.value?.jumpInfo?.pageType) && <Space align="center">
                            <img src={brand?.[0]?.value?.brandImageId} alt="" width={20} style={{ display: 'block' }} />
                            <span style={{ fontWeight: 'bold', color: '#000', fontSize: 12 }}>{brand?.[0]?.value?.brandName}</span>
                        </Space>}
                    </>}
                    <p style={{ fontWeight: 'bold', color: '#000' }}>跳转类型：{mainJumpInfo?.map((item: any) => {
                        let pageType = item.value.pageType
                        return PAGE_TYPE_ENUM[pageType as keyof typeof PAGE_TYPE_ENUM]
                    }).toString()}</p>
                    {textLink?.length > 0 && <>
                        <p style={{ fontWeight: 'bold', color: '#000' }}>朋友圈文字链：开启</p>
                        <p>文字链文案：{TEXT_LINK_TYPE_ENUM[textLink?.[0]?.value?.linkNameType as keyof typeof TEXT_LINK_TYPE_ENUM]}</p>
                        {textLink?.[0]?.value?.jumpInfo?.pageType && <p>跳转落地页：{PAGE_TYPE_ENUM[textLink?.[0]?.value?.jumpInfo?.pageType as keyof typeof PAGE_TYPE_ENUM]}</p>}
                    </>}
                    {actionButton?.length > 0 && <>
                        <p style={{ fontWeight: 'bold', color: '#000' }}>行动按钮：开启</p>
                        <p>按钮文案：{actionButton?.[0]?.value?.buttonText}</p>
                        {actionButton?.[0]?.value?.jumpInfo?.pageType && <p>跳转落地页：{PAGE_TYPE_ENUM[actionButton?.[0]?.value?.jumpInfo?.pageType as keyof typeof PAGE_TYPE_ENUM]}</p>}
                    </>}
                    {creativeLabelDTOS?.length > 0 && <>
                        <p style={{ fontWeight: 'bold', color: '#000' }}>标签：</p>
                        {creativeLabelDTOS.map((item: { content: string }, index: number) => <Tag key={index}>{item.content}</Tag>)}
                    </>}
                    {creativeBarrageDTOS?.length > 0 && <>
                        <p style={{ fontWeight: 'bold', color: '#000' }}>弹幕：</p>
                        {creativeBarrageDTOS.map((item: { text: string }, index: number) => <Tag key={index}>{item.text}</Tag>)}
                    </>}
                    {showData?.length > 0 && <>
                        <p style={{ fontWeight: 'bold', color: '#000' }}>数据外显：开启</p>
                        <p>数据类型：{CONVERSION_DATA_ENUM[showData?.[0]?.value?.conversionDataType as keyof typeof CONVERSION_DATA_ENUM]}</p>
                        <p>转化行为：{CONVERSION_TARGET_ENUM[showData?.[0]?.value?.conversionTargetType as keyof typeof CONVERSION_TARGET_ENUM]}</p>
                    </>}
                    {floatingZoneComponent && Object.keys(floatingZoneComponent).length > 0 && <>
                        <p style={{ fontWeight: 'bold', color: '#000' }}>浮层卡片：{floatingZoneComponent?.floatingZoneSwitch ? '开启' : '关闭'}</p>
                        {floatingZoneComponent?.floatingZoneType && <p>复层卡片类型：{FLOATING_ZONE_TYPE_ENUM[floatingZoneComponent.floatingZoneType as keyof typeof FLOATING_ZONE_TYPE_ENUM]}</p>}
                        {floatingZoneComponent?.floatingZoneImageUrl && <p style={{ display: 'flex', alignItems: 'flex-start' }}>创意图片：<img src={floatingZoneComponent?.floatingZoneImageUrl} width={40} /></p>}
                        {floatingZoneComponent?.floatingZoneSingleImageUrl && <p style={{ display: 'flex', alignItems: 'flex-start' }}>创意图片：<img src={floatingZoneComponent?.floatingZoneSingleImageUrl} width={40} /></p>}
                        {floatingZoneComponent?.floatingZoneName && <p>文案：{floatingZoneComponent.floatingZoneName}</p>}
                        {floatingZoneComponent?.floatingZoneDesc && <p>文案：{floatingZoneComponent.floatingZoneDesc}</p>}
                        {floatingZoneComponent?.floatingZoneButtonText && <p>按钮文案：{floatingZoneComponent.floatingZoneButtonText}</p>}
                    </>}
                    {creativeFirstReplyDTO?.text && <p>首评：{creativeFirstReplyDTO?.text}</p>}
                </>}
            </div>
            <div className={style.detail_footer}>
                <Button disabled={!(adgroups && Object.keys(adgroups)?.length > 0)} type="link" icon={<EditOutlined />} style={{ padding: 0, fontSize: 12 }} onClick={() => setNewVisible(true)}>编辑</Button>
            </div>
        </div>
        
        {/* 添加创意 */}
        {newVisible && <NewDynamic
            visible={newVisible}
            putInType={putInType}
            creativeTemplateStyle={creativeTemplateStyle}
            value={dynamicData}
            onClose={() => {
                setNewVisible(false)
            }}
            onChange={(dynamic) => {
                let oldPageTypeList = mainJumpInfo?.map((item: { value: { pageType: any } }) => item.value) || []
                let newPageTypeList = dynamic?.creativeComponents?.mainJumpInfo.map((item: { value: { pageType: any } }) => item.value)
                if (
                    oldPageTypeList?.[0]?.pageType !== newPageTypeList?.[0]?.pageType || 
                    oldPageTypeList?.length !== newPageTypeList?.length || 
                    (oldPageTypeList?.[0]?.pageType === "PAGE_TYPE_WECHAT_CANVAS" && newPageTypeList?.[0]?.pageType === "PAGE_TYPE_WECHAT_CANVAS" && oldPageTypeList?.[0]?.pageSpec?.wechatCanvasSpec?.overrideCanvasHeadOption !== newPageTypeList?.[0]?.pageSpec?.wechatCanvasSpec?.overrideCanvasHeadOption) ||
                    dynamic.deliveryMode !== deliveryMode || // 投放模式
                    dynamic?.creativeTemplateId !== creativeTemplateId // 创意形式
                ) {
                    setAccountCreateLogs(accountCreateLogs.map(item => ({ ...item, pageList: [] })))
                }
                if (
                    dynamic.deliveryMode === deliveryMode && // 投放模式
                    dynamic?.creativeTemplateId === creativeTemplateId // 创意形式
                ) {
                    setAddelivery({ ...addelivery, dynamic })
                } else {
                    setAddelivery({ ...addelivery, dynamic, dynamicMaterialDTos: {}, dynamicCreativesTextDTOS: {} })
                }
                setNewVisible(false)
                clearData()
                setIsDqSubmit?.(false)
            }}
        />}
    </div>
}

export default React.memo(Dynamic)