import { useAjax } from "@/Hook/useAjax"
import { CheckOutlined, CloseOutlined, QuestionCircleOutlined, SyncOutlined } from "@ant-design/icons"
import { Button, Input, message, Modal, Space, Table, Tooltip, Typography } from "antd"
import React, { useEffect, useState } from "react"
import style from './index.less'
import columns from './tableConfig'
import { getByRemotemarketingAssetContentApi } from "@/services/adqV3/global"
import { MARKETING_TARGET_TYPE_ENUM } from "../../tencentAdPutIn/const"
const { Title, Text } = Typography;

/**
 * 获取商品列表
 * @returns 
 */
interface Props {
    marketingTargetType: MARKETING_TARGET_TYPE_ENUM,
    visible?: boolean,
    onClose?: () => void,
    onChange?: (data: PULLIN.AccountCreateLogsProps[]) => void,
    data: PULLIN.AccountCreateLogsProps[]
}
const GoodsModal: React.FC<Props> = (props) => {

    /************************/
    const { marketingTargetType, visible, onClose, data: data1, onChange } = props
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [data, setData] = useState<PULLIN.AccountCreateLogsProps[]>(data1)
    const [queryForm, setQueryForm] = useState<{
        marketingAssetType?: string,
        marketingAssetName?: string,
        pageNum: number,
        pageSize: number,
        accountId?: number
    }>({ pageNum: 1, pageSize: 10 })

    const getByRemotemarketingAssetContent = useAjax((params) => getByRemotemarketingAssetContentApi(params))
    // const synMarketingAssetContent = useAjax((params) => synMarketingAssetContentApi(params))
    /************************/

    useEffect(() => {
        if (data?.length > 0) {
            getList({ accountId: data[selectAdz - 1].accountId, pageNum: 1, pageSize: 10 })
        } else {
            getByRemotemarketingAssetContent.data && getByRemotemarketingAssetContent.mutate({ records: [] })
        }
    }, [selectAdz])

    // 获取商品列表
    const getList = (data: {
        marketingAssetType?: string,
        marketingAssetName?: string,
        pageNum: number,
        pageSize: number,
        accountId?: number
    }) => {
        setQueryForm(data)
        getByRemotemarketingAssetContent.run({ ...data, marketingAssetType: marketingTargetType })
    }

    const handleOk = () => {
        if (data.every(item => item?.productList?.length)) {
            onChange && onChange(data)
        } else {
            message.error('请完善所有账号产品')
        }
    }

    // 同步小说
    // const synGoodsList = () => {
    //     synMarketingAssetContent.run({ accountId: data[selectAdz - 1].accountId }).then(res => {
    //         if (res) {
    //             message.success('同步成功，结果可能几分钟后展示，请勿重复点击同步')
    //         }
    //     })
    // }

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

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

    // 清空已选
    const clearGoods = () => {
        let newData = JSON.parse(JSON.stringify(data))
        newData[selectAdz - 1]['productList'] = []
        setData([...newData])
    }

    /** 一键设置 */
    const setOnekey = () => {
        let marketingIdList: number[] = data[selectAdz - 1]['productList']?.map((item: { marketingAssetId: number }) => item.marketingAssetId) || []
        let newData: PULLIN.AccountCreateLogsProps[] = JSON.parse(JSON.stringify(data))
        const hide = message.loading(`正在设置...`, 0, () => {
            message.success('设置成功');
        });
        let dataAjax = newData?.filter(item => item.accountId !== data[selectAdz - 1].accountId)?.map(item => item?.accountId).map(accountId => {
            return getByRemotemarketingAssetContentApi({ pageNum: 1, pageSize: 10, accountId: accountId, marketingIdList, marketingAssetType: marketingTargetType })
        })
        Promise.all(dataAjax).then(res => {
            if (res?.length > 0) {
                res.forEach(ajax => {
                    let data = ajax.data?.records
                    if (data?.length > 0) {
                        let accountId = data[0].accountId
                        newData = newData.map(item => {
                            if (item.accountId.toString() === accountId.toString()) {
                                return { ...item, productList: ajax.data?.records }
                            }
                            return item
                        })
                    }
                })
            }
            setData(newData)
            message.success('设置完成');
            hide()
        }).catch(() => {
            hide()
            message.error('设置失败')
        })
    }

    return <Modal
        title={<Space>
            <strong>产品库</strong>
            {/* <Button size="small" style={{ padding: 0 }} onClick={() => { synGoodsList() }} type="link" loading={synMarketingAssetContent?.loading}>同步小说</Button> */}
        </Space>}
        open={visible}
        onCancel={() => { onClose && onClose() }}
        onOk={handleOk}
        width={1000}
        className={`${style.SelectPackage} modalResetCss`}
        bodyStyle={{ padding: '0 10px 0 10px' }}
    >
        <div className={style.content}>
            <div className={style.left}>
                <h4 className={style.title}>媒体账户</h4>
                <div className={style.accountIdList}>
                    {data?.map((item, index) => {
                        let productList = data[index].productList || []
                        return <div key={index} onClick={() => { handleSelectAdz(index + 1) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            {item?.accountId}
                            {productList?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    })}
                </div>
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }} align="end" size={0}>
                    <Input.Search enterButton allowClear placeholder="请输入商品名称" onSearch={(value) => getList({ ...queryForm, marketingAssetName: value, pageNum: 1 })} />
                    <Button icon={<SyncOutlined />} type='link' loading={getByRemotemarketingAssetContent?.loading} onClick={() => { getList({ ...queryForm, accountId: data[selectAdz - 1].accountId }) }}>刷新</Button>
                    {data?.length > 1 && <Button disabled={!data[selectAdz - 1]['productList']?.length} onClick={setOnekey} type="link" loading={getByRemotemarketingAssetContent.loading}>
                        <Space>
                            <span>一键设置</span>
                            <Tooltip color="#FFF" overlayInnerStyle={{ color: '#000' }} title="设置其它账号有相同产品Id为那个账号的产品（注意需要产品Id相同，否则不设置）">
                                <QuestionCircleOutlined />
                            </Tooltip>
                        </Space>
                    </Button>}
                    {(data[selectAdz - 1]?.productList || [])?.length > 0 && <Button type='link' onClick={() => { clearGoods() }}>清空</Button>}
                </Space>
                <Table
                    columns={columns()}
                    dataSource={getByRemotemarketingAssetContent.data?.records}
                    size="small"
                    loading={getByRemotemarketingAssetContent?.loading}
                    scroll={{ y: 400 }}
                    bordered
                    pagination={{
                        defaultPageSize: 100,
                        current: getByRemotemarketingAssetContent.data?.current || 1,
                        pageSize: getByRemotemarketingAssetContent.data?.size || 10,
                        total: getByRemotemarketingAssetContent.data?.total || 0
                    }}
                    rowKey={'marketingAssetId'}
                    rowSelection={{
                        getCheckboxProps(record) {
                            let length = data[selectAdz - 1]?.productList?.length || 0
                            return {
                                disabled: length >= 10 && data[selectAdz - 1]?.productList?.every((item: any) => item?.marketingAssetId !== record?.marketingAssetId)
                            }
                        },
                        type: 'checkbox',
                        selectedRowKeys: data[selectAdz - 1]?.productList?.map((item: any) => item?.marketingAssetId),
                        onChange: onChangeTable
                    }}
                    onChange={(pagination) => {
                        const { current, pageSize } = pagination
                        getList({ ...queryForm, pageNum: current || 1, pageSize: pageSize || 10 })
                    }}
                />
            </div>
            <div className={style.center}>
                <Title level={5}>已选：{data[selectAdz - 1]?.productList?.length || 0}/10</Title>
                <div className={style.select_content}>
                    {data[selectAdz - 1]?.productList?.map(item => <div key={item.marketingAssetId}>
                        <Text ellipsis={{ tooltip: true }} className={style.marketingAssetName}>{item.marketingAssetName}</Text>
                        <CloseOutlined className={style.close} onClick={() => {
                            let newData: PULLIN.AccountCreateLogsProps[] = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1].productList = newData[selectAdz - 1]?.productList?.filter((i: any) => i?.marketingAssetId !== item.marketingAssetId)
                            setData(newData)
                        }} />
                    </div>)}
                </div>
            </div>
        </div>
    </Modal>
}

export default React.memo(GoodsModal)