import React, { useState, useEffect, useCallback } from 'react'
import { Badge, Card, Col, Menu, Row, Select, Tabs, Tag } from 'antd';
// import './index.less'
import Campaign from './campaign';
import AdAccount from './adAccount';
import Ad from './ad';
import Creative from './creative';
import LandingPage from './landingPage';
import { getAdAccountAllOfMember } from '@/services/launchAdq/adq';
import Targeting from './targeting';
import { useAjax } from '@/Hook/useAjax';
import { IdcardFilled } from '@ant-design/icons';
import { useModel } from 'umi';
const { TabPane } = Tabs;
let Menus: any = Menu
const tabsConfig = [
    { key: '1', tab: '账户信息', jsx: (props: any) => <AdAccount {...props} /> },
    { key: '2', tab: '计划', jsx: (props: any) => <Campaign {...props} /> },
    { key: '3', tab: '广告', jsx: (props: any) => <Ad {...props} /> },
    { key: '4', tab: '创意', jsx: (props: any) => <Creative {...props} /> },
    { key: '5', tab: '落地页', jsx: (props: any) => <LandingPage {...props} /> },
    { key: '6', tab: '定向', jsx: (props: any) => <Targeting {...props} /> },
]
function Adq() {
    const userInfo = useModel('@@initialState', model => model.initialState?.currentUser)
    const allOfMember = useAjax(() => getAdAccountAllOfMember(), { formatResult: true })
    const [userAll, setUserAll] = useState([])
    const [activeKey, setActiveKey] = useState('1')
    const [userId, setUserId] = useState<any>(userInfo?.userId?.toString())
    const [selectedArr, setSelectedArr] = useState([])
    const [queryParmas, setQueryParmas] = useState<any>({
        accountId: undefined,//账户ID
        campaignId: undefined,//计划ID
        adgroupId: undefined,//广告ID
        adcreativeId: undefined,//创意ID
        pageId: undefined,//落地页ID
        targetingId: undefined,//定向ID
    })
    const [idS, setIds] = useState({//需要用到的accountId，adAccountId
        accountId: '',
        adAccountId: ''
    })
    // 点击table中的ID添加对应条件
    const tableIdClick = useCallback((props: {
        activeKey: string,
        parma: {
            accountId?: string,//账户ID
            campaignId?: string,//计划ID
            adgroupId?: string,//广告ID
            adcreativeId?: string,//创意ID
            pageId?: string,//落地页ID
            targetingId?: string,//定向ID
        }
    }) => {
        // 暂时注释不开放
        let { activeKey, parma } = props
        setQueryParmas({ ...queryParmas, ...parma })
        setActiveKey(activeKey)

    }, [queryParmas, activeKey])
    // 获取组员
    useEffect(() => {
        allOfMember.run().then(res => {
            if (res?.data) {
                let useAll: any = []
                res?.data?.forEach((item: { key: { userId: any; nickName: any; }; value: any[]; }) => {
                    let obj = {
                        key: item.key.userId,
                        label: item.key.nickName,
                        icon: <IdcardFilled />,
                    }
                    if (item?.value) {
                        obj['childrenarr'] = item?.value?.map(item => {
                            return { key: item.accountId + '_' + item.id, label: item?.remark ? item.accountId + '_' + item?.remark : item.accountId }
                        })
                    }
                    useAll.push(obj)
                })
                setUserAll(useAll)
            }
        })
    }, [])
    //选中的组员的子账号
    useEffect(() => {
        if (userAll.length > 0 && userId) {
            let newArr: any = userAll?.filter((item: any) => item.key == userId)
            setSelectedArr(newArr[0]?.childrenarr || [])
        }
    }, [userAll, userId])
    // 用户点击table中的账号ID处理
    useEffect(() => {
        if (selectedArr.length > 0 && queryParmas.accountId) {
            let obj: any = selectedArr?.filter((item: any) => item.key.includes(queryParmas.accountId))[0]
            if (obj) {
                let arr = obj.key.split('_')
                setIds({ accountId: arr[0], adAccountId: arr[1] })
            }
        }
    }, [queryParmas, selectedArr])
    // // 初始跳转到自己的名称
    useEffect(() => {
        if (userAll?.length > 0 && userId) {
            let topEq = userAll?.findIndex((item: any) => item.key == userId)
            let em: any = document.getElementById('myMenus')
            console.log(topEq)
            if (em) {
                em.scrollTop = (52 - 4) * topEq
            }
        }
    }, [userId, userAll])
    //判定是否从任务列表跳转过来
    useEffect(()=>{
        let data = sessionStorage.getItem('adqQuery')
        if(data){
            let obj = JSON.parse(data)
            Object.keys(obj).forEach(key=>{
                switch(key){
                    case 'accountId':
                        setQueryParmas(obj)
                        setActiveKey('1')
                        break
                    case 'campaignId':
                        setQueryParmas(obj)
                        setActiveKey('2')
                        break
                    case 'adgroupId':
                        setQueryParmas(obj)
                        setActiveKey('3')
                        break
                    case 'adcreativeId':
                        setQueryParmas(obj)
                        setActiveKey('4')
                        break
                }
            })
            sessionStorage.removeItem('adqQuery')
        }
    },[])
    return <Row style={{ position: 'relative' }}>
        <Col style={{ height: '100%', minHeight: 'calc(100vh - 100px)', overflowY: 'auto', position: 'absolute', left: 0, top: 0, bottom: 0, width: 150, background: '#fff' }}>
            <Select
                placeholder='名称搜索'
                style={{ width: '100%' }}
                showSearch
                filterOption={(input: any, option: any) => {
                    return (option!?.children as unknown as string)?.toLowerCase()?.includes(input?.toLowerCase())
                }

                } allowClear onChange={(value: any) => {
                    if (value) {
                        setUserId(value.toString())
                    }
                }}>
                {
                    userAll.map((item: any) => {
                        return <Select.Option value={item.key} key={item.key}>{item.label}</Select.Option>
                    })
                }
            </Select>
            <Menus
                id='myMenus'
                theme='light'
                onClick={(e: any) => {//点击菜单
                    setUserId(e.key)
                }}
                selectedKeys={userId}
                mode="inline"
                multiple={false}
                items={userAll}
                style={{
                    overflowY: 'auto',
                    height: 'calc(100vh - 150px)',
                    overflowX: 'hidden'
                }}
            />
        </Col>
        <Col span={21} style={{ marginLeft: 150 }}>
            <Card>
                <Tabs activeKey={activeKey} type="card" onChange={(activeKey) => { setActiveKey(activeKey) }} tabBarExtraContent={
                    <Select
                        placeholder='广点通账号'
                        style={{ minWidth: 200 }}
                        showSearch
                        allowClear 
                        onChange={(value: any) => {
                            let accountId = ''
                            let adAccountId = ''
                            if (value) {
                                let arr = value.split('_')
                                accountId = arr[0]
                                adAccountId = arr[1]
                            }
                            setIds({ accountId, adAccountId })
                        }}
                        value={idS.accountId ? idS.accountId + '_' + idS.adAccountId : null}
                    >
                        {
                            selectedArr?.map((item: any) => {
                                return <Select.Option value={item.key} key={item.key}>{item.label}</Select.Option>
                            })
                        }
                    </Select>
                }>
                    {
                        tabsConfig?.map(item => {
                            return <TabPane tab={item.tab} key={item.key} >
                                <>
                                    {/* 点击了列表中的ID默认展示并搜索对应ID条件 */}
                                    <Row >
                                        <Col>
                                            {
                                                Object.keys(queryParmas)?.filter(key => queryParmas[key])?.map(key => {
                                                    enum nameEnum {
                                                        accountId = '账户ID',
                                                        campaignId = '计划ID',
                                                        adgroupId = '广告ID',
                                                        adcreativeId = '创意ID',
                                                        pageId = '落地页ID',
                                                        targetingId = '定向ID',
                                                    }
                                                    return <Badge
                                                        key={key}
                                                        count={
                                                            <span
                                                                style={{ width: 14, height: 14, borderRadius: '50%', background: '#ff4d4f', boxShadow: '0 0 0 1px #fff', color: '#fff', textAlign: 'center' }}
                                                                onClick={() => {
                                                                    setQueryParmas({ ...queryParmas, [key]: '' })
                                                                    setIds({
                                                                        accountId: '',
                                                                        adAccountId: ''
                                                                    })
                                                                }}
                                                            >x</span>}
                                                        size='small'
                                                        offset={[-20, 2]}
                                                        style={{ cursor: 'pointer' }}
                                                    >
                                                        <Tag style={{ marginRight: 20, marginBottom: 20 }}>{nameEnum[key]}：{queryParmas[key]}</Tag>
                                                    </Badge>
                                                })
                                            }
                                        </Col>
                                    </Row>
                                    {activeKey === item.key && item.jsx({ ...idS, userId, queryParmas, tableIdClick })}
                                </>
                            </TabPane>
                        })
                    }
                </Tabs>
            </Card>
        </Col>
    </Row>

}
export default Adq