import { getRouter } from "@/utils/utils";
import { observable, runInAction } from "mobx";
import { getMenu, loginUserInfo, outLogin, selectCompanyApi } from "../API";
import { exitFullScreen, isFull, requestFullScreen } from "../utils/fullScreen";

export interface DataProps {
    /**用户初始信息*/
    userInfo: any;
    /**菜单*/
    menus: any;
    /**按钮权限*/
    btnAuthority: any[];
    /**公司列表*/
    companyList: any[];
    /**左侧菜单是否收起*/
    collapsed: boolean,
    /**是否是移动端*/
    isMobile: boolean,
    /**是否是全屏*/
    isFull: boolean,
    /**是否隐藏搜索框 */
    isFullscreen: boolean
    routerLoading: boolean
}

/**
 * 全局需要当前登录的状态
 * */
const initStore: {
    data: DataProps;
    /**初始化操作*/
    userInit(): Promise<void>;
    /**获取用户信息*/
    getUserInfo(): Promise<void>;
    /**获取菜单*/
    menuInfo(): Promise<void>;
    /**退出登录*/
    loginOut(): Promise<void>;
    /**切换公司*/
    selectCompany(companyId: number): Promise<void>;
    /**菜单折叠事件*/
    menuCollapsed(collapsed: boolean): Promise<void>;
    /**全屏操作*/
    handleFullScreen(): Promise<void>;
    /**是否是移动端*/
    handleMobile(): Promise<void>;
    /**修改data的值 */
    updata(data: Partial<DataProps>): Promise<void>;
} = {
    data: {
        userInfo: { userId: null },//用户初始信息
        menus: {},//菜单
        btnAuthority: [],//按钮权限
        companyList: [],//公司列表
        collapsed: false,//左侧菜单是否收起
        isMobile: false,//是否是移动端
        isFull: false,//是否是全屏
        isFullscreen: false,
        routerLoading: true,
    },
    /**初始化操作*/
    async userInit() {
        this.getUserInfo()
        this.menuInfo()
        this.handleMobile()
    },
    async updata(data) {
        this.data = { ...this.data, ...data }
    },
    /**获取用户信息*/
    async getUserInfo() {
        await loginUserInfo().then(res => {
            runInAction(() => {
                this.data.userInfo = { ...res?.data?.userInfo, onlineCompanyId: res?.data?.onlineCompanyId }
                this.data.companyList = res?.data?.companyRelationInfo
                let userName = res?.data?.userInfo?.nickname
                let userId = res?.data?.userInfo?.userId
                sessionStorage.setItem('userName', userName)
                sessionStorage.setItem('userId', userId)
                sessionStorage.setItem('powerLevel', res?.data?.userInfo?.powerLevel)
            })
        })
    },
    /**获取菜单*/
    async menuInfo() {
        this.data.routerLoading = true
        await getMenu().then(res => {
            // res.data = menu//=================临时虚拟数据==================
            let menu = getRouter(res?.data)
            let btn: any = []
            //返回按钮路由
            function btnFun(items: any) {
                items?.childrenBtn?.forEach((b: any,) => {
                    btn.push(b.title)
                })
            }
            //返回子路由
            function routeFun(items: any) {
                return items.children.map((route: any) => {//循环重组
                    if (route?.children?.length > 0) {
                        routeFun(route)
                    }
                    if (route?.childrenBtn?.length > 0) {
                        btnFun(route)
                    }
                })
            }
            if (menu) {//添加按钮权限
                Object.values(menu).forEach((item: any) => {
                    if (item?.length > 0) {
                        routeFun(item[0])
                    }
                })
            }
            runInAction(() => {
                // 过滤掉空的
                let arr = Object.keys(menu)?.filter(key => {
                    return menu[key]?.length > 0
                })
                let obj: any = {}
                arr.forEach(a => {
                    menu[a][0].children = menu[a][0].children?.filter((item: { title: any; }) => {
                        let noArr = ["企微信息", "企微客户联系成员", "企微客服", "企微客服消息", "投诉信息"]
                        return noArr.every(i => i !== item.title)
                    })//过滤不要的菜单
                    obj[a] = menu[a]
                })
                // 赋值
                this.data.menus = obj
                this.data.btnAuthority = btn
            })

        })
        runInAction(() => {
            this.data.routerLoading = false
        })
    },
    /**退出登录*/
    async loginOut() {
        outLogin().then(res => {
            localStorage.removeItem('Admin-Token')
            sessionStorage.removeItem('userId')
            window.location.href = window.location.origin + '/#/login'
        })
    },
    /**切换公司*/
    async selectCompany(companyId: number) {
        selectCompanyApi(companyId).then(res => {
            localStorage.setItem('Admin-Token', res?.data?.token)
            window.location.reload()
        })
    },
    /**菜单折叠事件*/
    async menuCollapsed(collapsed: any) {
        runInAction(() => {
            this.data.collapsed = collapsed
        })
    },
    /**是否是移动端*/
    async handleMobile() {
        let u = navigator.userAgent
        let isPhone: any = !!u.match(/AppleWebKit.*Mobile.*/) || u.indexOf('iPad') > -1
        if (isPhone) {
            runInAction(() => {
                this.data.isMobile = isPhone
            })
        }
    },
    /**全屏操作*/
    async handleFullScreen() {
        let isf: any = isFull()
        let f: any = !isf
        if (isf) {
            exitFullScreen()
        } else {
            requestFullScreen()
        }
        runInAction(() => {
            this.data.isMobile = f
        })
    },
}
export default observable(initStore)