import { InputNumber, message, Modal, Radio, Space, Switch, Table, Tooltip } from "antd"
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import style from './index.less'
import { InfoCircleFilled, QuestionCircleOutlined } from "@ant-design/icons"
import { updateBatchAdgroupInfoApi } from "@/services/launchAdq/adqv3"
import { useAjax } from "@/Hook/useAjax"

interface Props {
    selectAdList: any[]
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}

/**
 * 批量一键起量
 * @param param0 
 * @returns 
 */
const AutoAcquisitionSet: React.FC<Props> = ({ selectAdList, visible, onChange, onClose }) => {

    /****************************************/
    const [autoAcquisitionData, setAutoAcquisitionData] = useState<{ autoAcquisitionEnabled: boolean, autoAcquisitionBudget?: number, autoAcquisitionBudgetPercent?: number }>({ autoAcquisitionEnabled: false })
    const [isPercent, setIsPercent] = useState<boolean>(false)
    const [addType, setAddType] = useState<'fixed' | 'percent'>('fixed')
    const updateBatchAdgroupInfo = useAjax((params) => updateBatchAdgroupInfoApi(params)) // 名称
    const [failIdList, setFailIdList] = useState<{ adgroupId: number, code: number, message: string, messageCn: string }[]>([])
    const [failVisible, setFailVisible] = useState<boolean>(false)
    /****************************************/

    useEffect(() => {
        if (selectAdList.every(item => item.autoAcquisitionEnabled)) {
            setIsPercent(true)
        } else {
            setIsPercent(false)
        }
    }, [selectAdList])

    const handleOk = () => {
        let params = { ...autoAcquisitionData }
        if (params?.autoAcquisitionEnabled) {
            if (addType === 'fixed' && !params?.autoAcquisitionBudget) {
                message.error('请填写起量预算')
                return
            }
            if (addType === 'percent' && !params?.autoAcquisitionBudgetPercent) {
                message.error('请填写起量预算百分比')
                return
            }
        }

        if (params?.autoAcquisitionBudgetPercent !== null && params?.autoAcquisitionBudgetPercent !== undefined) params.autoAcquisitionBudgetPercent = params?.autoAcquisitionBudgetPercent / 100
        let accountAdgroupMaps = [...new Set(selectAdList?.map(item => item.accountId + ',' + item.adgroupId))]
        updateBatchAdgroupInfo.run({ accountAdgroupMaps, ...params }).then(res => {
            if (res?.failIdList?.length === 0) {
                message.success(`修改操作完成！`)
                onChange?.()
            } else {
                setFailIdList(res?.list || [])
                setFailVisible(true)
            }
        })
        console.log(params)
    }

    return <Modal
        title={<strong>批量修改一键起量</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        className='modalResetCss'
        width={750}
        confirmLoading={updateBatchAdgroupInfo.loading}
    >
        <div className={style.autoAcquisitionSet}>
            <div className={style.left}>
                <Table
                    dataSource={selectAdList}
                    size="small"
                    scroll={{ x: 400, y: 450 }}
                    bordered
                    rowKey={'adgroupId'}
                    pagination={false}
                    columns={[
                        {
                            title: '广告名称',
                            dataIndex: 'adgroupName',
                            key: 'adgroupName',
                            width: 200,
                            render(value) {
                                return <span style={{ wordBreak: 'break-all' }}>{value}</span>
                            },
                        },
                        {
                            title: '原设置',
                            dataIndex: 'beforeSet',
                            key: 'beforeSet',
                            width: 120,
                            render(value, record) {
                                if (!record?.autoAcquisitionEnabled) {
                                    return '未开启'
                                }
                                return `一键起量中，起量预算：${record?.autoAcquisitionBudget} 元`
                            },
                        }
                    ]}
                />
            </div>
            <div className={style.right}>
                <div className={style.header}>
                    <Space>
                        <span>修改一键起量</span>
                        <Tooltip title={<div>
                            <p>1. 一键起量期间产生的消耗不赔付，但转化计入赔付门槛判断；</p>
                            <p>2. 一键起量可能导致转化成本高于预期，且起量结束后不一定能持续消耗。</p>
                        </div>}>
                            <QuestionCircleOutlined />
                        </Tooltip>
                    </Space>
                </div>
                <div className={style.edit}>
                    <div>
                        <div className={style.tips}>
                            <InfoCircleFilled style={{ color: '#296BEF', marginTop: 2 }} />
                            {
                                autoAcquisitionData?.autoAcquisitionEnabled ?
                                    // '对于状态为“一键起量中”、“一键起量完成”、“一键起量中止”的广告，将会自动关闭一键起量，同时按照新的起量预算重新开启一键起量'
                                    '开启一键起量'
                                    :
                                    '当前开关为关闭状态，点击「确定」将默认关闭已选广告的一键起量功能'
                            }
                        </div>
                        <div>
                            <Switch
                                checkedChildren="开启"
                                unCheckedChildren="未开启"
                                onChange={(e) => {
                                    setAutoAcquisitionData({ ...autoAcquisitionData, autoAcquisitionEnabled: e })
                                }}
                                checked={autoAcquisitionData?.autoAcquisitionEnabled}
                            />
                        </div>
                        {autoAcquisitionData?.autoAcquisitionEnabled && <>
                            <Radio.Group buttonStyle="solid" value={addType} onChange={(e) => setAddType(e.target.value)}>
                                <Radio.Button value="fixed">固定值</Radio.Button>
                                <Radio.Button value="percent" disabled={!isPercent}>百分比上下浮动修改</Radio.Button>
                            </Radio.Group>
                            {addType === 'fixed' ?
                                <InputNumber placeholder="起量预算，建议设置为出价的10倍" min={200} max={100000} style={{ width: '100%' }} value={autoAcquisitionData?.autoAcquisitionBudget} onChange={(e) => setAutoAcquisitionData({ autoAcquisitionEnabled: true, autoAcquisitionBudget: e || 0 })} />
                                :
                                <InputNumber placeholder="起量预算，原有基础上下调百分比" style={{ width: '100%' }} addonAfter="%" value={autoAcquisitionData?.autoAcquisitionBudgetPercent} onChange={(e) => setAutoAcquisitionData({ autoAcquisitionEnabled: true, autoAcquisitionBudgetPercent: e || 0 })} />
                            }
                        </>}
                    </div>
                </div>
            </div>
        </div>

        {failVisible && <Modal
            title={<strong>报错信息</strong>}
            open={failVisible}
            className='modalResetCss'
            width={650}
            onCancel={() => { setFailVisible(false); setFailIdList([]) }}
            footer={null}
        >
            <Table
                size="small"
                bordered
                rowKey={'adgroupId'}
                columns={[{
                    title: '广告ID',
                    dataIndex: 'adgroupId',
                    key: 'adgroupId',
                    width: 110,
                    render: (value) => <span style={{ fontSize: 12 }}>{value}</span>,
                }, {
                    title: 'code',
                    dataIndex: 'code',
                    key: 'code',
                    width: 70,
                    align: 'center',
                    render: (value) => <span style={{ fontSize: 12 }}>{value}</span>,
                }, {
                    title: '错误信息',
                    dataIndex: 'messageCn',
                    key: 'messageCn',
                    render: (value) => <span style={{ fontSize: 12 }}>{value}</span>,
                }]}
                dataSource={failIdList}
            />
        </Modal>}
    </Modal>
}

export default React.memo(AutoAcquisitionSet)