import { gameMethod } from "../../common/gameMethod";
import { SevBack } from "../../common/Xys";
import { NetworkEvent } from "../../data/const/EventConst";
import GameController from "../../GameController";
import EventMng from "../../manager/EventMng";

export default class IDataModel {
    protected modelName: string = 'default';

    /**
     * 本地缓存的数据
     */
    private _dLocalData = {};

    constructor(modelName = 'default') {
        this.modelName = modelName;
        this.LoadStorage();
        EventMng.on(NetworkEvent.NET_MSG_REGISTER, this.onRegister.bind(this), this);
    }

    protected onRegister() {

    }

    clear() {

    }

    protected LoadStorage() {
        let localStorage = cc.sys.localStorage.getItem(`model_${this.modelName}`)
        if (gameMethod.isEmpty(localStorage)) {
            this._dLocalData = {}
            this.Save();
        } else {
            let data = JSON.parse(localStorage);
            this._dLocalData = data;
        }
    }

    /**
     * protected 只让实现类操作数据  也就是model类型操作数据 对外提供别的方法
     * @param sKey 
     * @param defaultValue 
     */
    protected Query(sKey: string, defaultValue: any = null) {
        if (this._dLocalData[sKey] != undefined) {
            return this._dLocalData[sKey];
        }
        return defaultValue;
    }

    /**
     * 设置成功返回 true，反之返回 false 用于是否保存数据
     * @param sKey 
     * @param value
     */
    protected Set(sKey: string, value: string | number) {
        if (this._dLocalData[sKey] && this._dLocalData[sKey] == value) {
            return false;//一样就不要改了
        }
        this._dLocalData[sKey] = value;
        return true;
    }

    protected Save() {
        cc.sys.localStorage.setItem(`model_${this.modelName}`, JSON.stringify(this._dLocalData));
    }

    public getModelName() {
        return this.modelName
    }

    /**
    * 发送登录协议
    * @param msg 
    */
    sendLogin(url: string, param: Object = {}, cb1: Function = (sev: SevBack) => { }) {
        GameController.network.sendLogin(url, param, cb1)
    }

    /**
     * 发送业务协议
     * @param param     参数
     * @param cb1       处理回传的sevback之后调用
     * @param cb2       处理回传的sevback之前调用
     * @param deal(1)   处理回传的sevback  1:处理通用回调   2:处理通用回调(不处理弹窗) 3:不处理通用回调
     *                  待业务处理后,执行network.dealLeftSevback即可处理未处理的事件
     */
    send(url: string, param: Object = {}, cb1?: (sev: SevBack) => void, cb2?: (sev: SevBack) => void, deal: number = 1, needWait: boolean = false) {
        GameController.network.send(url, param, cb1, cb2, deal, needWait)
    }
    /**
    * 数据处理
    * @param result 后端发回的数据(在serverData处理完后触发)
    */
    doSevback(result: SevBack) { }
    /**
     * 事件处理
     * @param result 后端发回的数据
     */
    doEvent(result: SevBack) { }
}