import { useAjax } from "@/Hook/useAjax"
import TimeSeriesLook from "@/pages/launchSystemNew/adq/ad/timeSeriesLook"
import { addAdToRuleBlackListApi, delAdToRuleBlackListApi, delAdWarningRuleApi, getAdgroupDetailsApi } from "@/services/adMonitor/adMonitor"
import { AdStatusEnum, BidModeEnum, BidStrategyEnum, OptimizationGoalEnum, PromotedObjectType } from "@/services/launchAdq/enum"
import { Card, Descriptions, Empty, Popover, Space, Spin, Typography, message } from "antd"
import React, { useEffect, useMemo, useState } from "react"
import TableData from "@/pages/launchSystemNew/components/TableData"
import SetEarlyWarnings from "@/components/EarlyWarning/setEarlyWarnings"
import RuleLog from "@/components/EarlyWarning/ruleLog"
import tableConfigEw from "@/pages/adMonitor/adMonitorList/components/tableConfigEw"
import tableConfig from "../adqv3/creative/tableConfig"

export enum EWTypeEnum {
    DEFAULT = '默认告警规则',
    ACCOUNT = '广告账号告警规则',
    ADGROUP = '广告告警规则',
    ADGROUP_BLACK_LIST = '告警黑名单'
}

interface Props {
    accountId: any
    adgroupId: any
}
const TabAd: React.FC<Props> = ({ accountId, adgroupId }) => {

    /*******************************/
    const [logVisible, setLogVisible] = useState<boolean>(false)
    const [ruleId, setrRleId] = useState<number>(0)
    const [ruleName, setrRuleName] = useState<string>('')

    const getAdgroupDetails = useAjax((params) => getAdgroupDetailsApi(params), { formatResult: true })
    const delAdWarningRule = useAjax((params) => delAdWarningRuleApi(params), { formatResult: true })
    const addAdToRuleBlackList = useAjax((params) => addAdToRuleBlackListApi(params), { formatResult: true })
    const delAdToRuleBlackList = useAjax((params) => delAdToRuleBlackListApi(params), { formatResult: true })
    /*******************************/

    useEffect(() => {
        getAdgroupDetails.run({ adgroupId, accountId })
    }, [adgroupId, accountId])

    const addBlack = (value: any) => {
        console.log(value)
        addAdToRuleBlackList.run({ adgroupId, accountId, ruleId: value.id }).then(res => {
            if (res?.data) {
                message.success('添加成功')
                getAdgroupDetails.refresh()
            }
        })
    }

    const remove = (value: any) => {
        delAdWarningRule.run({ adgroupId, accountId, ruleId: value.id }).then(res => {
            if (res?.data) {
                message.success('移除成功')
                getAdgroupDetails.refresh()
            }
        })
    }

    const removeBlack = (value: any) => {
        delAdToRuleBlackList.run({ adgroupId, accountId, ruleId: value.id }).then(res => {
            if (res?.data) {
                message.success('移出成功')
                getAdgroupDetails.refresh()
            }
        })
    }

    const log = (value: any) => {
        setrRleId(value.id)
        setrRuleName(value.ruleName)
        setLogVisible(true)
    }

    const AdContent = useMemo(() => {
        if (getAdgroupDetails?.data?.data) {
            const { adgroupName, bidAmount, bidMode, optimizationGoal, adgroupId, rejectMessageList, status, smartBidType, beginDate,
                endDate, targetingTranslation, timeSeries, firstDayBeginTime, dailyBudget, bidStrategy, promotedObjectType, accountId,
                creativeName
            } = getAdgroupDetails?.data?.data
            return <Spin spinning={getAdgroupDetails.loading}>
                <Descriptions column={2} size="small" colon={false}>
                    <Descriptions.Item labelStyle={{ width: 100, flex: '0 0 auto' }} label="广告名称">
                        <div style={{ width: '90%' }}>
                            <Typography.Text ellipsis={{ tooltip: true }}>{adgroupName}</Typography.Text>
                        </div>
                    </Descriptions.Item>
                    <Descriptions.Item labelStyle={{ width: 100 }} label="出价">{`${BidModeEnum[bidMode]} ${bidAmount}元/${bidMode === 'BID_MODE_CPM' ? '千次曝光' : bidMode === 'BID_MODE_CPC' ? '点击' : OptimizationGoalEnum[optimizationGoal]}`}</Descriptions.Item>
                    <Descriptions.Item labelStyle={{ width: 100 }} label="广告ID">{adgroupId}</Descriptions.Item>
                    <Descriptions.Item labelStyle={{ width: 100 }} label="状态">
                        {rejectMessageList?.filter((str: any) => str)?.length > 0 ? <Popover
                            style={{ width: 500 }}
                            overlayStyle={{ width: 500, fontSize: 12 }}
                            placement="left"
                            content={rejectMessageList?.map((str: string, eq: number) => {
                                return str ? <><strong style={{ fontSize: 13 }}>{eq + 1}:</strong>{str}<br /></> : ""
                            })}>
                            {AdStatusEnum[status]}
                        </Popover> :
                            AdStatusEnum[status]}
                    </Descriptions.Item>
                    <Descriptions.Item label="广告账号" labelStyle={{ width: 100 }}>{accountId}</Descriptions.Item>
                    <Descriptions.Item label="出价类型" labelStyle={{ width: 100 }}>{smartBidType === 'SMART_BID_TYPE_CUSTOM' ? '手动出价' : '自动出价'}</Descriptions.Item>
                    <Descriptions.Item label="推广目标类型" labelStyle={{ width: 100 }}>{PromotedObjectType[promotedObjectType]}</Descriptions.Item>
                    <Descriptions.Item label="投放日期" labelStyle={{ width: 100 }}>{endDate ? beginDate + '~' + endDate : beginDate + '~' + '长期投放'}</Descriptions.Item>
                    <Descriptions.Item label="定向" labelStyle={{ width: 100 }} span={2}>{targetingTranslation}</Descriptions.Item>
                    <Descriptions.Item label="投放时间" labelStyle={{ width: 100 }}>{<TimeSeriesLook timeSeries={timeSeries} />}</Descriptions.Item>
                    <Descriptions.Item label="首日开始时间" labelStyle={{ width: 100 }}>{firstDayBeginTime}</Descriptions.Item>
                    <Descriptions.Item label="日预算" labelStyle={{ width: 100 }}>{dailyBudget}</Descriptions.Item>
                    <Descriptions.Item label="创意名称" labelStyle={{ width: 100 }}>{creativeName}</Descriptions.Item>
                    <Descriptions.Item label="出价策略" labelStyle={{ width: 100 }}>{BidStrategyEnum[bidStrategy]}</Descriptions.Item>
                </Descriptions>
            </Spin>
        }
        return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
    }, [getAdgroupDetails?.data?.data, getAdgroupDetails.loading])

    console.log(getAdgroupDetails?.data?.data?.dynamicCreativeList)

    const CreativePreview = useMemo(() => {

        return <Card
            hoverable
            style={{ width: '100%' }}
            bodyStyle={{ padding: 16 }}
        >
            <TableData
                size="small"
                isCard={false}
                columns={() => tableConfig()}
                ajax={getAdgroupDetails}
                dataSource={getAdgroupDetails?.data?.data?.dynamicCreativeList || []}
                leftChild={<Space>
                    <strong>创意预览</strong>
                </Space>}
                myKey={'dynamicCreativeId'}
                loading={getAdgroupDetails?.loading}
                total={getAdgroupDetails?.data?.data?.dynamicCreativeList?.length || 0}
                gutter={[0, 10]}
            />
        </Card>
    }, [getAdgroupDetails, getAdgroupDetails?.data?.data, getAdgroupDetails.loading])

    const EWContent = useMemo(() => {
        if (getAdgroupDetails?.data?.data?.warningRuleMap && Object.keys(getAdgroupDetails?.data?.data?.warningRuleMap).length > 0) {
            let data = getAdgroupDetails?.data?.data?.warningRuleMap
            let dataArr = Object.keys(getAdgroupDetails?.data?.data?.warningRuleMap)
            if (!dataArr.includes('ADGROUP')) {
                dataArr.push('ADGROUP')
            }
            return dataArr.map(key => <Card
                hoverable
                style={{ width: '100%' }}
                key={key}
                bodyStyle={{ padding: 16 }}
            >
                <TableData
                    size="small"
                    isCard={false}
                    columns={() => tableConfigEw(key as any, addBlack, remove, removeBlack, log)}
                    ajax={getAdgroupDetails}
                    dataSource={data[key]}
                    leftChild={<Space>
                        <strong>{EWTypeEnum[key]}</strong>
                        {key === 'ADGROUP' && <SetEarlyWarnings accountId={accountId} adgroupId={adgroupId} onChange={() => getAdgroupDetails.refresh()} />}
                    </Space>}
                    loading={getAdgroupDetails?.loading}
                    total={getAdgroupDetails?.data?.data?.length}
                    gutter={[0, 10]}
                />
            </Card>)
        }
        return <Card
            hoverable
            style={{ width: '100%' }}
            bodyStyle={{ padding: 16 }}
        >
            <TableData
                size="small"
                isCard={false}
                columns={() => tableConfigEw('ADGROUP', addBlack, remove, removeBlack, log)}
                ajax={getAdgroupDetails}
                dataSource={[]}
                leftChild={<Space>
                    <strong>{EWTypeEnum['ADGROUP']}</strong>
                    <SetEarlyWarnings accountId={accountId} adgroupId={adgroupId} onChange={() => getAdgroupDetails.refresh()} />
                </Space>}
                loading={getAdgroupDetails?.loading}
                total={getAdgroupDetails?.data?.data?.length}
                gutter={[0, 10]}
            />
        </Card>
    }, [getAdgroupDetails?.data?.data, getAdgroupDetails.loading])

    return <Space style={{ width: '100%' }} direction="vertical">
        <Card
            hoverable
            className="detail_card"
            style={{ width: '100%' }}
        >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px 0' }}>
                <strong>广告</strong>
                <Space align="center">
                    <span style={{ fontSize: 10, color: '#999' }}>刷新时间:{getAdgroupDetails?.data?.reqTime}</span>
                    <a onClick={() => getAdgroupDetails.refresh()} style={{ fontSize: 14 }}>刷新</a>
                </Space>
            </div>
            <div style={{ padding: 16 }}>
                {AdContent}
            </div>
        </Card>
        {CreativePreview}
        {EWContent}

        {logVisible && <RuleLog ruleName={ruleName} ruleId={ruleId} visible={logVisible} onClose={() => setLogVisible(false)} />}
    </Space>
}

export default React.memo(TabAd)