import { OptimizationGoalEnum, SiteSetEnum } from "@/services/launchAdq/enum"
import { EditOutlined } from "@ant-design/icons"
import { Button, InputNumber, Space } from "antd"
import React, { useEffect, useRef, useState } from "react"
import './index.less'

interface Props {
    value?: { siteSet: string[], bidCoefficient?: number, deepBidCoefficient?: number }[],   // 版位
    bidAmount: number,   // 出价
    onChange?: (data: any[]) => void,
    deepConversionType?: string,  // DEEP_CONVERSION_BEHAVIOR 优化转化行为  DEEP_CONVERSION_WORTH 优化 ROI  BID_MODE 出价
    goal?: string,
    optimizationGoal?: string,
    children?: JSX.Element
}
/**
 * 分版位深度目标出价
 * @returns 
 */
const BidAdjustment: React.FC<Props> = (props) => {

    /*****************************/
    const { bidAmount, value, onChange, deepConversionType, goal, optimizationGoal, children } = props
    const [tableData, setTableData] = useState<{ siteSet: string[], bidCoefficient?: number, deepBidCoefficient?: number, bidAmount: number | string, openEditBid: boolean }[]>([])
    const [bidModeName, setBidModeName] = useState<string>('')
    const ref: { current: any } = useRef(null)
    /*****************************/

    // 处理表格数据
    useEffect(() => {
        if (value && deepConversionType) {
            setTableData(value?.map((item: any, index) => {
                if (deepConversionType === 'BID_MODE') {
                    return { ...item, bidAmount: bidAmount ? (item.bidCoefficient * bidAmount).toFixed(3) : '--', openEditBid: tableData[index]?.openEditBid || false }
                } else {
                    return { ...item, bidAmount: bidAmount ? (item.deepBidCoefficient * bidAmount).toFixed(3) : '--', openEditBid: tableData[index]?.openEditBid || false }
                }
            }))
        } else {
            setTableData([])
        }
    }, [value, deepConversionType, bidAmount])

    // 处理名称
    useEffect(() => {
        switch (deepConversionType) {
            case 'DEEP_CONVERSION_BEHAVIOR':
                setBidModeName(`深度目标出价（元/${goal ? OptimizationGoalEnum[goal] : '优化目标'}）`)
                break
            case 'DEEP_CONVERSION_WORTH':
                setBidModeName(`期望ROI (首日付费ROI)`)
                break
            case 'BID_MODE':
                setBidModeName(`出价（元/${optimizationGoal ? OptimizationGoalEnum[optimizationGoal] : ''}）`)
                break
        }
    }, [deepConversionType, goal])

    // 设置系数
    const setCoefficient = (num: number, index: number) => {
        let data: any[] = []
        if (deepConversionType === 'BID_MODE') {
            data = tableData?.map((item, index1) => {
                if (index === index1) {
                    return { ...item, bidCoefficient: num, bidAmount: (bidAmount * num).toFixed(3) }
                } else {
                    return item
                }
            })
        } else {
            data = tableData?.map((item, index1) => {
                if (index === index1) {
                    return { ...item, deepBidCoefficient: num, bidAmount: (bidAmount * num).toFixed(3) }
                } else {
                    return item
                }
            })
        }
        setTableData(data)
        onChange && onChange(data?.map(item => ({ siteSet: item.siteSet, bidCoefficient: item.bidCoefficient, deepBidCoefficient: item.deepBidCoefficient })))
    }
    // 设置价格
    const setBidAmount = (amount: number, index: number) => {
        let data: any[] = []
        if (deepConversionType === 'BID_MODE') {
            let newBidCoefficient = amount / bidAmount
            if (newBidCoefficient < 0.01) {
                newBidCoefficient = 0.01
            } else if (newBidCoefficient > 5) {
                newBidCoefficient = 5
            }
            newBidCoefficient = Math.round(newBidCoefficient * 100) / 100
            data = tableData?.map((item, index1) => {
                if (index === index1) {
                    return { ...item, bidCoefficient: newBidCoefficient, bidAmount: (bidAmount * newBidCoefficient).toFixed(3) }
                } else {
                    return item
                }
            })

        } else {
            let newDeepBidCoefficient = amount / bidAmount
            if (newDeepBidCoefficient < 0.01) {
                newDeepBidCoefficient = 0.01
            } else if (newDeepBidCoefficient > 5) {
                newDeepBidCoefficient = 5
            }
            newDeepBidCoefficient = Math.round(newDeepBidCoefficient * 100) / 100
            data = tableData?.map((item, index1) => {
                if (index === index1) {
                    return { ...item, deepBidCoefficient: newDeepBidCoefficient, bidAmount: (bidAmount * newDeepBidCoefficient).toFixed(3) }
                } else {
                    return item
                }
            })
        }
        setTableData(data)
        onChange && onChange(data?.map(item => ({ siteSet: item.siteSet, bidCoefficient: item.bidCoefficient, deepBidCoefficient: item.deepBidCoefficient })))
    }

    // 设置出价
    const setOpenEditBid = (index: number) => {
        setTableData(tableData?.map((item, index1) => {
            if (index === index1) {
                if (item.openEditBid) {
                    ref.current = null
                } else {
                    setTimeout(() => {
                        ref.current?.focus()
                    }, 100)
                }
                return { ...item, openEditBid: !item.openEditBid }
            } else {
                return item
            }
        }))
    }

    return <div>
        <div className="myTable">
            <div className="tableUl" style={{ height: 40 }}>
                <div>广告版位组合</div>
                <div>系数 (0.01~5)</div>
                <div style={{ textAlign: 'right' }}>{bidModeName}</div>
            </div>
            {tableData?.map((item, index) => {
                return <div className="tableUl tr" key={'table' + index}>
                    <div>
                        {item?.siteSet?.map(item => <div key={item}>{SiteSetEnum[item]}</div>)}
                    </div>
                    <div className="coefficient">
                        <InputNumber min={0.01} max={5} step={0.1} disabled={!bidAmount} value={deepConversionType === 'BID_MODE' ? item.bidCoefficient : item.deepBidCoefficient} onChange={(e) => setCoefficient(e, index)} />
                        <div className="tips">
                            {((deepConversionType === 'BID_MODE' ? item.bidCoefficient : item.deepBidCoefficient) || 1)?.toString()?.split('.')[1]?.length > 2 ? '系数仅支持2位小数' : ''}
                        </div>
                    </div>
                    <div style={{ textAlign: 'right' }}><Space>
                        {!item.openEditBid ? item.bidAmount : <InputNumber ref={ref} value={Number(item.bidAmount)} onBlur={() => { setOpenEditBid(index) }} onChange={(e) => setBidAmount(e, index)} />}
                        {!item.openEditBid && <Button icon={<EditOutlined />} type='link' onClick={() => { setOpenEditBid(index) }} style={{ padding: 0 }} disabled={!bidAmount}></Button>}
                    </Space></div>
                </div>
            })}
        </div>
        {children && <div style={{ marginTop: 10 }}>{children}</div>}
    </div>
}


export default React.memo(BidAdjustment)