/**
 * 客户端本地缓存组件
 */
window.root = require('root');
cc.Class({
    extends: cc.Component,
    editor: {
        executionOrder: -20,
    },
    properties: {
        cache: {
            default: {},
        },
        queue: {
            default: [],
        },
        local_name: '拳击机模板',
    },
    onLoad() {
        console.log('local');
        cc.game.addPersistRootNode(this.node);
        window.local = this;
        this[this.local_name] = {
            audio: '1',
        };
        this.init_local();
        this.init_data();
    },
    init_data() {
        console.log('init_data');
        try {
            window.courseware.getData(function (res) {
                this.data = res;
                cc.find('Canvas').getComponent('index').init_load();
                console.log(res);
            }.bind(this));
        } catch (error) {
            console.error('没有查找到courseware.getData方法', error);
            this.data = {
                text0: 'A a',
                text1: 'apple',
                text2: 'bind',
            };
            cc.find('Canvas').getComponent('index').init_load();
        }
    },
    /**
     * 获取预设数据
     */
    getTempData(key) {
        console.log('getTempData');
        return (this.data[key]);
    },
    save() {
        cc.sys.localStorage.setItem(this.local_name, JSON.stringify(this.cache));
    },
    init_local() {
        if (!cc.sys.localStorage.getItem(this.local_name)) {
            cc.sys.localStorage.setItem(this.local_name, JSON.stringify(this[this.local_name]));
        }
        this.cache = JSON.parse(cc.sys.localStorage.getItem(this.local_name));
    },
    getData(key, int = false) {
        var value = this.cache[key];
        if (int) {
            return (parseInt(value));
        } else {
            return (value);
        }
    },
    setData(key, value) {
        this.cache[key] = value;
        switch (key) {
            case 'audio':
                this.save();
                break;
            default:
                break;
        }
    },
    dataAdd(key, ins = 1) {
        var value = this.getData(key);
        value = parseInt(value);
        this.setData(key, value + ins);
    },
});