import { Tag, Space, Badge, Modal, Select, Avatar as AntdAvatar } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import { useModel } from 'umi';
import Avatar from './AvatarDropdown';
import styles from './index.less';
import { exitFullScreen, requestFullScreen, isFull } from '@/utils/fullScreen'
import { BellOutlined, UserOutlined } from '@ant-design/icons';
import { getAppListApi } from '@/services/iaaData';
import { useAjax } from '@/Hook/useAjax';

export type SiderTheme = 'light' | 'dark';


const GlobalHeaderRight: React.FC<{}> = () => {

    const [left, setLeft] = useState(0)
    const { initialState, setInitialState } = useModel('@@initialState');
    const { state: { versionsOpen }, dispatch, getversions } = useModel('useOperating.useWxGroupList')
    if (!initialState || !initialState.settings) {
        return null;
    }
    const [appList, setApplist] = useState<{ label: string, value: string, productType: string; mediaPlatform: string; icon?: string }[]>([])
    const getAppList = useAjax(() => getAppListApi())
    const [productTypeList, setProductTypeList] = useState<{ label: string, value: string }[]>([])
    const [mediaPlatformList, setMediaPlatformList] = useState<{ label: string, value: string }[]>([])
    const [productType, setProductType] = useState<string>()
    const [isJr, setIsJr] = useState<boolean>(false)

    const haveTo = (type: 'MEDIA_PLATFORM_TENCENT' | 'MEDIA_PLATFORM_OCENAENGINE') => {
        let menus = initialState?.menu?.data?.find((item: { path: string; }) => item.path === "/iaaData")?.routes
        const firstTencent = menus?.find((item: { path: string; }) => item.path === "/iaaData/tencentIaa")?.routes?.[0]?.path
        const firstOcenaengine = menus?.find((item: { path: string; }) => item.path === "/iaaData/ocenaengineIaa")?.routes?.[0]?.path
        switch (type) {
            case 'MEDIA_PLATFORM_TENCENT':
                if (!location.hash.includes('tencentIaa')) {
                    window.location.href = `/#${firstTencent}`
                }
                break
            case 'MEDIA_PLATFORM_OCENAENGINE':
                if (!location.hash.includes('ocenaengineIaa')) {
                    window.location.href = `/#${firstOcenaengine}`
                }
                break
        }
    }

    useEffect(() => {
        if (location.hash.includes('/iaaSystem')) {
            setIsJr(() => true)
        }
    }, [location.hash])

    useEffect(() => {
        if (location.hash.includes('/iaaData') && !isJr) {
            setIsJr(() => true)
            getAppList.run().then(res => {
                if (res?.data) {
                    let menus = initialState?.menu?.data?.find((item: { path: string; }) => item.path === "/iaaData")?.routes
                    const firstTencent = menus?.find((item: { path: string; }) => item.path === "/iaaData/tencentIaa")?.routes?.[0]?.path
                    const firstOcenaengine = menus?.find((item: { path: string; }) => item.path === "/iaaData/ocenaengineIaa")?.routes?.[0]?.path
                    const productTypeSet = new Set();
                    const mediaPlatformSet = new Set();
                    const data: { label: string, value: string, productType: string; mediaPlatform: string; icon?: string }[] = res?.data?.filter((item: { mediaPlatform: string; }) => (firstTencent && item.mediaPlatform === 'MEDIA_PLATFORM_TENCENT') || (firstOcenaengine && item.mediaPlatform === 'MEDIA_PLATFORM_OCENAENGINE'))?.map((item: { name: string; id: number; productType: string; mediaPlatform: string; icon?: string }) => {
                        productTypeSet.add(item.productType)
                        mediaPlatformSet.add(item.mediaPlatform)
                        return { label: item.name, value: item.id + '||' + item.productType, productType: item.productType, mediaPlatform: item.mediaPlatform, icon: item.icon }
                    })
                    if (data?.length) {
                        setProductTypeList([{ label: '游戏业务', value: 'PRODUCT_TYPE_GAME' }, { label: '小说业务', value: 'PRODUCT_TYPE_NOVEL' }, { label: '短剧业务', value: 'PRODUCT_TYPE_PLAYLET' }].filter(item => [...productTypeSet].includes(item.value)))
                        setMediaPlatformList([{ label: '腾讯', value: 'MEDIA_PLATFORM_TENCENT' }, { label: '头条', value: 'MEDIA_PLATFORM_OCENAENGINE' }].filter(item => [...mediaPlatformSet].includes(item.value)))
                        const app = initialState?.iaaApp
                        let iaaApp: string;
                        let mediaPlatform: string;
                        const d = data.find(item => item.value === app)
                        if (app && d) {
                            iaaApp = app
                            mediaPlatform = d.mediaPlatform
                        } else {
                            iaaApp = data?.[0].value || undefined as any
                            mediaPlatform = data?.[0].mediaPlatform || undefined as any
                        }
                        const productType = iaaApp ? iaaApp.split('||')?.[1] : undefined
    
                        haveTo(mediaPlatform as any)
                        sessionStorage.setItem('mediaPlatform', mediaPlatform)
                        setProductType(productType)
                        setInitialState({ ...initialState, iaaApp, mediaPlatform })
                        setApplist(data)
                    }
                }
            })
        }
    }, [location.hash, isJr])


    useEffect(() => {

        setTimeout(() => {
            let nav: any = document.querySelector('.top-nav-menu')
            let navLi: any = document.querySelectorAll('.top-nav-menu > li')
            if (nav && navLi) {
                let l = nav.offsetLeft
                let lw = 0
                for (const iterator of navLi) {
                    lw += iterator.offsetWidth
                }
                setLeft(l + lw - 50)
            }
        }, 30)
    }, [])

    const { navTheme, layout } = initialState.settings;
    let className = styles.right;

    if ((navTheme === 'dark' && layout === 'top') || layout === 'mix') {
        className = `${styles.right}  ${styles.dark}`;
    }
    let handleFullScreen = () => {
        if (isFull()) {
            exitFullScreen()
        } else {
            requestFullScreen()
        }
    }
    //消息弹窗更新
    const inform = useCallback(() => {
        let bdVersions = localStorage.getItem('versions') //本地
        getversions.run().then((res) => {
            let fwqVersions = ''//服务器版本
            let content: any = ''//版本更新内容
            if (res) {
                fwqVersions = res?.configValue
                content = <div dangerouslySetInnerHTML={{ __html: res?.remark?.replace(/\n/ig, '<br/>') }}></div >
                if (fwqVersions && bdVersions !== fwqVersions) {//不一样
                    //执行逻辑
                    Modal.confirm({
                        title: '版本更新！',
                        content,
                        keyboard: false,
                        cancelText: '稍后我自己刷新页面',
                        okText: '现在就去刷新页面',
                        onOk: () => {
                            localStorage.setItem('versions', fwqVersions)//重新设置服务器版本
                            location?.reload()
                        },
                        onCancel: () => {
                            dispatch({ type: 'versionsOpen', params: { versionsOpen: true } })
                        }
                    })
                    console.log('不一样')
                }
            }
        })
    }, [])

    return (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            {location.hash.includes('/iaaData') && <div style={{ left: left + 10, position: 'absolute' }}>
                <Select
                    showSearch
                    style={{ width: 100 }}
                    placeholder={'请选择业务类型'}
                    filterOption={(input, option) =>
                        (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    onChange={(type) => {
                        let newApplist = appList.filter(item => item.productType === type)
                        sessionStorage.setItem('mediaPlatform', newApplist?.[0]?.mediaPlatform)
                        newApplist?.[0]?.mediaPlatform && haveTo(newApplist?.[0]?.mediaPlatform as any);
                        setInitialState({ ...initialState, iaaApp: newApplist?.[0]?.value, mediaPlatform: newApplist?.[0]?.mediaPlatform })
                        setProductType(type)
                    }}
                    value={productType}
                    options={productTypeList}
                />
                <Select
                    showSearch
                    style={{ width: 100, marginLeft: 10 }}
                    placeholder={'请选择媒体'}
                    filterOption={(input, option) =>
                        (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    onChange={(type) => {
                        let newApplist = appList.filter(item => item.productType === productType).filter(item => item.mediaPlatform === type)
                        sessionStorage.setItem('mediaPlatform', type)
                        haveTo(type as any)
                        setInitialState({ ...initialState, iaaApp: newApplist?.[0]?.value, mediaPlatform: type })
                    }}
                    value={initialState?.mediaPlatform}
                    options={mediaPlatformList}
                />
                <Select
                    showSearch
                    style={{ width: 200, marginLeft: 10 }}
                    placeholder={'请选择应用'}
                    filterOption={(input, option) => (option?.name as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    value={initialState?.iaaApp}
                    onChange={(e) => setInitialState({ ...initialState, iaaApp: e })}
                    loading={getAppList.loading}
                >
                    {appList.filter(item => item.productType === productType).filter(item => item.mediaPlatform === initialState?.mediaPlatform).map(item => {
                        return <Select.Option key={item.value} value={item.value} name={item.label}>
                            <Space align='center'>
                                <AntdAvatar shape="square" style={{ marginBottom: 4 }} size={24} icon={<UserOutlined />} src={item?.icon} />
                                <span>{item.label}</span>
                            </Space>
                        </Select.Option>
                    })}
                </Select>
            </div>}

            <Space className={className}>
                {versionsOpen && <div onClick={versionsOpen && inform}>
                    <Badge count={versionsOpen && 1} size='small' offset={[2, 0]}>
                        <span style={{ cursor: 'pointer' }} ><BellOutlined /></span>
                    </Badge>
                </div>}
                <Avatar />
                <Tag color="#87d068" onClick={handleFullScreen}>全屏模式</Tag>
            </Space>
        </div>
    );
};
export default GlobalHeaderRight;
