import { Input, message, Modal, Radio, Space, Spin, Table, Tag } from "antd";
import React, { useCallback, useEffect, useReducer, useState } from "react";
import { CheckOutlined } from "@ant-design/icons";
import { columnsMp, columnsAdq } from './tableConfigAd'
// import '../../adAuthorize/index.less'
import { useModel } from "umi";

interface State {
    unames: {
        MP?: any,
        ADQ?: any,
        id: number,
        accountName: string
    }[]
}

interface Action {
    type: 'init' | 'unames',
    params?: any
}

function reducer(state: State, action: Action) {
    let { type, params } = action
    switch (type) {
        case 'unames':
            const newState = { ...state, unames: [...params.unames] }
            return newState
        case 'init':
            return {
                unames: []
            }
        default:
            return state
    }
}

type Props = {
    show?: boolean
    onClose?: () => void,
    onChange?: (unames: {
        MP?: any,
        ADQ?: any,
        id: number,
        accountName: string
    }[]) => void,
    channelAccounts?: {
        MP?: any,
        ADQ?: any,
        id: number,
        accountName: string
    }[], // 回填数据
    disabled?: boolean,
    disabledAccounts?: {
        MP?: any,
        ADQ?: any
    }
}
function SelectAccount(props: Props) {
    const { show = false, onClose, onChange, channelAccounts = [], disabled = false, disabledAccounts = [] } = props
    const initState = {
        unames: []
    }
    const [state, dispatch] = useReducer(reducer, initState)
    const [ispList, setIspList] = useState<any[]>([]);  // 服务商列表
    const [selectServer, setSelectServer] = useState<number>(0) // 点击选中的服务商
    const [channel, setChannel] = useState<string>('MP') // 选择渠道
    const [paging, setPaging] = useState<{ pageSize: number, pageNum: number, uname?: string }>({ pageSize: 20, pageNum: 1 }) // 用户表格参数
    const { allOfLoginUser, adsChannelAccountAdq, adsChannelAccountMp, adqSc, mpSc } = useModel('useLaunch.useAdAuthorize')

    useEffect(() => {
        if (show) {
            allOfLoginUser.run().then((res: any) => {
                setIspList(() => res?.data)
                if (res?.data?.length > 0) {
                    setSelectServer(() => res?.data[0]?.id)
                }
            })
        }
    }, [show])

    useEffect(() => {
        return () => {
            dispatch({ type: 'unames', params: { unames: [] } })
        }
    }, [])
    /** 回填选中 */
    useEffect(() => {
        if (channelAccounts?.length > 0) {
            dispatch({ type: 'unames', params: { unames: channelAccounts } })
        }
    }, [channelAccounts])

    useEffect(() => {
        if (selectServer > 0) {
            if (channel === 'MP') {
                adsChannelAccountMp.run({ ...paging, channelId: selectServer })
            } else {
                adsChannelAccountAdq.run({ ...paging, channelId: selectServer })
            }
        }
    }, [channel, selectServer, paging])

    const onSearch = (value: string) => {
        setPaging({ ...paging, uname: value, pageNum: 1 })
    }

    const onBack = useCallback(() => {
        if (state?.unames?.some((item: { ADQ: any[], MP: any[] }) => item?.ADQ?.length > 0 || item?.MP?.length > 0)) {
            onChange && onChange(state?.unames)
        } else {
            // message.error('请选择账号')
            onChange && onChange([])
        }

    }, [state?.unames])

    useEffect(() => {

    }, [disabled, disabledAccounts])


    const rowSelection = disabled ? {
        getCheckboxProps: (record: any) => {
            return {
                disabled: disabledAccounts?.[channel]?.indexOf(record?.id) !== -1,
                name: record.name,
            }
        },
        selectedRowKeys: state?.unames?.find((item: any) => item?.id === selectServer)?.[channel]?.map((item: any) => item.id)
    } : {
            selectedRowKeys: state?.unames?.find((item: any) => item?.id === selectServer)?.[channel]?.map((item: any) => item.id)
        }
    /**收藏*/
    const collect = useCallback((arg: { id: any, c: boolean, name: 'adq' | 'mp' }) => {
        let { id, c, name } = arg
        if (name === 'mp') {
            mpSc.run({ accountId: id, collect: c }).then((res) => {
                adsChannelAccountMp.refresh()
            })
        } else {
            adqSc.run({ accountId: id, collect: c }).then((res) => {
                adsChannelAccountAdq.refresh()
            })
        }
    }, [adsChannelAccountMp, adsChannelAccountAdq])
    return <Modal
        title='选择账户'
        open={show}
        onCancel={() => { onClose && onClose() }}
        maskClosable
        width={1000}
        destroyOnClose
        onOk={onBack}
        className="launchRefresh"
    >
        <div className="refContent">
            <div className="left">
                <Spin spinning={allOfLoginUser?.loading}>
                    <h4>服务商账户</h4>
                    <div style={{ height: 410, overflowY: 'scroll' }}>
                        {ispList?.length > 0 && ispList.map((item: any) => {
                            return <div className={`isp ${item?.id === selectServer ? 'selectServer' : ''}`} key={item?.id} onClick={() => { setSelectServer(item?.id) }}>
                                <span>{item?.accountName}</span> {(state?.unames?.find((it: any) => it?.id === item?.id)?.MP?.length > 0 || state?.unames?.find((it: any) => it?.id === item?.id)?.ADQ?.length > 0) && <CheckOutlined />}
                            </div>
                        })}
                    </div>
                </Spin>
            </div>
            <div className="right">
                <Space direction="vertical" style={{ width: '100%' }}>
                    <Space>
                        <Radio.Group value={channel} onChange={(e) => { setChannel(e.target.value); setPaging({ pageSize: 20, pageNum: 1 }) }}>
                            <Radio.Button value="MP">MP {state?.unames?.find((it: any) => it?.id === selectServer)?.MP?.length > 0 && <CheckOutlined />}</Radio.Button>
                            {/* <Radio.Button value="ADQ">ADQ {state?.unames?.find((it: any) => it?.id === selectServer)?.ADQ?.length > 0 && <CheckOutlined />}</Radio.Button> */}
                        </Radio.Group>
                        <Input.Search placeholder="请输入广告主名称" onSearch={onSearch} style={{ width: 200 }} allowClear />
                    </Space>
                    {
                        channel === "MP" ? <Table dataSource={adsChannelAccountMp?.data?.data?.records} scroll={{ x: 660, y: 300 }} loading={adsChannelAccountMp?.loading} columns={columnsMp(collect)} size="small" bordered
                            pagination={{
                                position: ['bottomLeft'],
                                total: adsChannelAccountMp?.data?.data?.total,//总共多少条数据,服务器给,设置后分页自动计算页数
                                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                                showSizeChanger: true,
                                showLessItems: true,
                                defaultCurrent: 1,
                                defaultPageSize: 20,//默认初始的每页条数
                                current: paging?.pageNum || 1,
                                pageSize: paging?.pageSize || 20,
                                onChange: (page, pageSize) => { setPaging({ ...paging, pageNum: page, pageSize: pageSize as number }) }
                            }}
                            rowKey={(row) => row.id}
                            rowSelection={{
                                onSelectAll: (selected, selectedRows, changeRows) => {
                                    let index = state?.unames?.findIndex((item: any) => item?.id === selectServer)
                                    let data = state?.unames
                                    let server = ispList?.find((item: any) => item?.id === selectServer)
                                    if (selected) { // 全选
                                        if (index !== -1) {
                                            let ch: any = {}
                                            if (Object.keys(data[index])?.indexOf(channel) !== -1) { // 判断已有
                                                ch[channel] = [...data[index][channel], ...changeRows]
                                            } else {
                                                ch[channel] = changeRows
                                            }
                                            ch.id = selectServer
                                            ch.accountName = server?.accountName
                                            data[index] = { ...ch }
                                        } else {
                                            let ch: any = {}
                                            ch[channel] = changeRows
                                            ch.id = selectServer
                                            ch.accountName = server?.accountName
                                            data?.push({ ...ch })
                                        }
                                    } else { // 全部取消
                                        let ch: any = {}
                                        let channelData = data[index][channel]
                                        changeRows.forEach((item: any) => {
                                            let channelIndex = channelData?.findIndex((can: any) => can?.id === item?.id)
                                            channelData?.splice(channelIndex, 1)
                                        })
                                        ch[channel] = [...channelData]
                                        ch.id = selectServer
                                        ch.accountName = server?.accountName
                                        data[index] = { ...ch }
                                    }
                                    dispatch({ type: 'unames', params: { unames: [...data] } })
                                },
                                onSelect: (record, selected, selectedRows, nativeEvent) => {
                                    selectedRows = selectedRows?.filter((item: any) => item)
                                    let index = state?.unames?.findIndex((item: any) => item?.id === selectServer)
                                    let data = state?.unames
                                    let server = ispList?.find((item: any) => item?.id === selectServer)
                                    if (selected) { // 增加
                                        if (index !== -1) {
                                            let ch: any = {}
                                            if (Object.keys(data[index])?.indexOf(channel) !== -1) { // 判断已有
                                                ch[channel] = [...data[index][channel], { ...record }]
                                            } else {
                                                ch[channel] = selectedRows
                                            }
                                            ch.id = selectServer
                                            ch.accountName = server?.accountName
                                            data[index] = { ...ch }
                                        } else {
                                            let ch: any = {}
                                            ch[channel] = selectedRows
                                            ch.id = selectServer
                                            ch.accountName = server?.accountName
                                            data?.push({ ...ch })
                                        }
                                    } else { // 减少
                                        let ch: any = {}
                                        if (Object.keys(data[index])?.indexOf(channel) !== -1) { // 判断已有
                                            let channelData = data[index][channel]
                                            let channelIndex = channelData?.findIndex((can: any) => can?.id === record?.id)
                                            channelData?.splice(channelIndex, 1)
                                            ch[channel] = [...channelData]
                                        }
                                        ch.id = selectServer
                                        ch.accountName = server?.accountName
                                        data[index] = { ...ch }
                                    }
                                    dispatch({ type: 'unames', params: { unames: [...data] } })
                                },
                                ...rowSelection
                            }}
                        /> :
                            <Table dataSource={adsChannelAccountAdq?.data?.data?.records} scroll={{ x: 660, y: 300 }} loading={adsChannelAccountAdq?.loading} columns={columnsAdq(collect)} size="small" bordered
                                pagination={{
                                    position: ['bottomLeft'],
                                    total: adsChannelAccountAdq?.data?.data?.total,//总共多少条数据,服务器给,设置后分页自动计算页数
                                    showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                                    showSizeChanger: true,
                                    showLessItems: true,
                                    defaultCurrent: 1,
                                    defaultPageSize: 20,//默认初始的每页条数
                                    current: paging?.pageNum || 1,
                                    pageSize: paging?.pageSize || 20,
                                    onChange: (page, pageSize) => { setPaging({ ...paging, pageNum: page, pageSize: pageSize as number }) }
                                }}
                                rowKey={(row) => row.id}
                                rowSelection={{
                                    onSelectAll: (selected, selectedRows, changeRows) => {
                                        let index = state?.unames?.findIndex((item: any) => item?.id === selectServer)
                                        let data = state?.unames
                                        let server = ispList?.find((item: any) => item?.id === selectServer)
                                        if (selected) { // 全选
                                            if (index !== -1) {
                                                let ch: any = {}
                                                if (Object.keys(data[index])?.indexOf(channel) !== -1) { // 判断已有
                                                    ch[channel] = [...data[index][channel], ...changeRows]
                                                } else {
                                                    ch[channel] = changeRows
                                                }
                                                ch.id = selectServer
                                                ch.accountName = server?.accountName
                                                data[index] = { ...ch }
                                            } else {
                                                let ch: any = {}
                                                ch[channel] = changeRows
                                                ch.id = selectServer
                                                ch.accountName = server?.accountName
                                                data?.push({ ...ch })
                                            }
                                        } else { // 全部取消
                                            let ch: any = {}
                                            let channelData = data[index][channel]
                                            changeRows.forEach((item: any) => {
                                                let channelIndex = channelData?.findIndex((can: any) => can?.id === item?.id)
                                                channelData?.splice(channelIndex, 1)
                                            })
                                            ch[channel] = [...channelData]
                                            ch.id = selectServer
                                            ch.accountName = server?.accountName
                                            data[index] = { ...ch }
                                        }
                                        dispatch({ type: 'unames', params: { unames: [...data] } })
                                    },
                                    onSelect: (record, selected, selectedRows, nativeEvent) => {
                                        selectedRows = selectedRows?.filter((item: any) => item)
                                        let index = state?.unames?.findIndex((item: any) => item?.id === selectServer)
                                        let data = state?.unames
                                        let server = ispList?.find((item: any) => item?.id === selectServer)
                                        if (selected) { // 增加
                                            if (index !== -1) {
                                                let ch: any = {}
                                                if (Object.keys(data[index])?.indexOf(channel) !== -1) { // 判断已有
                                                    ch[channel] = [...data[index][channel], { ...record }]
                                                } else {
                                                    ch[channel] = selectedRows
                                                }
                                                ch.id = selectServer
                                                ch.accountName = server?.accountName
                                                data[index] = { ...ch }
                                            } else {
                                                let ch: any = {}
                                                ch[channel] = selectedRows
                                                ch.id = selectServer
                                                ch.accountName = server?.accountName
                                                data?.push({ ...ch })
                                            }
                                        } else { // 减少
                                            let ch: any = {}
                                            if (Object.keys(data[index])?.indexOf(channel) !== -1) { // 判断已有
                                                let channelData = data[index][channel]
                                                let channelIndex = channelData?.findIndex((can: any) => can?.id === record?.id)
                                                channelData?.splice(channelIndex, 1)
                                                ch[channel] = [...channelData]
                                            }
                                            ch.id = selectServer
                                            ch.accountName = server?.accountName
                                            data[index] = { ...ch }
                                        }
                                        dispatch({ type: 'unames', params: { unames: [...data] } })
                                    },
                                    ...rowSelection
                                }}
                            />
                    }
                </Space>
            </div>
        </div>
    </Modal>
}


export default React.memo(SelectAccount)