
import HocError from '@/Hoc/HocError'
import { message, Tabs } from 'antd'
import React, { useCallback, useState } from 'react'
import './index.less'

import Plan from './components/plan'
import LandingPage from '../../launchManage/weChat/components/landingPage'
import CreatePlan from './components/createPlan'
import { useModel } from 'umi'
import { getCookie, setCookie } from '@/utils/cry'
import AdLogin from '../../launchManage/components/adLogin'
/** 投放管理 */
const WeChatNew: React.FC = () => {
    const [authData, setAuthData] = useState<{ base64: string, code: string }>({ base64: '', code: '' })
    const [radioIndex, setRadioIndex] = useState<string>('b')
    const [data, setData] = useState<{ type: string, item: any } | undefined>(undefined)
    const { loginAd } = useModel('useLaunch.useAdAuthorize')
    const userId = useModel('@@initialState', model => model.initialState?.currentUser?.userId as string)
    const planCallBack = useCallback((type: string, item: any) => {
        console.log(type, item);
        setData({
            type,
            item
        })
        setRadioIndex('c')
    }, [radioIndex])
    /**验证授权*/
    const checkLogin = useCallback((fn: () => void) => {
        let isLogin = getCookie('mpLogin' + userId) || getCookie(userId)
        if (!isLogin) {
            let hide = message.warning('验证授权状态中,成功授权后请重新点击....', 0)
            loginAd.run({ scanCode: 'wx' }).then((res: any) => {
                if (res?.code === 1003 && res?.data?.base64) {
                    setAuthData(res?.data)
                } else if (res?.code === 500) {
                    console.log('接口出错')
                } else if (res?.code === 200) { 
                    console.log('已授权3', res)
                    setCookie('mpLogin' + userId, 'true', 1)
                    fn()
                }
                hide()
            })
        } else {
            fn()
        }
    }, [])
    return <div className="weChat">
        <Tabs activeKey={radioIndex} className="adMonitorListTab" type="card" onChange={(activeKey: string) => {
            if (activeKey === 'c') {
                checkLogin(() => setRadioIndex(activeKey))
            } else {
                setRadioIndex(activeKey)
            }
        }}>
            <Tabs.TabPane tab="计划列表" key="b" />
            <Tabs.TabPane tab="推广页" key="d" />
            <Tabs.TabPane tab="创建计划" key="c" />
        </Tabs>
        {
            radioIndex === 'd' ? <LandingPage checkLogin={checkLogin}></LandingPage> :
            radioIndex === 'b' ? <Plan planCallBack={planCallBack} checkLogin={checkLogin}></Plan> :
            radioIndex === 'c' ? <CreatePlan data={data} ></CreatePlan> : null
        }
        {/* 授权登录 */}
        <AdLogin onClose={() => { setAuthData({ base64: '', code: '' }) }} value={authData} onChange={() => { setAuthData({ base64: '', code: '' }) }} />
    </div>
}

export default HocError(WeChatNew)