
var ReportType = require("../utils/GameEnum").ReportType;
var Base64 = require("../lib/Base64").Base64;
var HomeApi = require("../net/HomeApi");
var GameModule = require('./GameModule');

class DWTool {

    static coinParse(coin) {

        if (coin < 10000) {
            return coin.toString();
        } else if (coin >= 10000 && coin < 1000000) {
            let parseCoin = Math.floor((coin / 1000)).toFixed(0);
            return parseCoin.toString() + "K";
        } else if (coin >= 1000000 && coin < 1000000000) {
            let parseCoin = Math.floor((coin / 1000000)).toFixed(0);
            return parseCoin.toString() + "M";
        } else {
            let parseCoin = Math.floor((coin / 1000000000)).toFixed(0);
            return parseCoin.toString() + "B";
        }
    };

    static setGenderIcon(gender) {
        return this.getGenderIconPath(gender).then((filePath) => {
            return this.loadResSpriteFrame(filePath);
        });
    };

    /**
     * 上报方法, 抽成公用方法
     * @param {*} seq 
     * @param {*} totalMoney 总金币
     * @param {*} stars 星星数
     * @param {*} recordModify 是否有修改的建筑
     * @param {*} recordUnlockModify 是否有解锁的建筑
     */
    static reportInfo(seq = 1, totalMoney = 0, stars = 0, recordModify = [], recordUnlockModify = []) {
        return new Promise((resolve, reject) => {

            let reportFormInfo = {};
            reportFormInfo[ReportType.Seq] = seq;
            reportFormInfo[ReportType.GrossIncome] = totalMoney;
            reportFormInfo[ReportType.Stars] = stars;
            reportFormInfo[ReportType.Timestamp] = Date.parse(new Date());

            if (recordUnlockModify.length > 0 || recordModify.length > 0) {
                reportFormInfo[ReportType.Event] = 1;
                if (recordUnlockModify.length > 0) {
                    reportFormInfo[ReportType.UnLockBuild] = this.parseReportArray(recordUnlockModify);
                }
                if (recordModify.length > 0) {
                    reportFormInfo[ReportType.Build] = this.parseReportArray(recordModify);
                }
            } else {
                reportFormInfo[ReportType.Event] = 0;
            }

            // 还是将上报信息log出来吧, 方便调试
            console.log("reportFormInfo: " + JSON.stringify(reportFormInfo));

            let ecData = Base64.encode(JSON.stringify(reportFormInfo));
            HomeApi.userReportGross(ecData, (rep) => {
                console.log("上报成功!");
                resolve();
            }, (code, msg) => {
                reject({ "code": code, "msg": msg });
            });
        });
    };

    static submitWechatStars(score) { //提交得分
        // if (window.wx != undefined) {
        //     // 对用户托管数据进行写数据操作
        //     window.wx.setUserCloudStorage({
        //         KVDataList: [{ key: 'stars', value: "" + stars }],
        //         success: function (res) {
        //             console.log('setUserCloudStorage', 'success', res)
        //         },
        //         fail: function (res) {
        //             console.log('setUserCloudStorage', 'fail')
        //         },
        //         complete: function (res) {
        //         }
        //     });
        // } else {
        //     cc.log("提交星星数:" + stars)
        // }
        let key2 = Global.wechatScoreKey;

        if (window.wx != undefined) {
            // window.wx.getUserCloudStorage({
            //     // 以key/value形式存储
            //     keyList: [key2],
            //     success: function (getres) {
            // if (getres.KVDataList.length != 0) {
            //     let wxgame = JSON.parse(getres.KVDataList[0].value).wxgame;
            //     if (wxgame) {
            //         let preScore = wxgame.score;
            //         if (preScore > score) {
            //             return;
            //         }
            //     }
            // }
            // 对用户托管数据进行写数据操作

            let myValue = {
                wxgame: {
                    score: score,
                    update_time: Date.parse(new Date()) / 1000
                },
                gender: Global.user.gender,
                jobName: GameModule.userInfo.levelName,
                jobLevel: GameModule.userInfo.level
            }
            var myValueString = JSON.stringify(myValue);
            window.wx.setUserCloudStorage({
                KVDataList: [{ key: key2, value: myValueString }],
                success: function (res) {
                    console.log('setUserCloudStorage', 'success', res)
                },
                fail: function (res) {
                    console.log('setUserCloudStorage', 'fail')
                },
                complete: function (res) {
                }
            });
            //     },
            //     fail: function (res) {
            //         console.log('getUserCloudStorage', 'fail')
            //     },
            //     complete: function (res) {

            //     }
            // });
        } else {
            cc.log("提交得分:" + key2 + " : " + score)
        }
    }

    static parseReportArray(array) {
        let tempArray = [];
        // 删除没用的字段
        for (let i = 0; i < array.length; i++) {
            let model = array[i];
            let tempObj = {};
            tempObj[ReportType.ID] = model.buildingId;
            tempObj[ReportType.Level] = model.level
            tempObj[ReportType.NotPickupCoinCount] = model.coinCount;
            tempArray.push(tempObj);
        }
        return tempArray;
    };


    static getGenderIconPath(gender) {
        return new Promise((resolve, reject) => {
            // if (gender === 0 || gender === 1) {
            let filePath = (gender === 1) ? './textures/icon_male' : './textures/icon_female';
            resolve(filePath);
            // } else {
            //     reject();
            // }
        })
    };

    // clickOnce(cb) {
    //     if (this._clickDic === 0) { return; }
    //     this._clickDic = 0;

    //     setTimeout(() => {
    //         this._clickDic = 1;
    //     }, 1000);

    //     cb && cb();
    // };

    static loadResPrefab(path) {

        let p = new Promise((resolve, reject) => {
            cc.loader.loadRes(path, cc.Prefab, (error, prefab) => {
                if (error) {
                    console.log(error);
                    reject(error);
                } else {
                    resolve(prefab)
                }
            });
        });
        return p;
    };

    static loadResSpriteAtlasToSpriteFrame(path, subAsset) {

        let p = new Promise((resolve, reject) => {

            cc.loader.loadRes(path, cc.SpriteAtlas, (error, atlas) => {
                if (error) {
                    console.log(error);
                    reject(error);
                } else {
                    var spriteFrame = atlas.getSpriteFrame(subAsset);
                    resolve(spriteFrame)
                }
            });
        });
        return p;
    };

    static loadResSpriteAtlas(path) {
        let p = new Promise((resolve, reject) => {
            cc.loader.loadRes(path, cc.SpriteAtlas, (error, atlas) => {
                if (error) {
                    console.log(error);
                    reject(error);
                } else {
                    resolve(atlas);
                }
            });
        });
        return p;
    };

    static loadResSpriteFrame(path) {
        let p = new Promise((resolve, reject) => {
            cc.loader.loadRes(path, cc.SpriteFrame, (error, sf) => {
                if (error) {
                    console.log(error);
                    reject(error);
                } else {
                    resolve(sf);
                }
            });
        });
        return p;
    }

    static loadResPrefabArray(pathArr) {
        let p = new Promise((resolve, reject) => {
            cc.loader.loadResArray(pathArr, cc.Prefab, (error, resourceArr) => {
                if (error) {
                    console.log(error);
                    reject(error);
                } else {
                    resolve(resourceArr);
                }
            });
        });
        return p;
    }

    static loadResSpine(path) {
        let p = new Promise((resolve, reject) => {
            cc.loader.loadRes(path, cc.skeletonData, (error, prefab) => {
                if (error) {
                    console.log(error);
                    reject(error);
                } else {
                    resolve(prefab);
                }
            });
        });
        return p;
    }


    //时间戳格式化为对应文字时间显示
    static timeParse(timestamp) {
        function zeroize(num) {
            return (String(num).length == 1 ? '0' : '') + num;
        }

        var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
        var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数

        var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
        var tmDate = new Date(timestamp * 1000);  // 参数时间戳转换成的日期对象

        var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
        var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds();

        if (timestampDiff < 60) { // 一分钟以内
            return "刚刚";
        } else if (timestampDiff < 3600) { // 一小时前之内
            return Math.floor(timestampDiff / 60) + "分钟前";
        } else if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
            return '今天' + H + ':' + zeroize(i);
        } else {
            var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
            if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
                return '昨天' + H + ':' + zeroize(i);
            } else if (curDate.getFullYear() == Y) {
                return m + '月' + d + '日 ' + H + ':' + zeroize(i);
            } else {
                return Y + '年' + m + '月' + d + '日 ' + H + ':' + zeroize(i);
            }
        }
    };

    /**
     * 将时间戳转成00:00显示
     * @param {floor} t 
     */
    static calculateTime(t) {

        // 好像经常会出现时间格式化出错的问题, 这里先这样解决一下
        if (t < 0) { 
            t = 0; 
            console.log("出现负数的时间");
        }

        let hour = Math.floor(t / 60 / 60);
        let minute = Math.floor(t / 60 % 60);
        let second = Math.floor(t % 60);

        if (hour != 0 && hour < 10) {
            hour = "0" + hour;
        }

        if (minute < 10) {
            minute = "0" + minute;
        }

        if (second < 10) {
            second = "0" + second;
        }

        if (hour != 0) {
            return `${hour}:${minute}:${second}`;
        } else {
            return `${minute}:${second}`;
        }
    };

    /**
     * 获取Url上指定参数
     * @param {String} name 参数名
     */
    static getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        } else {
            return null;
        }
    }
}

module.exports = DWTool;