import { initTrackAll, trackEvent } from "../tracking/TrackAll";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { routes } from "@db/routes";
import {
    ROUTE_PATH,
    ROUTE_TYPE_CUSTOM,
    ROUTE_TYPE_FULL,
    ROUTE_TYPE_IN,
    ROUTE_TYPE_OUTLINK,
    ROUTE_TYPE_POP,
    ROUTE_TYPE_POP_OR_FULL, SIDE_TYPE_NOMAL
} from "@constants/routes";
import { REQ_STATUS } from "@api/config";
import {
    buildReqReducer,
    reqBindSMS,
    reqChangeEmail,
    reqChangeInfo,
    reqChangePass,
    reqChangePhone,
    reqCustomLeaveMsg,
    reqCustomService,
    reqFavoGet, reqForgetPass,
    reqForgetPayPass,
    reqGameCardInfo,
    reqGameInfo,
    reqGetRoutes,
    reqLogin,
    reqLogout,
    reqRegister,
    reqRegisterGold,
    reqSendCode,
    reqSMSLogin,
    reqUpdateFavoInfo,
    reqFreeWithdraw,
    reqFreeWithdrawMission,
    reqFreeWithdrawClaim,
    reqHolidaysGiftInfo,
    reqHolidaysActInfo,
    reqGetPwaBonus
} from "@features/api";
import { toast } from 'react-toastify';
import { getFinger2DeviceId, getHttpMsg, localStorageGet, localStorageSet } from "@utils/helpers";
import {
    LOCAL_ACTIVITY_C,
    LOCAL_CUSTOM_LOCK,
    LOCAL_FAVO_IDS, LOCAL_GAME_URL,
    LOCAL_IS_LOGIN,
    LOCAL_LAST_LOGIN_TYPE,
    LOCAL_SIGN,
    LOCAL_USER_INFO,
    LOCAL_VISTOR_ID
} from "@constants/localkey";
import { reqPayConfig } from "@features/paySlice";
import FingerprintJS from '@fingerprintjs/fingerprintjs';
import { APP_LOGIN_TYPE } from "@constants/app";
import { v4 as uuidv4 } from 'uuid';
const i18n = global.i18n;
const generateNavs = (routes) => {
    const navs = [];
    const allNavs = [];
    const allTopNavs = [];
    for (let i = 0; i < routes.length; i++) {
        let route = routes[i];
        if (!route.side) continue;
        allNavs.push(route);
        if (route.side === SIDE_TYPE_NOMAL) allTopNavs.push(route);
        let block = route.block != null ? route.block : 0;
        let temp = navs[block];
        if (temp == null) temp = [];
        temp.push(route);
        navs[block] = temp;
    }
    return { navs, allNavs, allTopNavs };
};
const generateRoutes = (routes, asyncRoutes = []) => {
    const allMap = {};
    const inRoutes = [];
    const popRoutes = [];
    //路由等级
    //ppath parent path
    const _generate = (list, plevel, ppath) => {
        Object.keys(list).map((key) => {
            let route = list[key];
            if (route) {
                if (allMap[route.path] == null) {
                    //level
                    route.plv = plevel;
                    route.ppath = ppath;
                    route.lv = plevel + key + "_";
                    // if (route.path==="#/signin"||route.path==="#/signup"){
                    //     route.component="Login";
                    // }
                    if (route.path === "#/pay") {
                        route.component = "deposit";
                    }
                    if (route.path === "#/saque") {
                        route.component = "withdraw";
                    }
                    // if (route.path==="/sports"){
                    //     route.subs=[
                    //         {
                    //             "id": 100,
                    //             "parent_id": 4,
                    //             "index": 100,
                    //             "path": "/sports/soccer-1",
                    //             "type": 0,
                    //             "side": 1,
                    //             "block": 1,
                    //             "title": "Soccer",
                    //             "icon": "icon_Soccer",
                    //             "fill": ";;",
                    //             "style": 1,
                    //             "component": "Sport",
                    //             "query": "",
                    //             "login": 0,
                    //             "lpath": "#\/signup",
                    //             "state": 15,
                    //             "subs": []
                    //         },
                    //         {
                    //             "id": 101,
                    //             "parent_id": 4,
                    //             "index": 101,
                    //             "path": "/sports/basketball-2",
                    //             "type": 0,
                    //             "side": 1,
                    //             "block": 1,
                    //             "title": "Basketball",
                    //             "icon": "icon_Basketball",
                    //             "fill": ";;",
                    //             "style": 1,
                    //             "component": "Sport",
                    //             "query": "",
                    //             "login": 0,
                    //             "lpath": "#\/signup",
                    //             "state": 15,
                    //             "subs": []
                    //         }
                    //     ]
                    // }
                    // if (route.path==="/sports"){
                    //     route.type=ROUTE_TYPE_FULL;
                    // }
                    allMap[route.path] = route;
                    let type = route.type;
                    if (type === ROUTE_TYPE_IN || type === ROUTE_TYPE_FULL) inRoutes.push(route);
                    else if (type === ROUTE_TYPE_POP_OR_FULL) popRoutes.push(route);
                    else if (type === ROUTE_TYPE_POP) popRoutes.push(route);
                    else if (type === ROUTE_TYPE_CUSTOM) popRoutes.push(route);
                }
                let subs = route.subs;
                if (subs != null) _generate(subs, route.lv, route.path);
            }
        });
    };
    const allroutes = [...routes, ...asyncRoutes];
    _generate(allroutes, "", "");
    const gnavs = generateNavs(allroutes);
    return { allMap, inRoutes, popRoutes, blockNavs: gnavs.navs, allNavs: gnavs.allNavs, allTopNavs: gnavs.allTopNavs };
};
const parseThemeStypes = (data) => {
    if (data != null) {
        for (const key in data) {
            let item = data[key];
            if (item != null) {
                if (typeof item == "string") {
                    if (item.indexOf(";") != -1) {
                        data[key] = item.split(";");
                    }
                }
            }
        }
    }
    return data;
};
const parseStyles = (data) => {
    let styles = {};
    if (data != null) {
        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            if (item) {
                let styleid = item.styleid;
                let style = item.style;
                let json = {};
                if (style != null && style != "") {
                    json = JSON.parse(style);
                    json['dark'] = parseThemeStypes(json['dark']);
                    json['light'] = parseThemeStypes(json['light']);
                }
                styles[styleid] = { styleid, style: json };
            }
        }
    }
    return styles;
};
const parseBlocks = (data) => {
    let blocks = {};
    if (data != null) {
        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            if (item) {
                blocks[item.block] = item;
            }
        }
    }
    return blocks;
};
const getFavorites = (data) => {
    let favorites = [];
    if (data != null && !!data.length) {
        let arr = data.split(",");
        if (arr) {
            for (let i = 0; i < arr.length; i++) {
                favorites.push(parseInt(arr[i]));
            }
        }
        localStorageSet(LOCAL_FAVO_IDS, JSON.stringify(favorites));
    }
    else {
        let localFavorites = localStorageGet(LOCAL_FAVO_IDS, "");
        if (localFavorites !== "") favorites = JSON.parse(localFavorites);
    }
    return favorites;
};
const reducerRoutes = (state, action) => {
    let json = action.payload;
    if (json && json.code == 0) {
        let data = json.data == null ? [] : json.data;
        let generData = generateRoutes(state.routes, data);
        let styles = parseStyles(json.styles);
        let blocks = parseBlocks(json.blocks);
        let user = json.user;
        let isLogin = 0;
        let userInfo = {};
        let hasPhone = 0;
        if (user) {
            if (typeof user == "object") {
                isLogin = 1;
                // user.InsurePass=0;
                userInfo = user;
                //请求pay
                // global.dispatch(reqPayConfig(user));
                let sign = user.sign;
                if (sign != null) localStorageSet(LOCAL_SIGN, sign);

                if (user.Phone !== "" && user.Phone.startsWith(user.RegisterLocation)) {
                    hasPhone = 1;
                }
                //同步lang
                if (user.DefaultLanguage != null) global.i18n.setLocalLangFromS(user.DefaultLanguage);
                checkChannel(user);
            }
        }
        let conf = json.conf;
        let hallServerUrl = '';
        let promoteInstall = 0;
        let guest = 0;
        let upgradeBonus = 0;
        let registerBonus = 0;
        let recommendGame = "";
        let popWheel = 0;
        let popBindPhone = 0;
        let firstBonus = 0;
        let openRelief = 0;
        let accountLogin = 1;
        let loginOpen = "";
        let registerOpen = "";
        let serviceLink = "";
        let landscapeGames = [];
        let area = global.getLocalAreaID();
        //sport 配置
        let bbConf = null;
        let popFirst = 0;
        let showInstall = 0;
        let download = {};
        let popPwaBonus = 0;
        if (conf) {
            if (!!conf.hall) hallServerUrl = conf.hall;
            if (!!conf.DOLLAR) global.DOLLAR = conf.DOLLAR;
            if (!!conf.currency) global.currency = conf.currency;
            global.pf = conf.pf;
            //平台配置
            if (!!conf.pf && !!conf.pf.id) {
                let { type, id } = conf.pf;
                initTrackAll(type, id, isLogin ? userInfo.UserID : null);
            }
            //promoteInstall
            if (!!conf.promoteInstall) promoteInstall = conf.promoteInstall;
            //guest
            if (!!conf.guest) guest = conf.guest;
            //绑定手机奖励
            if (!!conf.upgradeBonus) upgradeBonus = conf.upgradeBonus;
            ///初始注册奖励
            if (!!conf.registerBonus) registerBonus = conf.registerBonus;
            ///领取注册奖励后进入的游戏
            if (!!conf.recommendGame) recommendGame = conf.recommendGame;
            //客服地址
            if (!!conf.serviceLink) serviceLink = conf.serviceLink;

            //弹出转盘
            if (!!conf.popWheel) popWheel = conf.popWheel;
            //弹出绑定电话奖励,并显示浮标
            if (!!conf.popBindPhone) popBindPhone = hasPhone ? 0 : conf.popBindPhone;
            //显示首冲浮标
            if (!!conf.firstBonus) firstBonus = conf.firstBonus;
            //显示救济浮标
            if (!!conf.openRelief) openRelief = conf.openRelief;
            //sport 配置
            if (!!conf.bb) {
                bbConf = conf.bb;
                if (userInfo != null) userInfo.bb = bbConf;
            }
            if (!!conf.loginOpen) loginOpen = conf.loginOpen;
            if (!!conf.registerOpen) registerOpen = conf.registerOpen;
            if (!!conf.popFirst) popFirst = conf.popFirst;
            if (!!conf.showInstall) showInstall = conf.showInstall;
            //download 配置
            if (!!conf.download) download = conf.download;
            if (!!conf.LandscapeGames) landscapeGames = conf.LandscapeGames;

            // adjust相关配置
            if (!!conf.AdjustToken && !!conf.AdjustConfig) global.tracker.initAdjust(conf.AdjustToken, conf.AdjustConfig);

            if (!!conf.popPwaBonus) popPwaBonus = conf.popPwaBonus;
        }
        //favorites
        // let favorites=getFavorites(json.favorites);
        Object.assign(state, {
            routes: state.routes,
            asyncRoutes: data,
            styles,
            blocks,
            ...generData,
            isLogin: isLogin,
            userInfo,
            hallServerUrl,
            promoteInstall,
            guest,
            upgradeBonus,
            recommendGame,
            serviceLink,
            registerBonus,
            popWheel,
            popBindPhone,
            firstBonus,
            openRelief,
            bbConf,
            accountLogin,
            area,
            loginOpen,
            registerOpen,
            popFirst,
            showInstall,
            download,
            landscapeGames,
            popPwaBonus
        });
        // Object.assign(state, {routes:state.routes,asyncRoutes:data,styles:styles,blocks:blocks,...generData,isLogin:isLogin,userInfo:userInfo,hallServerUrl:hallServerUrl,promoteInstall:promoteInstall,guest:guest,upgradeBonus:upgradeBonus});
    }
};
const routesStatus = (state, status, arg) => {
    state.status = status;
};
//login
const getLocalUserInfo = () => {
    let user = {};
    let value = localStorageGet(LOCAL_USER_INFO, null);
    if (value && value != "") {
        user = JSON.parse(value);
    }
    return user;
};
const getLocalIsLogin = () => {
    let islogin = localStorageGet(LOCAL_IS_LOGIN, 0);
    islogin = Number(islogin);
    return islogin;
};
const getMsg = (payload) => {
    return getHttpMsg(payload);
};
//检查渠道
const checkChannel = (userInfo) => {
    if (userInfo != null && userInfo.Channel != null) {
        let Channel = parseInt(userInfo.Channel);
        let localC = localStorageGet(LOCAL_ACTIVITY_C, "");
        if (localC != null && localC !== "") {
            localC = parseInt(localC);
            if (Channel !== localC) {
                localStorageSet(LOCAL_ACTIVITY_C, Channel + "");
                let search=window.location.search || "";
                const params = new URLSearchParams(search);
                // 移除参数c和bfp
                params.delete('c');
                params.delete('bfp');
                search=params.toString();
                let url=`${window.location.origin}${search!==""?"?"+search:""}`;
                window.location.replace(url);
            }
        }
    }
};
const parseLogin = (state, action, arg, isShowMsg = true) => {
    let payload = action.payload;
    let code = payload.code;
    let msg = getMsg(payload);
    //success
    if (code == 200) {
        let data = payload.data;
        if (data.bb == null) {
            if (state.userInfo != null) data.bb = state.userInfo.bb;
        }
        if (arg) {
            if (arg.DefaultLanguage != null) data.lang = arg.DefaultLanguage;
            else {
                if (state.userInfo != null && state.userInfo.lang != null) data.lang = state.userInfo.lang;
            }
        }
        state.userInfo = data;
        state.isLogin = 1;
        if (!!data.recommendGame) state.recommendGame = data.recommendGame;
        // localStorageSet(LOCAL_USER_INFO,JSON.stringify(data));
        // localStorageSet(LOCAL_IS_LOGIN,1);
        let sign = data.sign;
        if (sign != null) localStorageSet(LOCAL_SIGN, sign);
        if (isShowMsg) toast.success(msg, { toastId: "login" });
        //请求pay
        // global.dispatch(reqPayConfig(data));
        if (!!data.reg) {
            //新注册的
            trackEvent("CompleteRegistration", { external_id: data.UserID });
        }
        checkChannel(data);
        // if (arg != null) {
        //     if (arg.type != null && arg.type === APP_LOGIN_TYPE.GUEST) {
        //         let { account, password } = data;
        //         if (account != null && password != null) {
        //             global.showSaveAccount({
        //                 account,
        //                 password
        //             })
        //         }
        //     }
        // }
    }
    else {
        if (isShowMsg) toast.error(msg, { toastId: "login" });
    }
    if (arg) {
        let callback = arg.callback;
        if (callback != null) callback(code, payload.data);
    }
};
const reducerLogin = (state, action, arg) => {
    // toast.success("success");
    parseLogin(state, action, arg);
};
const loginStatus = (state, status, arg) => {
    state.loginStatus.login = status;
};
const reducerReg = (state, action, arg) => {
    parseLogin(state, action, arg, false);
};
const regStatus = (state, status, arg) => {
    state.loginStatus.register = status;
};
const reducerRegGold = (state, action, arg) => {
    let payload = action.payload;
    //payload:{"data":{"user":{"InsureScore":10,"Registed":1,"message":"Success"}},"result":"","msg":"success","code":200}
    //payload:{"data":[],"msg":"Fail","code":301}
    let code = payload.code;
    let msg = getMsg(payload);
    if (code == 200) {
        let data = payload.data || {};
        let user = data.user;
        if (!!user) {
            if (user.InsureScore != null) {
                state.userInfo.InsureScore = Number(user.InsureScore);
            }

            if (user.Registed != null) {
                state.userInfo.Registed = Number(user.Registed);
            }
        }
    } else {
        toast.error(msg, { toastId: "regGold" });
    }
};
const regGoldStatus = (state, status, arg) => {
    state.loginStatus.regGold = status;
};
const reducerLogout = (state, action, arg) => {
    let payload = action.payload;
    let code = payload.code;
    let msg = getMsg(payload);
    if (code == 200) {
        state.userInfo = {};
        state.isLogin = 0;
        global.newUserPrompted = true;
        localStorageSet(LOCAL_SIGN, "");
        // localStorageSet(LOCAL_USER_INFO,"");
        // localStorageSet(LOCAL_IS_LOGIN,0);
        toast.success(msg, { toastId: "logout" });
    }
    else {
        toast.error(msg, { toastId: "logout" });
    }
};
const logoutStatus = (state, status, arg) => {
    state.loginStatus.logout = status;
};
//login
//modify
const reducerChangePass = (state, action, arg) => {
    // let payload=action.payload;
    // let code=payload.code;
    // let msg=getMsg(payload);
    // if (code==200){
    //     toast.success(msg);
    // }
    // else
    // {
    //     toast.error(msg);
    // }
    parseLogin(state, action, arg);
};
const changePassStatus = (state, status, arg) => {
    state.modifyStatus.password = status;
};
const reducerChangeInfo = (state, action, arg) => {
    // let payload=action.payload;
    // let code=payload.code;
    // let msg=getMsg(payload);
    // if (code==200){
    //     toast.success(msg);
    // }
    // else
    // {
    //     toast.error(msg);
    // }
    parseLogin(state, action, arg);
};
const changeInfoStatus = (state, status, arg) => {
    state.modifyStatus.info = status;
};
const reducerChangePhone = (state, action, arg) => {
    parseLogin(state, action, arg);
};
const changePhoneStatus = (state, status, arg) => {
    state.modifyStatus.phone = status;
};
const reducerChangeEmail = (state, action, arg) => {
    parseLogin(state, action, arg);
};
const changeEmailStatus = (state, status, arg) => {
    state.modifyStatus.phone = status;
};
//modify
//gameinfo
const reducerGameInfo = (state, action, arg) => {
    // parseLogin(state,action,arg);
    parseLogin(state, action, arg, false);
};
const gameInfoStatus = (state, status, arg) => {
    state.gameInfoStatus = status;
};
//gameinfo
//custom
const reducerCustom = (state, action, arg) => {
    let payload = action.payload;
    if (payload && payload.code === 200) {
        state.customerInfo = payload.data;
    }
};
const customStatus = (state, status, arg) => {
    state.customServiceStatus = status;
};
const reducerCustomLeaveMsg = (state, action, arg) => {
    let payload = action.payload;
    if (payload != null) {
        if (payload && payload.code === 200) {
            localStorageSet(LOCAL_CUSTOM_LOCK, Date.now());
            toast.success(i18n.t("customer.TopTip_succeed"), { toastId: "customLeaveMsg" });
        }
        else {
            toast.error(i18n.t("customer.TopTip_fail"), { toastId: "customLeaveMsg" });
        }
    }
    if (arg && arg.callback != null) {
        arg.callback(payload);
    }
};
const customLeaveMsgStatus = (state, status, arg) => {
    state.customLeaveMsgStatus = status;
};
const reducerUpdateFavoInfo = (state, action, arg) => {
    let payload = action.payload;
    let msg = getHttpMsg(payload);
    if (payload && payload.code === 200) {
        if (msg != null && msg !== "") {
            toast.success(msg, { toastId: "updateFavoInfo" });
        }
    }
    else {
        if (msg != null && msg !== "") {
            toast.error(msg, { toastId: "updateFavoInfo" });
        }
    }
};
const reducerFavoGet = (state, action, arg) => {
    let payload = action.payload;
    if (payload && payload.code === 200) {
        let data = payload.data;
        let favorites = [];
        if (data != null) {
            for (let i = 0; i < data.length; i++) {
                let item = data[i];
                if (item) favorites.push(item.id);
            }
        }
        state.favorites = favorites;
    }
};
const reducerFreeWithdraw = (state, action, arg) => {
    let payload = action.payload;
    if (payload && payload.code === 200) {
        let data = payload.data;
        // let favorites = [];
        // if (data != null) {
        //     for (let i = 0; i < data.length; i++) {
        //         let item = data[i];
        //         if (item) favorites.push(item.id);
        //     }
        // }
        //console.error("data", data);
        state.freeWithdrawInfo = data;
        global.freeTxTotal = data.total;
    }
};

const reducerFreeWithdrawMission = (state, action, arg) => {
    let payload = action.payload;
    if (payload && payload.code === 200) {
        let data = payload.data;
        // let favorites = [];
        // if (data != null) {
        //     for (let i = 0; i < data.length; i++) {
        //         let item = data[i];
        //         if (item) favorites.push(item.id);
        //     }
        // }
        // console.error("data", data);
        state.freeWithdrawMission = data;
    }
};

const reducerFreeWithdrawClaim = (state, action, arg) => {
    let payload = action.payload;
    let msg = getHttpMsg(payload);
    if (payload && payload.code === 200) {
        // toast.success(msg);
        toast.success(i18n.t("withdraw.tip.success"), { toastId: "freeWithdrawClaim" });
        setTimeout(() => {
            global.dispatch(reqGameInfo());
            global.dispatch(reqFreeWithdrawMission());
        }, 1);
    }
    else {
        toast.error(msg, { toastId: "freeWithdrawClaim" });
    }
    if (arg && arg.callback != null) {
        arg.callback(payload);
    }
};

const reducerHolidaysGiftInfo = (state, action, arg) => {
    let payload = action.payload;
    if (payload && payload.code === 200) {
        let data = payload.data;
        state.holidaysGiftInfo = data;
    }
};

const reducerHolidaysActInfo = (state, action, arg) => {
    let payload = action.payload;
    if (payload && payload.code === 200) {
        let data = payload.data;
        state.holidaysActInfo = data;
    }
};


const updateFreeWithdrawClaimStatus = (state, status, arg) => {
    state.freeTxClaimStatus = status;
};

export const getFreeWithdrawClaimStatus = (state) => {
    return state.main.freeTxClaimStatus;
};

const reducerGameCardInfo = (state, action, arg) => {
    let payload = action.payload;
    if (payload && payload.code === 200) {
        let data = payload.data;
        if (data != null) {
            let id = Number(data.id);
            let level_info = data.level_info;
            let level = level_info != null ? 1 : 0;
            let local = parseInt(localStorageGet(LOCAL_GAME_URL + id, 0));
            if (local > 0) level = local;
            state.gameCardInfo[id] = { ...data, level: level };
        }
    }
};
const gameCardInfoStatus = (state, status, arg) => {
    state.gameCardInfoStatus = status;
};
//send code
const reducerSendCode = (state, action, arg) => {
    let payload = action.payload;
    let msg = getHttpMsg(payload);
    if (payload && payload.code === 200) {
        toast.success(msg, { toastId: "sendCode" });
        state.otpTimeStamp = Date.now();
    }
    else {
        toast.error(msg, { toastId: "sendCode" });
    }
};
const sendCodeStatus = (state, status, arg) => {
    state.loginStatus.send_code = status;
};
//bind phone
const reducerBindSMS = (state, action, arg) => {
    let payload = action.payload;
    state.oldUserInfo = null;
    if (payload.code == 301 && payload.data && payload.data.UserID) {
        // 已有账号
        state.oldUserInfo = payload.data;
    } else if (payload.code == 200) {
        toast.success(i18n.t("bindPhone.success"), { toastId: "login" });
    }
    parseLogin(state, action, arg, payload.code != 200);
};
const bindSMSStatus = (state, status, arg) => {
    state.loginStatus.bind = status;
};
//sms login
const reducerSMSLogin = (state, action, arg) => {
    parseLogin(state, action, arg);
};
const smsLoginStatus = (state, status, arg) => {
    state.loginStatus.smslogin = status;
};
//custom
//pwa bonus
const reducerGetPwaBonus = (state, action, arg) => {
    let payload = action.payload;
    let msg = getHttpMsg(payload);
    if (payload && payload.code === 200) {
        toast.success(i18n.t("popPwaBonus.claim_success"), { toastId: "popPwaBonus" });
        state.popPwaBonus = 0;
    } else {
        toast.error(i18n.t("popPwaBonus.claim_failed"), { toastId: "popPwaBonus" });
    }
    if (arg && arg.callback != null) {
        arg.callback(payload);
    }
}
const getPwaBonusStatus = (state, status, arg) => {
    state.pwaBonusStatus = status;
}
//pwa bonus
export const Main = createSlice({
    name: 'main',
    initialState: {
        status: REQ_STATUS.NONE,
        routes: routes,
        asyncRoutes: [],
        styles: {},
        blocks: {},
        ...generateRoutes(routes),
        loginStatus: {
            login: REQ_STATUS.NONE,
            register: REQ_STATUS.NONE,
            regGold: REQ_STATUS.NONE,
            logout: REQ_STATUS.NONE,
            bind: REQ_STATUS.NONE,
            send_code: REQ_STATUS.NONE,
            smslogin: REQ_STATUS.NONE,
        },
        userInfo: null,
        oldUserInfo: null,
        isLogin: 0,
        modifyStatus: {
            info: REQ_STATUS.NONE,
            password: REQ_STATUS.NONE,
            phone: REQ_STATUS.NONE,
            email: REQ_STATUS.NONE
        },
        gameInfoStatus: REQ_STATUS.NONE,
        customLeaveMsgStatus: REQ_STATUS.NONE,
        customServiceStatus: REQ_STATUS.NONE,
        freeTxClaimStatus: REQ_STATUS.NONE,
        //客服
        customerInfo: [],
        //大厅服务器
        hallServerUrl: '',
        //收藏列表
        favorites: [],
        // 免费提现信息
        freeWithdrawInfo: {},
        //免费提现任务
        freeWithdrawMission: {},
        holidaysGiftInfo: {},
        holidaysActInfo: {},
        //当前游戏id
        gameID: 0,
        //服务器踢
        serverKick: 0,
        //安装提示
        promoteInstall: 0,
        //服务器返回777打开充值
        openPay: 0,
        gameCardInfoStatus: REQ_STATUS.NONE,
        //游戏卡信息
        gameCardInfo: {},
        //otp 时间戳
        otpTimeStamp: 0,
        //是否是guest登录
        guest: 0,
        //绑定奖励
        upgradeBonus: 0,
        //初始注册奖励
        registerBonus: 0,
        //领取注册奖励后进入的游戏
        recommendGame: "",
        //客服地址
        serviceLink: "",
        //sport conf
        bbConf: null,
        accountLogin: 0,
        area: 0,
        loginOpen: "",
        registerOpen: "",
        popFirst: 0,
        showInstall: 0,
        download: {},
        landscapeGames: [],
        popPwaBonus: 0,
        pwaBonusStatus: REQ_STATUS.NONE,
    },
    reducers: {
        logout: (state, action) => {
            state.userInfo = {};
            state.isLogin = 0;
            // localStorageSet(LOCAL_USER_INFO,"");
            // localStorageSet(LOCAL_IS_LOGIN,0);
        },
        updateUserInfo: (state, action) => {
            parseLogin(state, action, {}, false);
        },
        updateUserScore: (state, action) => {
            let score = action.payload;
            if (score != null) {
                if (state.userInfo) state.userInfo.Score = Number(score);
            }
        },
        updateAddScore: (state, action) => {
            let score = action.payload;
            if (score != null) {
                if (state.userInfo) state.userInfo.Score = state.userInfo.Score + Number(score);
            }
        },
        updateGameLike: (state, action) => {
            let payload = action.payload;
            let id = payload.id;
            let like = payload.like;
            let favorites = state.favorites;
            let index = favorites.indexOf(id);
            if (like) {
                if (index === -1) {
                    favorites.push(id);
                    state.favorites = favorites;
                }
            }
            else {
                let index = favorites.indexOf(id);
                if (index !== -1) {
                    favorites.splice(index, 1);
                    state.favorites = favorites;
                }
            }
            // localStorageSet(LOCAL_FAVO_IDS,JSON.stringify(favorites));
        },
        onSliceChangeUser: (state, action) => {
            state.favorites = [];
        },
        updateCurrGame: (state, action) => {
            state.gameID = action.payload;
        },
        updateServerKick: (state, action) => {
            state.serverKick = action.payload;
        },
        updateOpenPay: (state, action) => {
            state.openPay = action.payload;
        },
        updateGameRoute: (state, action) => {
            let route = state.allMap[ROUTE_PATH.GAME + "/*"];
            if (route != null) {
                let type = action.payload;
                route.type = type;
            }
        },
        updateGameCardInfo: (state, action) => {
            let { data, level } = action.payload;
            if (data != null) {
                if (level == null) level = 0;
                let id = data.id;
                state.gameCardInfo[id] = { ...data, level };
            }
        },
        updateAreaID: (state, action) => {
            let areaID = action.payload;
            global.setLocalAreaID(areaID);
            // window.location.replace(window.location.href);
            // window.location.reload();
        },
        updateHolidaysGiftSpinTimes: (state, action) => {
            let { left_times } = action.payload;
            if (left_times != null) {
                state.holidaysGiftInfo.user.left_times = left_times;
            }
        },
        updateHolidaysActSpinTimes: (state, action) => {
            let { left_times } = action.payload;
            if (left_times != null) {
                state.holidaysActInfo.user.left_times = left_times;
            }
        },
        changeOldAccount: (state, action) => {
            localStorageSet(LOCAL_LAST_LOGIN_TYPE, APP_LOGIN_TYPE.SMS);
            localStorageSet(LOCAL_SIGN, state.oldUserInfo.sign);
            window.location.reload();
        }
    },
    extraReducers: (builder) => {
        // Add reducers for additional action types here, and handle loading state as needed
        // reducerRoutes(builder);
        buildReqReducer(builder, reqGetRoutes, reducerRoutes, routesStatus);
        buildReqReducer(builder, reqLogin, reducerLogin, loginStatus);
        buildReqReducer(builder, reqRegister, reducerReg, regStatus);
        buildReqReducer(builder, reqRegisterGold, reducerRegGold, regGoldStatus);
        buildReqReducer(builder, reqLogout, reducerLogout, logoutStatus);
        buildReqReducer(builder, reqChangePass, reducerChangePass, changePassStatus);
        buildReqReducer(builder, reqChangeInfo, reducerChangeInfo, changeInfoStatus);
        buildReqReducer(builder, reqChangePhone, reducerChangePhone, changePhoneStatus);
        buildReqReducer(builder, reqChangeEmail, reducerChangeEmail, changeEmailStatus);
        buildReqReducer(builder, reqGameInfo, reducerGameInfo, gameInfoStatus);
        buildReqReducer(builder, reqCustomService, reducerCustom, customStatus);
        buildReqReducer(builder, reqCustomLeaveMsg, reducerCustomLeaveMsg, customLeaveMsgStatus);
        buildReqReducer(builder, reqUpdateFavoInfo, reducerUpdateFavoInfo, null);
        buildReqReducer(builder, reqFavoGet, reducerFavoGet, null);
        buildReqReducer(builder, reqGameCardInfo, reducerGameCardInfo, gameCardInfoStatus);
        buildReqReducer(builder, reqSendCode, reducerSendCode, sendCodeStatus);
        buildReqReducer(builder, reqBindSMS, reducerBindSMS, bindSMSStatus);
        buildReqReducer(builder, reqSMSLogin, reducerSMSLogin, smsLoginStatus);
        buildReqReducer(builder, reqForgetPass, reducerChangePass, changePassStatus);
        buildReqReducer(builder, reqFreeWithdraw, reducerFreeWithdraw, null);
        buildReqReducer(builder, reqFreeWithdrawMission, reducerFreeWithdrawMission, null);
        buildReqReducer(builder, reqFreeWithdrawClaim, reducerFreeWithdrawClaim, updateFreeWithdrawClaimStatus);
        buildReqReducer(builder, reqHolidaysGiftInfo, reducerHolidaysGiftInfo, null);
        buildReqReducer(builder, reqHolidaysActInfo, reducerHolidaysActInfo, null);
        buildReqReducer(builder, reqGetPwaBonus, reducerGetPwaBonus, getPwaBonusStatus);
    },
});
export const { logout, updateUserInfo, updateUserScore, updateAddScore, updateGameLike, updateCurrGame, updateServerKick, updateOpenPay, updateGameRoute, updateGameCardInfo, updateAreaID, updateHolidaysGiftSpinTimes, changeOldAccount, updateHolidaysActSpinTimes } = Main.actions;
//数据获取
export const getFetchStatus = (state) => {
    return state.main.status;
};
export const routesMap = (state) => {
    return state.main.allMap;
};
export const routesIn = (state) => {
    return state.main.inRoutes;
};
export const routesPop = (state) => {
    return state.main.popRoutes;
};
export const nBlocks = (state) => {
    return state.main.blockNavs;
};
export const allNavs = (state) => {
    return state.main.allNavs;
};
export const allTopNavs = (state) => {
    return state.main.allTopNavs;
};
const getRouteFromPath = (state, path) => {
    let allMap = routesMap(state);
    let route = allMap[path];
    if (route == null) {
        //查看是否有可变路由
        let paths = path.split("/");
        paths[paths.length - 1] = "*";
        let newpath = paths.join("/");
        route = allMap[newpath];
    }
    return route;
};
export const getRoute = (path) => (state) => {
    // let route=routesMap(state)[path];
    let route = getRouteFromPath(state, path);
    if (route == null) return {};
    return route;
};
export const getRouteChain = (path) => (state) => {
    let map = routesMap(state);
    let list = [];
    let getChain = (cpath) => {
        let route = map[cpath];
        if (route != null) {
            list.unshift(route);
            if (route.ppath != null && route.ppath !== "") {
                getChain(route.ppath);
            }
        }
    };
    getChain(path);
    return list;
};
export const getRouteStyles = (state) => {
    let styles = state.main.styles;
    return styles;
};
export const getBlockColumn = (state) => {
    let blocks = state.main.blocks;
    return blocks;
};
export const isFullRoute = (path) => (state) => {
    // let route=routesMap(state)[path];
    let route = getRouteFromPath(state, path);
    if (route) return route.type === ROUTE_TYPE_FULL;
    return false;
};
export const isPopRoute = (path) => (state) => {
    // let route=routesMap(state)[path];
    let route = getRouteFromPath(state, path);
    if (route) return route.type === ROUTE_TYPE_POP;
    return false;
};
export const isInRoute = (path) => (state) => {
    // let route=routesMap(state)[path];
    let route = getRouteFromPath(state, path);
    if (route) return route.type === ROUTE_TYPE_IN;
    return false;
};
export const isOutRoute = (path) => (state) => {
    // let route=routesMap(state)[path];
    let route = getRouteFromPath(state, path);
    if (route) return route.type === ROUTE_TYPE_OUTLINK;
    return false;
};
//login
export const getLoginStatus = (state) => {
    return state.main.loginStatus.login;
};
export const getRegStatus = (state) => {
    return state.main.loginStatus.register;
};
export const getRegGoldStatus = (state) => {
    return state.main.loginStatus.regGold;
};
export const getLogoutStatus = (state) => {
    return state.main.loginStatus.logout;
};
export const getSendCodeStatus = (state) => {
    return state.main.loginStatus.send_code;
};
export const getBindSMSStatus = (state) => {
    return state.main.loginStatus.bind;
};
export const getSMSLoginStatus = (state) => {
    return state.main.loginStatus.smslogin;
};
export const getSendCodeTS = (state) => {
    return state.main.otpTimeStamp;
};
//modify
export const getChangeInfoStatus = (state) => {
    return state.main.modifyStatus.info;
};
export const getChangePassStatus = (state) => {
    return state.main.modifyStatus.password;
};
export const getChangePhoneStatus = (state) => {
    return state.main.modifyStatus.phone;
};
export const getChangeEmailStatus = (state) => {
    return state.main.modifyStatus.email;
};

export const isLogined = (state) => {
    // console.log(state.main.isLogin)
    return state.main.isLogin;
    // return 1;
};
export const getUserInfo = (state) => {
    return state.main.userInfo;
};
export const getOldUserInfo = (state) => {
    return state.main.oldUserInfo;
};
export const getUserVip = (state) => {
    return state.main.vip || 0;
};
export const getUserInsureScore = (state) => {
    if (state.main.freeWithdrawInfo) {
        return state.main.freeWithdrawInfo.InsureScore;
    }

    let userInfo = state.main.userInfo;
    if (userInfo != null) return userInfo.InsureScore;
    return 0;
};
export const getUserID = (state) => {
    let uid = -1;
    let userInfo = state.main.userInfo;
    if (userInfo) {
        if (userInfo.UserID != null) uid = Number(userInfo.UserID);
        else uid = 0;
    }
    return uid;
};
export const getCustomInfo = (state) => {
    return state.main.customerInfo;
};
export const getCustomTypeInfo = (type) => (state) => {
    let item = null;
    let customerInfo = state.main.customerInfo;
    if (customerInfo) {
        for (let i = 0; i < customerInfo.length; i++) {
            let info = customerInfo[i];
            if (info.StatusName === type) {
                item = info;
                break;
            }
        }
    }
    return item;
};
export const getCustomStatus = (state) => {
    return state.main.customLeaveMsgStatus;
};
export const getCustomServiceStatus = (state) => {
    return state.main.customServiceStatus;
};
export const getHallServerUrl = (state) => {
    return state.main.hallServerUrl;
};
export const getGameLikes = (state) => {
    return state.main.favorites;
};
export const getGameLike = (id) => (state) => {
    let favorites = state.main.favorites;
    if (favorites.includes(id)) return 1;
    return 0;
};
export const getKickState = (state) => {
    return state.main.serverKick;
};
export const getPromoteInstall = (state) => {
    return state.main.promoteInstall;
};
export const getPopWheel = (state) => {
    return state.main.popWheel;
};
export const getOpenPay = (state) => {
    return state.main.openPay;
};
export const getGameCardInfo = (id) => (state) => {
    id = Number(id);
    return state.main.gameCardInfo[id];
};
export const getIsGuest = (state) => {
    return state.main.guest;
};
export const getIsBindPhone = (state) => {
    let phone = "";
    if (state.main.userInfo != null) {
        phone = state.main.userInfo.Phone || "";
    }
    return phone.length > 0;
};
export const getUpgradeBonus = (state) => {
    return state.main.upgradeBonus;
};
export const getreRisterBonus = (state) => {
    return state.main.registerBonus;
};
export const getreRecommendGame = (state) => {
    return state.main.recommendGame;
};
export const getServiceLink = (state) => {
    return state.main.serviceLink;
};
export const getPopBindPhone = (state) => {
    return state.main.popBindPhone;
};
export const getFirstBonus = (state) => {
    return state.main.firstBonus;
};
export const getOpenRelief = (state) => {
    return state.main.openRelief;
};
export const getBBConf = (state) => {
    return state.main.bbConf;
};
export const getAccountLogin = (state) => {
    return state.main.accountLogin;
};
export const getArea = (state) => {
    return state.main.area;
};
export const getUserBBToken = (state) => {
    let token = null;
    let userInfo = state.main.userInfo;
    if (userInfo) {
        if (userInfo.bb != null && userInfo.bb.token != null) token = userInfo.bb.token;
    }
    return token;
};
export const getUserLang = (state) => {
    let lang = "";
    let userInfo = state.main.userInfo;
    if (userInfo) {
        lang = userInfo.lang;
    }
    return lang;
};
export const getUserNick = (state) => {
    let nick = "";
    let userInfo = state.main.userInfo;
    if (userInfo) {
        nick = userInfo.NickName;
    }
    return nick;
};
export const getUserRegisted = (state) => {
    let userInfo = state.main.userInfo;
    if (userInfo) {
        return userInfo.Registed == 1;
    }

    return false;
};
export const getLoginOpen = (state) => {
    return state.main.loginOpen;
};
export const getRegisterOpen = (state) => {
    return state.main.registerOpen;
};
export const getPopFirst = (state) => {
    return state.main.popFirst;
};
export const getShowInstall = (state) => {
    return state.main.showInstall;
};
export const getDownloadConf = (state) => {
    return state.main.download;
};
//数据获取
export default Main.reducer;

export const getBFP = () => {
    return async (dispatch, getState) => {
        //Finger2 添加指纹
        global.FF = await getFinger2DeviceId();
        let bfp = "";
        if (window.Capacitor?.isNativePlatform?.()) {
            bfp = window.AndroidAdjust?.getAdid();
        } else {
            bfp = localStorageGet(LOCAL_VISTOR_ID, "");
        }
        if (bfp != null && bfp !== "") {
            global.BFP = bfp;
            return bfp;
        }
        bfp = uuidv4();
        localStorageSet(LOCAL_VISTOR_ID, bfp);
        global.BFP = bfp;
        // const fpPromise = FingerprintJS.load({
        //     apiKey: "W7zWifGvJhjacPekHi64"
        // })
        //换成uuid
        // const fpPromise =FingerprintJS.load();
        // try {
        //     let fp=await fpPromise;
        //     let result=await fp.get();
        //     if (result!=null){
        //         bfp=result.visitorId;
        //         localStorageSet(LOCAL_VISTOR_ID,bfp);
        //         global.BFP=bfp;
        //     }
        // }
        // catch (err){
        //     console.log(err);
        // }
        return bfp;
    };
};
export const getFreeWithdraw = (state) => {
    return state.main.freeWithdrawInfo;
};
export const getFreeWithdrawMission = (state) => {
    return state.main.freeWithdrawMission;
};

export const getHolidaysGiftInfo = (state) => {
    return state.main.holidaysGiftInfo;
};
export const getHolidaysActInfo = (state) => {
    return state.main.holidaysActInfo;
};
export const getLandscapeGames = (state) => {
    return state.main.landscapeGames;
}
export const getPopPwaBonus = (state) => {
    return state.main.popPwaBonus;
}
export const getPwaCliamStatus = (state) => {
    return state.main.pwaBonusStatus;
}

