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

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 getAdgroupsDetails = useAjax((params) => getAdgroupsDetailsApi(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(() => {
        getAdgroupsDetails.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('添加成功')
                getAdgroupsDetails.refresh()
            }
        })
    }

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

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

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

    const AdContent = useMemo(() => {
        if (getAdgroupsDetails?.data?.data) {
            const { adgroupName, bidAmount, bidMode, optimizationGoal, adgroupId, rejectMessageList, status, smartBidType, beginDate,
                endDate, targetingTranslation, timeSeries, firstDayBeginTime, dailyBudget, bidStrategy, promotedObjectType, accountId,
                creativeName, creativePreview
            } = getAdgroupsDetails?.data?.data
            return <Spin spinning={getAdgroupsDetails.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.Item label="创意预览" labelStyle={{ width: 100 }}><div style={{ width: 50, height: 22 }}>{<Box b={{ creativePreview }} />}</div></Descriptions.Item>
                </Descriptions>
            </Spin>
        }
        return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
    }, [getAdgroupsDetails?.data?.data, getAdgroupsDetails.loading])

    const EWContent = useMemo(() => {

        if (getAdgroupsDetails?.data?.data?.warningRuleMap && Object.keys(getAdgroupsDetails?.data?.data?.warningRuleMap).length > 0) {
            let data = getAdgroupsDetails?.data?.data?.warningRuleMap
            let dataArr = Object.keys(getAdgroupsDetails?.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={getAdgroupsDetails}
                    dataSource={data[key]}
                    leftChild={<Space>
                        <strong>{EWTypeEnum[key]}</strong>
                        {key === 'ADGROUP' && <SetEarlyWarnings accountId={accountId} adgroupId={adgroupId} onChange={() => getAdgroupsDetails.refresh()} />}
                    </Space>}
                    loading={getAdgroupsDetails?.loading}
                    total={getAdgroupsDetails?.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={getAdgroupsDetails}
                dataSource={[]}
                leftChild={<Space>
                    <strong>{EWTypeEnum['ADGROUP']}</strong>
                    <SetEarlyWarnings accountId={accountId} adgroupId={adgroupId} onChange={() => getAdgroupsDetails.refresh()} />
                </Space>}
                loading={getAdgroupsDetails?.loading}
                total={getAdgroupsDetails?.data?.data?.length}
                gutter={[0, 10]}
            />
        </Card>
    }, [getAdgroupsDetails?.data?.data, getAdgroupsDetails.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' }}>刷新时间:{getAdgroupsDetails?.data?.reqTime}</span>
                    <a onClick={() => getAdgroupsDetails.refresh()} style={{ fontSize: 14 }}>刷新</a>
                </Space>
            </div>
            <div style={{ padding: 16 }}>
                {AdContent}
            </div>
        </Card>
        {EWContent}

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

export default React.memo(TabAd)