import { createAction, createSlice } from "@reduxjs/toolkit";
import { REQ_STATUS } from "@api/config";
import { buildReqReducer, reqFavoGet, reqPageModules } from "@features/api";
import { localStorageGet, localStorageRemove, localStorageSet } from "@utils/helpers";
import { LOCAL_FAVO_DATA, LOCAL_FAVO_IDS } from "@constants/localkey";
const addFavoriteKey = (state, key) => {
    let favoriteKeys = state.favoriteKeys;
    if (!favoriteKeys.includes(key)) {
        favoriteKeys.push(key);
    }
    state.favoriteKeys = favoriteKeys;
};
const parseModules = (data, key = "", state) => {
    if (data != null) {
        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            if (item != null) {
                let tkey = key + "_" + i;
                item["_mkey"] = tkey;
                if (item.data_key === "favorite") {
                    addFavoriteKey(state, tkey);
                }
                let tdata = item.data;
                if (tdata != null) {
                    tkey = tkey + "_data";
                    item.data = parseModules(tdata, tkey, state);
                }
            }
        }
    }
    return data;
};
//mkey module key
const getModuleData = (data, mkey) => {
    let module = null;
    if (data != null) {
        let keys = mkey.split("_");
        let tdata = data;
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            let temp = tdata[key];
            if (temp == null) break;
            tdata = temp;
        }
        module = tdata;
    }
    return module;
};
//初始化favorite
const getLocalFavorite = () => {
    let localFIDS = localStorageGet(LOCAL_FAVO_IDS, "");
    let favoData = [];
    if (localFIDS != null && localFIDS !== "") {
        let list = JSON.parse(localFIDS);
        if (list != null) {
            for (let i = 0; i < list.length; i++) {
                let key = LOCAL_FAVO_DATA + "_" + list[i];
                let temp = localStorageGet(key, "");
                if (temp !== "") {
                    favoData.push(JSON.parse(temp));
                }
            }
        }
    }
    return favoData;
};
const parseFavorite = (state) => {
    let favoriteKeys = state.favoriteKeys;
    if (favoriteKeys != null && favoriteKeys.length > 0) {
        // let localFavorite=null;
        for (let i = 0; i < favoriteKeys.length; i++) {
            let module = getModuleData(state.pageData, favoriteKeys[i]);
            if (module != null) {
                let data = module.data;
                if (data == null || data.length === 0) {
                    // if (localFavorite==null)localFavorite=getLocalFavorite();
                    data = state.favoriteData;
                }
                module.data = data;
            }
        }
    }
};
//page modules
const reducerPage = (state, action) => {
    let json = action.payload;
    if (json && json.code === 0) {
        let data = json.data == null ? [] : json.data;
        let pageID = json.pageID;
        data = parseModules(data, pageID, state);
        state.pageData[pageID] = data;
        parseFavorite(state);
    }
};
const pageStatus = (state, status, arg) => {
    state.status = status;
};
//page modules
const reducerFavoGet = (state, action, arg) => {
    let payload = action.payload;
    if (payload && payload.code === 200) {
        state.favoriteData = payload.data;
        parseFavorite(state);
    }
};
export const Page = createSlice({
    name: 'page',
    initialState: {
        status: REQ_STATUS.NONE,
        pageData: {},
        favoriteKeys: [],
        favoriteData: []
    },
    reducers: {
        updateGameList: ((state, action) => {
            let payload = action.payload;
            let mkey = payload.mkey;
            let module = getModuleData(state.pageData, mkey);
            if (module != null) {
                let oldData = module.data;
                let data = payload.data;
                let newData = [];
                if (oldData != null && data != null) newData = oldData.concat(data);
                let newObj = { page: payload.page, totalPage: payload.totalPage, data: newData };
                Object.assign(module, newObj);
            }
        }),
        updatePageGameLike: ((state, action) => {
            let { data, like } = action.payload;
            let favoriteKeys = state.favoriteKeys;
            if (favoriteKeys && favoriteKeys.length > 0) {
                for (let i = 0; i < favoriteKeys.length; i++) {
                    let mkey = favoriteKeys[i];
                    let module = getModuleData(state.pageData, mkey);
                    if (module != null) {
                        let oldData = module.data;
                        if (oldData == null) oldData = [];
                        if (oldData.length === 0) {
                            if (like === 1) oldData.unshift(data);
                        }
                        else {
                            let index = -1;
                            for (let j = 0; j < oldData.length; j++) {
                                let item = oldData[j];
                                if (item != null && item.id === data.id) {
                                    index = j;
                                    break;
                                }
                            }
                            if (like === 1) {
                                if (index === -1) oldData.unshift(data);
                            }
                            else {
                                if (index >= 0) oldData.splice(index, 1);
                            }
                        }
                        module.data = oldData;
                        state.favoriteData = oldData;
                    }
                }
            }
            // if (like===1)localStorageSet(LOCAL_FAVO_DATA+"_"+data.id,JSON.stringify(data));
            // else localStorageRemove(LOCAL_FAVO_DATA+"_"+data.id)
        }),
        onSliceChangeUser: (state, action) => {
            state.favoriteData = [];
            let favoriteKeys = state.favoriteKeys;
            if (favoriteKeys && favoriteKeys.length > 0) {
                for (let i = 0; i < favoriteKeys.length; i++) {
                    let mkey = favoriteKeys[i];
                    let module = getModuleData(state.pageData, mkey);
                    if (module != null) {
                        module.data = [];
                    }
                }
            }
        }
    },
    extraReducers: (builder) => {
        buildReqReducer(builder, reqPageModules, reducerPage, pageStatus);
        buildReqReducer(builder, reqFavoGet, reducerFavoGet, null);
    },
});
export const { updateGameList, updatePageGameLike } = Page.actions;
export const getFetchStatus = (state) => {
    return state.page.status;
};
export const getModules = (pageID) => (state) => {
    let pageData = state.page.pageData;
    if (pageData == null) return [];
    return pageData[pageID];
};
export const getPopularGames = (state) => {
    let pageData = getModules(1)(state);
    if (!pageData || pageData.length == 0) return [];
    let index = pageData.findIndex((modules) => {
        return modules.type === "ModuleGameTabs";
    });

    if (index === -1 || !pageData[index]) return [];
    const data = pageData[index].data || [];
    index = data.findIndex((element) => {
        return element.id === 5 || element.title === 'links.hot_games';
    });

    if (index === -1 || !data[index]) return [];
    const list = data[index].data || [];
    const indexs = list.map((_, index) => index);
    const populars = [];
    for (let i = 0; i < 3 && indexs.length > 0; ++i) {
        const r = Math.floor(Math.random() * indexs.length);
        index = indexs[r];
        populars.push(list[index]);
        indexs.splice(r, 1);
    }
    return populars;
};


export default Page.reducer;

