import { useAjax } from "@/Hook/useAjax"
import { CheckOutlined, QuestionCircleOutlined, SyncOutlined } from "@ant-design/icons"
import { Button, message, Modal, Space, Table, Tooltip } from "antd"
import React, { useEffect, useState } from "react"
import style from '../GoodsModal/index.less'
import columns from './tableConfig'
import { getVideoChannelInfoApi, getVideoChannelInfoBatchApi } from "@/services/adqV3/global"

/**
 * 获取视频号列表
 * @returns 
 */
interface Props {
    visible?: boolean,
    onClose?: () => void,
    onChange?: (data: PULLIN.AccountCreateLogsProps[]) => void,
    data: PULLIN.AccountCreateLogsProps[]
}
const VideoChannel: React.FC<Props> = (props) => {

    /************************/
    const { visible, onClose, data: data1, onChange } = props
    const [tableData, setTableData] = useState<any[]>([])//table数据
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [data, setData] = useState<PULLIN.AccountCreateLogsProps[]>(data1)
    const [loading, setLoading] = useState<boolean>(false)

    const getVideoChannelInfo = useAjax((params) => getVideoChannelInfoApi(params))
    const getVideoChannelInfoBatch = useAjax((params) => getVideoChannelInfoBatchApi(params))
    /************************/

    useEffect(() => {
        if (data?.length > 0) {
            getList(data[selectAdz - 1].accountId)
        } else {
            setTableData([])
        }
    }, [selectAdz])

    // 获取公众号列表
    const getList = (accountId: number) => {
        getVideoChannelInfo.run({ accountId }).then(res => {
            setTableData(res || [])
        })
    }

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

    /** 设置选中广告主 */
    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]['videoChannelList'] = selectedRows
        setData([...newData])
    }

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

    /** 一键设置 */
    const setOnekey = (isFirst?: boolean) => {
        let newData: PULLIN.AccountCreateLogsProps[] = JSON.parse(JSON.stringify(data))
        const hide = message.loading(`正在设置...`, 0, () => {
            message.success('设置成功');
        });
        if (isFirst) {
            setLoading(true)
            let ajax = data.map(item => getVideoChannelInfoApi({ accountId: item.accountId }))
            Promise.all(ajax).then(res => {
                if (res) {
                    res.forEach(a => {
                        let data = a?.data?.[0] || {}
                        newData = newData.map(item => {
                            if (item.accountId.toString() === data.accountId.toString()) {
                                return { ...item, videoChannelList: [data] }
                            }
                            return item
                        })
                    })
                    setData(newData)
                }
                message.success('设置完成');
                setLoading(false)
                hide()
            }).catch(() => {
                message.success('设置失败');
                setLoading(false)
                hide()
            })
        } else {
            let wechatChannelNames: string[] = data[selectAdz - 1]['videoChannelList']?.map((item: { wechatChannelsAccountName: string }) => item.wechatChannelsAccountName) || []
            getVideoChannelInfoBatch.run({ accountIdList: newData?.filter(item => item.accountId !== data[selectAdz - 1].accountId)?.map(item => item?.accountId) }).then(res => {
                if (res?.length > 0) {
                    res.forEach((i: { accountId: number, wechatChannelsAccountName: string }) => {
                        if (wechatChannelNames.includes(i.wechatChannelsAccountName)) {
                            newData = newData.map(item => {
                                if (item.accountId.toString() === i.accountId.toString()) {
                                    return { ...item, videoChannelList: [i] }
                                }
                                return item
                            })
                        }
                    })
                    setData(newData)
                }
                message.success('设置完成');
                hide()
            })
        }
    }


    return <Modal
        title={<Space>
            <strong>选择视频号</strong>
            <Button type="link" danger onClick={() => setOnekey(true)} loading={loading}>一键设置第一个视频号给账户</Button>
        </Space>}
        open={visible}
        onCancel={() => { onClose && onClose() }}
        onOk={handleOk}
        width={900}
        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 videoChannelList = data[index].videoChannelList || []
                        return <div key={index} onClick={() => { handleSelectAdz(index + 1) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            {item?.accountId}
                            {videoChannelList?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    })}
                </div>
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }} align="end" size={0}>
                    <Button icon={<SyncOutlined />} type='link' loading={getVideoChannelInfo?.loading} onClick={() => { getList(data[selectAdz - 1].accountId) }}>刷新</Button>
                    {data?.length > 1 && <Button disabled={!data[selectAdz - 1]['videoChannelList']?.length} onClick={() => setOnekey()} type="link" loading={getVideoChannelInfo.loading}>
                        <Space>
                            <span>一键设置</span>
                            <Tooltip color="#FFF" overlayInnerStyle={{ color: '#000' }} title="设置其它账号有相同名称的视频号为那个账号的视频号（注意需要用户视频号名称称相同，否则不设置）">
                                <QuestionCircleOutlined />
                            </Tooltip>
                        </Space>
                    </Button>}
                    {(data[selectAdz - 1]?.videoChannelList || [])?.length > 0 && <Button type='link' onClick={() => { clearGoods() }}>清空</Button>}
                </Space>
                <Table
                    columns={columns()}
                    dataSource={tableData}
                    size="small"
                    loading={getVideoChannelInfo?.loading}
                    scroll={{ y: 400 }}
                    rowKey={'wechatChannelsAccountId'}
                    rowSelection={{
                        type: 'radio',
                        selectedRowKeys: data[selectAdz - 1]?.videoChannelList?.map((item: any) => item?.wechatChannelsAccountId),
                        onChange: onChangeTable
                    }}
                    onRow={(record) => ({
                        onClick: () => {
                            let newDatas = JSON.parse(JSON.stringify(data))
                            let oldData = newDatas[selectAdz - 1]?.videoChannelList || []
                            const selected = oldData?.some((item: any) => item?.wechatChannelsAccountId === record.wechatChannelsAccountId);
                            const newSelectedRows = selected
                                ? oldData?.filter((item: any) => item?.wechatChannelsAccountId !== record.wechatChannelsAccountId)
                                : [...oldData, record];
                            newDatas[selectAdz - 1]['videoChannelList'] = newSelectedRows;
                            setData([...newDatas])
                        },
                    })}
                />
            </div>
        </div>
    </Modal>
}

export default React.memo(VideoChannel)