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 '@/pages/launchSystem/launchManage/components/authLogin'
import { useCallbackState } from './callbackState'

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 { allOfAccountGods, updateChannelInfo, allOfAccountGodsDetail } = useModel('useLaunch.useAdAuthorize')

    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择广告主
    const [selectGoods, setSelectGoods] = useState<number>(1)   // 选择商品
    const [goodsData, setGoodsData] = useState<any[]>([])  // 列表
    const [dataSource, setDataSource] = useState<any[]>([])  // 表格数据
    const [wechatInfo, setWechatInfo] = useState<any>({})   // 保存选中的广告主账户信息
    const [warrant, setWarrant] = useState<boolean>(false)  //授权弹窗控制
    const [authShow, setAuthShow] = useState<boolean>(false)  // 授权弹窗登录
    const [tableData, setTableData] = useState<any[]>([])//table数据
    const [oldtableData, setOldTableData] = useState<any[]>([])//备份table数据
    const [authData, setAuthData] = useState<{ base64: string, code: string }>({ base64: '', code: '' })
    const [queryForm, setQueryForm] = useState<{ accountType: 'mp' | 'adq', channelAccountId: number | string }>({ accountType: 'mp', channelAccountId: '' })
    const [queryFormDetail, setQueryFormDetail] = useCallbackState({ accountType: 'mp', channelAccountId: '' });

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

    const handleOk = useCallback(() => {
        callback(orientPackage)
        hideModel()
    }, [hideModel, orientPackage])

    useEffect(() => {
        if (launchAcc?.length > 0) {
            let info = launchAcc[0]
            dispatch({
                type: 'orientPackage', params: {
                    orientPackage: launchAcc?.map((item: any) => {
                        if (item?.package) {
                            return item
                        } else {
                            return { ...item, package: [] }
                        }
                    })
                }
            })
            setQueryForm(() => ({ ...queryForm, channelAccountId: info.id }))
            setQueryFormDetail({ ...queryForm, channelAccountId: info.id }, (data: any) => {
                getList(data)
            })
            setWechatInfo({ ...info })
        }
    }, [launchAcc])
    /** 获取列表 */
    const getList = useCallback(async (data: any) => {
        allOfAccountGods.run({ ...data }).then((res: any) => {
            if (res?.data) {
                setGoodsData(() => res.data)
                if (res.data?.length > 0) {
                    handleGoods(1, { ...data, godsId: res.data[0].catalogId })
                }
            } else {
                setTableData([])
            }
        })
    }, [tableData, goodsData, launchAcc])

    /** 设置选中广告主 */
    const handleSelectAdz = useCallback((value: number, item: any) => {
        if (value === selectAdz) {
            return
        }
        setSelectAdz(value)
        setWechatInfo({ ...item })
        setQueryForm({ ...queryForm, channelAccountId: item?.id })
        setQueryFormDetail({ ...queryForm, channelAccountId: item?.id }, (data: any) => {
            getList(data)
        })

    }, [selectAdz, dataSource, wechatInfo, queryForm, queryFormDetail])
    /**选中商品库,获取对应商品列表*/
    const handleGoods = useCallback((value: number, data: any) => {
        setSelectGoods(value)
        if (data) {
            allOfAccountGodsDetail.run({ ...data }).then((res: any) => {
                setTableData(res?.data?.map((item: any) => {
                    return item
                }))
                setOldTableData(res?.data?.map((item: any) => {
                    return item
                }))
            })
        }
    }, [tableData, selectGoods, queryFormDetail, launchAcc])

    /** 查询 */
    const queryHandle = useCallback((e) => {
        let name = e.target.value
        if(name){
            let newTableData= oldtableData?.filter(item=>item?.productName?.includes(name))
            setTableData(newTableData)
        }else{
            setTableData(oldtableData)
        }
     
    }, [oldtableData])

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

    /** 刷新人群包 */
    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, package: any[], id: number }, index: number) => (
                        <div key={index} onClick={() => { handleSelectAdz(index + 1, item) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            {item?.label}
                            {orientPackage[index].goods?.data?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>))}
                </div>
                <div className={style.left}>
                    <h4 className={style.title}>商品库</h4>
                    {goodsData?.map((item: { name: string, goodsList: any[], catalogId: number }, index: number) => (
                        <div key={index} onClick={() => { handleGoods(index + 1, { ...queryFormDetail, godsId: goodsData[index].catalogId }) }} className={`${style.accItem} ${selectGoods === index + 1 && style.select} `}>
                            {item?.name}
                            {orientPackage[selectAdz - 1]?.goods?.key === item?.catalogId && orientPackage[selectAdz - 1].goods?.data?.length > 0 && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>))
                    }
                </div>
                <div className={style.right}>
                    <Space style={{ marginBottom: 10 }}>
                        <Input  onChange={queryHandle} placeholder="请输入商品名称" prefix={<SearchOutlined />} allowClear/>
                        <Button icon={<SyncOutlined />} onClick={() => { allOfAccountGods.refresh() }} loading={allOfAccountGods?.loading}>刷新</Button>
                    </Space>
                    <Tables
                        columns={columns()}
                        dataSource={tableData}
                        size="small"
                        loading={allOfAccountGods?.loading}
                        scroll={{ y: 300 }}
                        bordered
                        rowSelection={{
                            type: 'radio',
                            selectedRowKeys: orientPackage[selectAdz - 1]?.goods?.data?.map((item: any) => item?.id?.toString()),
                            onChange: onChangeTable
                        }}
                    />
                </div>
            </div>
        </Modal>
    </>
}

export default React.memo(SelectPackage)