import { useAjax } from "@/Hook/useAjax"
import TimeSeriesLook from "@/pages/launchSystemNew/adq/ad/timeSeriesLook"
import { addAdToRuleBlackListApi, delAdToRuleBlackListApi, delAdWarningRuleApi, getAdgroupDetailsApi } from "@/services/adMonitor/adMonitor"
import { BidModeEnum, BidStrategyEnum, OptimizationGoalEnum } from "@/services/launchAdq/enum"
import { Card, Descriptions, Empty, 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"
import { ADGROUP_STATUS } from "../adqv3/const"
import ReviewDetails from "../adqv3/creative/reviewDetails"

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 [dynimicData, setDynamicData] = useState<any>({})
    const [dynimicVisible, setDynamicVisible] = useState<boolean>(false)

    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, systemStatus, smartBidType, beginDate,
                endDate, targetingTranslation, timeSeries, firstDayBeginTime, dailyBudget, bidStrategy, 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 as keyof typeof BidModeEnum]} ${bidAmount}元/${bidMode === 'BID_MODE_CPM' ? '千次曝光' : bidMode === 'BID_MODE_CPC' ? '点击' : OptimizationGoalEnum[optimizationGoal as keyof typeof OptimizationGoalEnum]}`}</Descriptions.Item>
                    <Descriptions.Item labelStyle={{ width: 100 }} label="广告ID">{adgroupId}</Descriptions.Item>
                    <Descriptions.Item labelStyle={{ width: 100 }} label="状态">
                        {ADGROUP_STATUS[systemStatus as keyof typeof ADGROUP_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 }}>{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 as keyof typeof BidStrategyEnum]}</Descriptions.Item>
                </Descriptions>
            </Spin>
        }
        return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
    }, [getAdgroupDetails?.data?.data, getAdgroupDetails.loading])

    const reviewStatusDetails = (value: any) => {
        setDynamicData(value)
        setDynamicVisible(true)
    }

    const CreativePreview = useMemo(() => {

        return <Card
            hoverable
            style={{ width: '100%' }}
            bodyStyle={{ padding: 16 }}
        >
            <TableData
                size="small"
                isCard={false}
                columns={() => tableConfig(reviewStatusDetails)}
                ajax={getAdgroupDetails}
                dataSource={getAdgroupDetails?.data?.data?.dynamicCreativeList || []}
                leftChild={<Space>
                    <strong>创意预览</strong>
                </Space>}
                scroll={{ y: 500 }}
                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 as keyof typeof EWTypeEnum]}</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)} />}
        {dynimicVisible && <ReviewDetails
            visible={dynimicVisible}
            dynamic={dynimicData}
            onClose={() => {
                setDynamicData({})
                setDynamicVisible(false)
            }}
        />}
    </Space>
}

export default React.memo(TabAd)