
import Tables from "@/components/Tables"
import { useAjax } from "@/Hook/useAjax"
import { getAdqLandingPageList, putAdqLandingPage } from "@/services/launchAdq/adq"
import { CheckOutlined, QuestionCircleOutlined, SyncOutlined } from "@ant-design/icons"
import { Button, Input, message, Modal, Space, Tooltip } from "antd"
import React, { useEffect, useState } from "react"
import style from '../goodsModal/index.less'
import columns from "./tableConfig"


/**
 * 获取adq落地页
 * @returns 
 */
interface Props {
    cloudParams: { adcreativeTemplateId?: number }
    visible?: boolean,
    onClose?: () => void,
    onChange?: (data: any) => void,
    data: any
}
const PageModal: React.FC<Props> = (props) => {

    /*************************/
    const { cloudParams, visible, onClose, data: data1, onChange } = props
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [data, setData] = useState<any>(data1 || [])
    const [queryForm, setQueryForm] = useState<{ accountId?: number, pageName?: string, pageSize: number, pageNum: number }>({ pageNum: 1, pageSize: 20 })
    const [loading, setLoading] = useState<boolean>(false)

    const listAjax = useAjax((params) => getAdqLandingPageList(params))
    /*************************/

    useEffect(() => {
        if (data?.length > 0) {
            setQueryForm({ ...queryForm, pageNum: 1, accountId: data[selectAdz - 1].adAccountId })
        }
    }, [selectAdz])

    useEffect(() => {
        if (queryForm?.accountId) {
            getList()
        }
    }, [queryForm])

    // 获取落地页列表
    const getList = () => {
        listAjax.run({ ...queryForm, ...cloudParams, pageStatus: 'NORMAL' })
    }

    const handleOk = () => {
        if (data?.every((item: { pageList: any }) => item.pageList)) {
            onChange && onChange(data)
        } else {
            message.error('还有账号未选择落地页！')
        }
    }

    /** 设置选中广告主 */
    const handleSelectAdz = (value: number, item: any) => {
        if (value === selectAdz) {
            return
        }
        setSelectAdz(value)
    }

    /** 表格选折 */
    const onChangeTable = (selectedRowKeys: React.Key[], selectedRows: any) => {
        let newData = JSON.parse(JSON.stringify(data))
        newData[selectAdz - 1]['pageList'] = selectedRows
        setData([...newData])
    }

    /** 同步落地页 */
    const synPageList = () => {
        setLoading(true)
        putAdqLandingPage({ accountIdList: data?.map((item: { adAccountId: number }) => item.adAccountId), isUsePool: false }).then(res => {
            message.success('同步成功，结果可能需要几分钟返回，请手动点击下面刷新按钮')
            setLoading(false)
            listAjax.refresh()
        }).catch(() => setLoading(false))
    }

    /** 一键设置 */
    const setOnekey = () => {
        let pageName: string = data[selectAdz - 1]['pageList']?.[0]?.pageName
        let newData = JSON.parse(JSON.stringify(data))
        const hide = message.loading(`正在设置...`, 0, () => {
            message.success('设置成功');
        });
        let ajax = newData?.filter((item: { adAccountId: number }) => item.adAccountId !== data[selectAdz - 1].adAccountId)?.map((item: { adAccountId: number }) => {
            return getAdqLandingPageList({ pageName, accountId: item.adAccountId, pageNum: 1, pageSize: 20, pageStatus: 'NORMAL' })
        })
        Promise.all(ajax).then(res => {
            if (res && Array.isArray(res)) {
                res.forEach((item: any) => {
                    let records = item?.data?.records
                    if (Array.isArray(records) && records?.length > 0) {
                        let record = records[0]
                        newData = newData.map((item: { adAccountId: string }) => {
                            if (item.adAccountId.toString() === record.accountId.toString()) {
                                return { ...item, pageList: [{ ...record, id: record.pageId }] }
                            }
                            return item
                        })
                    }
                })
                setData(newData)
            }
            message.success('设置完成');
            hide()
        })
    }

    return <Modal
        title={<Space>
            <span>ADQ落地页</span>
            <Button size="small" onClick={() => { synPageList() }} type="link" loading={loading}>同步落地页</Button>
        </Space>}
        open={visible}
        onCancel={() => { onClose && onClose() }}
        onOk={handleOk}
        width={1100}
        className={style.SelectPackage}
        bodyStyle={{ padding: '0 10px 0 10px' }}
    >

        <div className={style.content}>
            <div className={style.left}>
                <h4 className={style.title}>媒体账户</h4>
                {data?.map((item: { adAccountId: number, id: number }, index: number) => (
                    <div key={index} onClick={() => { handleSelectAdz(index + 1, item) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                        {item?.adAccountId}
                        {data[index].pageList?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                    </div>
                ))}
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }} align="end">
                    <Input value={queryForm?.pageName} allowClear placeholder='请输入落地页名称' onChange={(e) => setQueryForm({ ...queryForm, pageNum: 1, pageName: e.target.value })}/>
                    {data?.length > 1 && <Button disabled={!data[selectAdz - 1]['pageList']?.length} onClick={setOnekey} type="link" loading={listAjax.loading}>
                        <Space>
                            <span>一键设置</span>
                            <Tooltip color="#FFF" overlayInnerStyle={{ color: '#000' }} title="设置其它账号有相同名称的落地页为那个账号的落地页（注意需要落地页名称相同，否则不设置）">
                                <QuestionCircleOutlined />
                            </Tooltip>
                        </Space>
                    </Button>} 
                    <Button icon={<SyncOutlined />} type='link' loading={listAjax?.loading} onClick={() => { listAjax?.refresh() }}></Button>
                </Space>
                <Tables
                    columns={columns()}
                    dataSource={listAjax?.data?.records?.map((item: any) => ({ ...item, id: item.pageId }))}
                    size="small"
                    loading={listAjax?.loading}
                    scroll={{ y: 300 }}
                    bordered
                    total={listAjax?.data?.total}
                    defaultPageSize={20}
                    current={listAjax?.data?.current}
                    pageSize={listAjax?.data?.size}
                    pageChange={(page: number, pageSize?: number) => {
                        setQueryForm({ ...queryForm, pageNum: page, pageSize: pageSize as number || 20 })
                    }}
                    rowSelection={{
                        type: 'radio',
                        selectedRowKeys: data[selectAdz - 1]?.pageList?.map((item: any) => item?.id?.toString()),
                        onChange: onChangeTable
                    }}
                />
            </div>
        </div>

    </Modal>
}

export default React.memo(PageModal)