import React, { useContext, useEffect, useState } from "react"
import style from '../index.less'
import { Button, Space } 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, PAGE_TYPE_ENUM, TEXT_LINK_TYPE_ENUM, pageSpecFieldConVertUn } from "../../const"
import { getProfilesApi } from "@/services/adqV3/global"
import { useAjax } from "@/Hook/useAjax"
import { arraysHaveSameValues } from "@/utils/utils"

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

    /***************************************/
    const { addelivery, setAddelivery, clearData, setAccountCreateLogs, accountCreateLogs } = useContext(DispatchAddelivery)!;
    const { adgroups, dynamic: dynamicData } = addelivery;
    const { deliveryMode, creativeTemplateId, dynamicCreativeName, creativeComponents, configuredStatus } = dynamicData
    const { textLink, actionButton, showData, brand, mainJumpInfo } = 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>}
                    </>}
                    {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>
                    </>}
                </>}
            </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}
            creativeTemplateStyle={creativeTemplateStyle}
            value={dynamicData}
            onClose={() => {
                setNewVisible(false)
            }}
            onChange={(dynamic) => {
                if (
                    dynamic.deliveryMode === deliveryMode && // 投放模式
                    dynamic?.creativeTemplateId === creativeTemplateId // 创意形式
                ) {
                    setAddelivery({ ...addelivery, dynamic })
                } else {
                    setAddelivery({ ...addelivery, dynamic, dynamicMaterialDTos: {}, dynamicCreativesTextDTOS: {} })
                }
                let oldPageTypeList = mainJumpInfo?.map((item: { value: { pageType: any } }) => item.value) || []
                let newPageTypeList = dynamic?.creativeComponents?.mainJumpInfo.map((item: { value: { pageType: any } }) => item.value)
                setNewVisible(false)
                clearData()
                if (!arraysHaveSameValues(oldPageTypeList || [], newPageTypeList || [])) {
                    setAccountCreateLogs(accountCreateLogs.map(item => ({ ...item, pageList: [] })))
                }
            }}
        />}
    </div>
}

export default React.memo(Dynamic)