import Tables from "@/components/Tables";
import Warrant from "@/pages/launchSystem/launchManage/adAuthorize/warrant";
import { CheckOutlined, SearchOutlined, SyncOutlined } from "@ant-design/icons";
import { Button, Input, message, Modal, Space } from "antd";
import React, { useCallback, useEffect, useReducer, useState } from "react";
import { useModel } from "umi";
import style from './index.less'
import columns from './tableConfig'
import AuthLogin from '../../../../../components/authLogin'

interface State {
    orientPackage: any[]
}
interface Action {
    type: 'init' | 'orientPackage',
    params?: any
}

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

interface Props {
    visible: boolean,
    hideModel: () => void,
    launchAcc: any[],
    callback: (value: any) => void
}

function SelectPackage(props: Props) {
    let { visible, hideModel, launchAcc, callback } = props
    const [state, dispatch] = useReducer(reducer, initState)
    let { orientPackage } = state
    const { allDataSource, updateChannelInfo } = useModel('useLaunch.useAdAuthorize')

    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [dataSource, setDataSource] = useState<any[]>([])  // 表格数据
    const [wechatInfo, setWechatInfo] = useState<any>({})   // 保存选中的广告主账户信息
    const [warrant, setWarrant] = useState<boolean>(false)  //授权弹窗控制
    const [name, setName] = useState<string>('')   // 搜索输入
    const [authShow, setAuthShow] = useState<boolean>(false)  // 授权弹窗登录
    const [authData, setAuthData] = useState<{ base64: string, code: string }>({ base64: '', code: '' })
    const [queryForm, setQueryForm] = useState<{ accountType: 'mp' | 'adq', channelAccountId: number | string }>({ accountType: 'mp', channelAccountId: '' })

    const hideHandle = useCallback(() => {
        hideModel()
    }, [hideModel])

    const handleOk = useCallback(() => {
        console.log('orientPackage--->', orientPackage);
        
        callback(orientPackage)
        hideModel()
    }, [hideModel, orientPackage])

    useEffect(() => {
        if (launchAcc?.length > 0) {
            console.log('11111---->', launchAcc)
            let info = launchAcc[0]
            dispatch({
                type: 'orientPackage', params: {
                    orientPackage: launchAcc?.map((item: any) => {
                        if (item?.dataSource) {
                            return item
                        } else {
                            return { ...item, dataSource: [] }
                        }
                    })
                }
            })
            setQueryForm({ ...queryForm, channelAccountId: info.id })
            setWechatInfo({ ...info })
            allDataSource.run({ ...queryForm, channelAccountId: info.id })
        }
    }, [launchAcc])

    /** 设置选中广告主 */
    const handleSelectAdz = useCallback((value: number, item: any) => {
        setSelectAdz(value)
        setWechatInfo({ ...item })
        allDataSource.run({ ...queryForm, channelAccountId: item?.id })
    }, [selectAdz, dataSource, wechatInfo, queryForm])

    /** 查询 */
    const queryHandle = useCallback(() => {
        let wechat_info = wechatInfo?.wechat_info
        allDataSource.run({ ...queryForm, serviceName: wechat_info?.service_name, wechatName: wechat_info?.wechat_name, humanPackageName: name }).then((res: any) => {
            if (res?.msg === "SUCCESS") {
                setDataSource(res?.data?.records)
            }
        })
    }, [dataSource, wechatInfo, name, queryForm])

    /** 表格选折 */
    const onChangeTable = useCallback((selectedRowKeys: React.Key[], selectedRows: any) => {
        let data = orientPackage
        data[selectAdz - 1]['dataSource'] = selectedRows
        dispatch({ type: 'orientPackage', params: { orientPackage: data } })
    }, [orientPackage, selectAdz])

    /** 刷新定向包 */
    const refreshPack = useCallback(() => {
        let channels: number[] = []
        let channelMpAccount: any = {}
        // let channelAdqAccount: any = {}  ADQ
        launchAcc?.forEach((item: any) => {
            if (channels?.indexOf(item?.serverId) === -1) {
                channels.push(item?.serverId)
            }
            if (channelMpAccount[item?.serverId] && channelMpAccount[item?.serverId]?.length > 0) {
                let mpIds = channelMpAccount[item?.serverId]
                mpIds = [...mpIds, item?.id]
                channelMpAccount[item?.serverId] = mpIds
            } else {
                channelMpAccount[item?.serverId] = [item?.id]
            }
        })
        updateChannelInfo.run({ updateName: 'crowd_package', channels, channelMpAccount }).then((res: any) => {
            if (res?.code === 1003 && !res?.data?.base64) {
                setWarrant(true)
            } else if (res?.code === 1003 && res?.data?.base64) {
                setAuthShow(true)
                setAuthData({ base64: res?.data?.base64, code: res?.data?.code })
            } else if (res?.code === 200) {
                message.success('正在刷新，可关闭当前窗口，刷新完成会钉钉通知')
            }
        })
    }, [launchAcc, warrant, authShow])

    return <>
        {/* 首次授权登录 */}
        {warrant && <Warrant show={warrant} onClose={() => { setWarrant(false) }} isUpdataAcc={false}></Warrant>}
        {authShow && <AuthLogin show={authShow} onClose={() => { setAuthShow(false) }} data={authData} onChange={() => { setAuthShow(false); message.success('正在刷新，可关闭当前窗口，刷新完成会钉钉通知') }} />}
        <Modal
            title={<Space>
                <span>数据源</span>
                <Button size="small" onClick={refreshPack} loading={updateChannelInfo.loading}>刷新数据源</Button>
            </Space>}
            visible={visible}
            onCancel={hideHandle}
            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>
                    {/* ${style.alreadySelect} */}
                    {orientPackage?.map((item: { label: string, dataSource: any[], id: number }, index: number) => (
                        <div key={index} onClick={() => { handleSelectAdz(index + 1, item) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            {item?.label}
                            {item.dataSource.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>))}
                </div>
                <div className={style.right}>
                    <Space style={{ marginBottom: 10 }}>
                        <Input value={name} onChange={(e) => { setName(e.target.value) }} placeholder="请输入数据源名称" prefix={<SearchOutlined />} /> 
                        <Button type='primary' onClick={queryHandle}>查询</Button>
                        <Button icon={<SyncOutlined />} onClick={()=>{allDataSource.refresh()}} loading={allDataSource?.loading}>刷新</Button>
                    </Space>
                    <Tables
                        columns={columns()}
                        dataSource={allDataSource?.data?.data}
                        size="small"
                        loading={allDataSource?.loading}
                        scroll={{ y: 300 }}
                        bordered
                        rowSelection={{
                            selectedRowKeys: orientPackage[selectAdz - 1]?.dataSource?.map((item: any) => item.id.toString()),
                            onChange: onChangeTable,
                            getCheckboxProps: (record: { activateStatus: boolean }) => {
                                // if (!record?.activateStatus) {
                                //     return { disabled: true }
                                // }
                                return false
                            }
                        }}
                    />
                </div>
            </div>
        </Modal>
    </>
}

export default React.memo(SelectPackage)