import {createSlice} from "@reduxjs/toolkit";
import {REQ_STATUS} from "@api/config";
import {buildReqReducer, reqProtectCheck, reqProtectGet} from "@features/api";
import {getHttpMsg} from "@utils/helpers";
import {toast} from "react-toastify";
const reducerProtectCheck=(state,action,arg)=>{
    let payload=action.payload;
    if (payload&&payload.code===200){
        let data=payload.data;
        if (data!=null){
            let info=data[0];
            if (info!=null)state.protectInfo=info;
        }
    }
}
const protectCheckStatus=(state,status,arg)=>{
    state.status.ProtectCheck=status;
}

const reducerProtectGet=(state,action,arg)=>{
    let payload=action.payload;
    let msg=getHttpMsg(payload);
    if (payload&&payload.code===200){
        let CurProtectTimes=state.protectInfo.CurProtectTimes!=null?Number(state.protectInfo.CurProtectTimes):0;
        CurProtectTimes=CurProtectTimes+1;
        state.protectInfo.CurProtectTimes=CurProtectTimes;
        if (msg!=null&&msg!="")toast.success(msg,{toastId:"protectGet"});
    }
    else
    {
        if (msg!=null&&msg!="")toast.error(msg,{toastId:"protectGet"});
    }
    if (arg.callback!=null)arg.callback(payload);
}
const protectGetStatus=(state,status,arg)=>{
    state.status.ProtectGet=status;
}

export const ProtectSlice = createSlice({
    name: "protect",
    initialState: {
        protectInfo: {},
        status:{
            ProtectCheck:REQ_STATUS.NONE,
            ProtectGet:REQ_STATUS.NONE,
        }
    },
    reducers: {
        onSliceChangeUser:((state, action) => {
            state.protectInfo= {};
        }),
    },
    extraReducers: (builder) => {
        buildReqReducer(builder,reqProtectCheck,reducerProtectCheck,protectCheckStatus);
        buildReqReducer(builder,reqProtectGet,reducerProtectGet,protectGetStatus);
    }
})
export const {} = ProtectSlice.actions;
export const getProtectInfo=(state)=>{
    return state.protect.protectInfo;
}
export const getProtectGetStatus=(state)=>{
    return state.protect.status.ProtectGet;
}
export default ProtectSlice.reducer;