cc.Class({
    extends: cc.Component,

    properties: {
        spinBtn: {
            default: null,      // The default value will be used only when the component attachin                    // to a node for the first time
            type: cc.Button,     // optional, default is typeof default
            visible: true,      // optional, default is true
            displayName: 'SpinBtn', // optional
        },
        wheelSp: {
            default: null,
            type: cc.Sprite,
            tooltip: "转盘图片"
        },
        background: {
            default: null,
            type: cc.Sprite,
            tooltip: "背景图片"
        },
        pointer: {
            default: null,
            type: cc.Sprite,
            tooltip: "指针图片"
        },
        title: {
            default: null,
            type: cc.Sprite,
            tooltip: "欢天喜地幸运大转盘"
        },
        startbtn: {
            default: null,
            type: cc.Sprite,
            tooltip: "开始按钮"
        },
        maxSpeed: {
            default: 5,
            type: cc.Float,
            max: 20,
            min: 2,
        },
        duration: {
            default: 0.1,
            type: cc.Float,
            max: 2,
            min: 0.1,
            tooltip: "减速前旋转时间"
        },
        acc: {
            default: 2,
            type: cc.Float,
            max: 20,
            min: 0.01,
            tooltip: "加速度"
        },
        targetID: {
            default: 0,
            type: cc.Integer,
            max: 7,
            min: 0,
            tooltip: "指定结束时的齿轮"
        },
        springback: {
            default: false,
            tooltip: "旋转结束是否回弹"
        },
        ShowRewards:cc.Node,
        Rewards:cc.Node,
        RewardDetail: {
            default: [],
            type: [cc.String],
        },
        Businesslicense: {
            default: null,
            type: cc.SpriteFrame,
        },
        LandDevelopmentCertificate: {
            default: null,
            type: cc.SpriteFrame,
        },
        Golden10: {
            default: null,
            type: cc.SpriteFrame,
        },
        Golden50: {
            default: null,
            type: cc.SpriteFrame,
        },
        Golden100: {
            default: null,
            type: cc.SpriteFrame,
        },
        ManageUI:cc.Node,
        ManageMap:cc.Node,

    },
    // use this for initialization
    onLoad: function () {
        //消耗钻石数量
        this.Diamond = 100;
        this.spin = this.getNode("spin");
        this.Sprite = this.getNode("New Sprite",this.spin);
        this.wheelState = 0;
        this.curSpeed = 0;
        this.spinTime = 0;                   //减速前旋转时间
        this.gearNum = 8;
        this.defaultAngle = 360 / this.gearNum / 2;        //修正默认角度
        this.gearAngle = 360 / this.gearNum;   //每个齿轮的角度
        this.wheelSp.node.angle = -this.defaultAngle;
        // console.log("修正默认角度",this.defaultAngle);
        this.finalAngle = 0;                 //最终结果指定的角度
        this.effectFlag = 0;                 //用于音效播放

        this.restMaxSpeed = this.maxSpeed;
        this.duration = 1;

        if (!cc.sys.isBrowser) {
            cc.loader.loadRes('Sound/game_turntable', function (err, res) {
                if (err) {
                    // cc.log('...err:' + err);
                }
            });
        }
        this.spinBtn.node.on(cc.Node.EventType.TOUCH_END, function (event) {
            // cc.log("begin spin");

            if (this.wheelState !== 0) {
                return;
            }

            // if (GlobalD.GameData.GetDiamond()>=this.Diamond) {
            //     GlobalD.GameData.PlusDiamond(-this.Diamond);
            //
            //     this.startLuck();
            //
            //
            // }else{
            //     // cc.log("没"+this.Diamond+"钻石转不了");
            //
            //     this._showDialog(function () {
            //         this.watchvideo.on(cc.Node.EventType.TOUCH_END, function (event) {
            //             this.startLuck();
            //             this._closeDialog();
            //         }.bind(this));
            //         this.close.on(cc.Node.EventType.TOUCH_END, function (event) {
            //             this._closeDialog();
            //         }.bind(this));
            //     }.bind(this));
            // }

            //每日签到
            let myDate = new Date();
            //'2019/05/01'
            let Today = myDate.toLocaleDateString();
            let LastTimeLuckDate = GlobalD.GameData.GetLastTimeLuckDate();
            // LastTimeLuckDate = "2019/3/20";
            let s = "2019/3/20"
            console.log("today",Today);
            console.log("LastTimeLuckDate",LastTimeLuckDate);


            if(Today == LastTimeLuckDate && LastTimeLuckDate!='0000/00/00')
            {

            }
            else
            {
                // console.log("走着么");
                //过了一天
                GlobalD.GameData.SetLotteryTimes(10);
                // GlobalD.GameData.SetLastTimeLuckDate(Today);
                GlobalD.GameData.SetLastTimeLuckDate(Today);

            }



            if (GlobalD.GameData.GetLotteryTimes()>0) {
                // cc.log("没"+this.Diamond+"钻石转不了");
                this._showDialog(function () {
                    this.watchvideo.on(cc.Node.EventType.TOUCH_END, function (event) {
                        this.startLuck();
                        this._closeDialog();
                    }.bind(this));
                    this.close.on(cc.Node.EventType.TOUCH_END, function (event) {
                        this._closeDialog();
                    }.bind(this));
                }.bind(this));
                // cc.log('11111111=='+GlobalD.GameData.GetLotteryTimes())
                GlobalD.GameData.PlusLotteryTimes(-1);
            }
            else
            {
                cc.loader.loadRes('resUI/ShowNotEnoughMoney', function (err, texture) {
                    var prefab = cc.instantiate(texture);
                    prefab.getComponent('ShowNotEnoughMoney').Text('明天再来试试手气吧！');
                    this.node.addChild(prefab);
                }.bind(this));
            }
        }.bind(this));
 
        this.initNetwork();
    },

    initNetwork : function(){
        UtilsPrefabs.loadResSpriteFrame('taskres/diamond_1',function (texture) {
        }.bind(this));
        UtilsPrefabs.loadResSpriteFrame('taskres/diamond_2',function (texture) {
        }.bind(this));
    },



    startLuck : function(){
        this.getRandom();
        this.decAngle = 1 * 360;  // 减速旋转两圈
        this.wheelState = 1;
        this.curSpeed = 0;
        this.spinTime = 0;
        this.maxSpeed = this.restMaxSpeed;
    },
  
    caculateFinalAngle: function (targetID) {
        this.finalAngle = 360 - this.targetID * this.gearAngle + this.defaultAngle;
        if (this.springback) {
            this.finalAngle += this.gearAngle;
        }
    },
    editBoxDidBegin: function (edit) {
    },
    editBoxDidChanged: function (text) {
    },
    editBoxDidEndEditing: function (edit) {
        var res = parseInt(edit.string);
        if (isNaN(res)) {
            if (cc.sys.isBrowser) {
                // alert('please input a number!');
            } else
            {
                // cc.log(".....invalid input");
            }
            this.targetID = Math.round(Math.random() * (this.gearNum - 1));
            // cc.log("停止的位置是", this.targetID);
            return;
        }
        this.targetID = res;
    },
    getRandom: function () {
        let TerritoryStateArray = GlobalD.GameData.GetTerritoryStateArray();
        var BuildingStateArray = GlobalD.GameData.BuildingStateArray;

        var tempcout = 0;
        var tempcout7 = 0;

        var probability = 0.1;
        var probability7 = 0.1;
        var probability100 = 0.1;
        var probability10 = 0.15;
        for(let i=0;i<TerritoryStateArray.length;i++)
        {
            // console.log("结构遍历",TerritoryStateArray[i]);
            if(TerritoryStateArray[i]==1)
            {
                tempcout++;
            }
        }
        for(let i=0;i<BuildingStateArray.length;i++)
        {
            // console.log("结构遍历",BuildingStateArray[i]);
            if(BuildingStateArray[i]==1)
            {
                tempcout7++;
            }
        }
        if (tempcout==TerritoryStateArray.length) {
            //没有能开的了
            probability = 0;
            probability100 = 0.1;
            probability10 = 0.2;
        }
        if (tempcout7==BuildingStateArray.length) {
            //没有能开的了
            probability7 = 0;
            probability100 = 0.1;
            probability10 = 0.2;
        }
        // console.log("设置概率",tempcout,probability);


        // 随机数范围 ：40~900
        let random = new GLRandom(0, this.gearNum);
        // 0 金币 x10
        // 1 随机建筑 x1
        // 2 金币 x50
        // 3 土地开发证件 x1
        // 4 金币 x10
        // 5 金币 x100
        // 6 金币 x10
        // 7 经营许可证 x1
        // 调整概率
        random.percentage = new Map([
            [0, 0.2],   // 调整值为41的数值，概率为20%
            [1, 0.05],   // 调整值为41的数值，概率为20%
            [2, 0.1],   // 调整值为41的数值，概率为20%
            [3, 0.1],   // 调整值为41的数值，概率为20%
            [4, 0.2],   // 调整值为41的数值，概率为20%
            [5, 0.1],   // 调整值为41的数值，概率为20%
            [6, 0.2],   // 调整值为41的数值，概率为20%
            [7, 0.05],   // 调整值为46的数值，概率为50%
        ]);

        // 生成值区间
        random.range();
        this.targetID = random.create();
        // 生成概率随机数
        // console.log("停止的位置是区间随机数", this.targetID);


        // this.targetID = Math.round(Math.random() * (this.gearNum - 1));
        // cc.log("停止的位置是", this.targetID);
    },
    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
        if (this.wheelState === 0) {
            return;
        }
        // cc.log('......update');
        // cc.log('......state=%d',this.wheelState);

        // 播放音效有可能卡
        // this.effectFlag += this.curSpeed;
        // if (!cc.sys.isBrowser && this.effectFlag >= this.gearAngle) {
        //     if (this.audioID) {
        //         // cc.audioEngine.pauseEffect(this.audioID);
        //     }
        //     // this.audioID = cc.audioEngine.playEffect(this.effectAudio,false);
        //     this.audioID = cc.audioEngine.playEffect(cc.url.raw('resources/Sound/game_turntable.mp3'));
        //     this.effectFlag = 0;
        // }

        if (this.wheelState == 1) {
            // cc.log('....加速,speed:' + this.curSpeed);
            this.spinTime += dt;
            this.wheelSp.node.angle = Math.abs(this.wheelSp.node.angle) + this.curSpeed;


            if (this.curSpeed <= this.maxSpeed) {
                this.curSpeed += this.acc;
            } else {
                if (this.spinTime < this.duration) {
                    return;
                }
                // cc.log('....开始减速');
                //设置目标角度
                this.finalAngle = 360 - this.targetID * this.gearAngle - this.defaultAngle;
                this.maxSpeed = this.curSpeed;
                if (this.springback) {
                    this.finalAngle += this.gearAngle;
                }
                this.wheelSp.node.angle = this.finalAngle;
                this.wheelState = 2;
            }
        } else if (this.wheelState == 2) {
            // cc.log('......减速');
            var curRo = Math.abs(this.wheelSp.node.angle); //应该等于finalAngle
            var hadRo = curRo - this.finalAngle;
            this.curSpeed = this.maxSpeed * ((this.decAngle - hadRo) / this.decAngle) + 0.1;
            this.wheelSp.node.angle = curRo + this.curSpeed;

            if ((this.decAngle - hadRo) <= 0) {
                // cc.log('....停止');
                this.wheelState = 0;
                this.wheelSp.node.angle = this.finalAngle;
                if (this.springback) {
                    //倒转一个齿轮
                    // var act = new cc.rotateBy(0.6, -this.gearAngle);
                    var act = cc.rotateBy(0.6, -this.gearAngle);
                    var seq = cc.sequence(cc.delayTime(0.2), act, cc.callFunc(this.showRes, this));
                    this.wheelSp.node.runAction(seq);
                } else {
                    this.showRes();
                }
            }
        }
    },
    showRes: function () {
        // console.log("随机转盘是",this.targetID);
        // this.targetID = 1;


        // this.targetID=7;
        this.Rewards.removeAllChildren();
        // 0 金币 x10
        // 1 随机建筑 x1
        // 2 金币 x50
        // 3 土地开发证件 x1
        // 4 金币 x10
        // 5 金币 x100
        // 6 金币 x10
        // 7 经营许可证 x1
    switch (this.targetID) {
        case 0:
        case 4:
        case 6:
            GlobalD.GameData.PlusGolden(10000);
            this.Rewards.getComponent(cc.Sprite).spriteFrame = this.Golden10;
            this.Rewards.scale=2;
            break;
        case 1:
            this.myScale = 0.2;
            // [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0];
            this.myScales = [
                0.2,
                0.2,
                0.2,
                //3
                1,
                1,
                1,
                1,
                //7
                1,
                1,
                1,
                1,
                //11
                1,
                1,
                1,
                1,
                //15
                1,
                1,
                1,
                1.5,
                //19
                1.5,
                1,
                1,
                1,
            ];


            let BuildingLockStateArray = GlobalD.GameData.BuildingLockStateArray;
            // console.log("我当前有什么",BuildingLockStateArray);
            let HadBuildingArray = [];
            // console.log("我当前有什么 领取之前",GlobalD.GameData.BuildingNumArray);
            for(let i=3;i<BuildingLockStateArray.length;i++)
            {
                // cc.log('BuildingStateArray[i]='+BuildingStateArray[i]);
                if(parseInt(BuildingLockStateArray[i])==1)
                {
                    HadBuildingArray.push(i);
                }
            }
            // console.log("我当前有什么 库存是 抽签",HadBuildingArray);
            let RandomIndex =  this.GetRandomRange(0,HadBuildingArray.length-1);
            let BuildingNumArray = GlobalD.GameData.BuildingNumArray;
            // cc.log('BuildingNumArray[RandomIndex]===='+BuildingNumArray[RandomIndex]);

            let num = parseInt(BuildingNumArray[HadBuildingArray[RandomIndex]])+1;
            BuildingNumArray[HadBuildingArray[RandomIndex]] = num;
            // console.log("我当前有什么 库存是",BuildingNumArray,"索引是",RandomIndex);
            // console.log("我当前有什么 领取之后",BuildingNumArray);
            GlobalD.GameData.SetBuildingNumArray(BuildingNumArray);

            let SelectedBuildingIndex = HadBuildingArray[RandomIndex];
            // SelectedBuildingIndex = 19;
            let SelectedBuilding = this.ManageUI.getComponent('ManageBuildings').BuildingArray[SelectedBuildingIndex];
            SelectedBuilding.getChildByName('Name').getChildByName('Num').getComponent(cc.Label).string = num;
            // console.log("都有啥",this.ManageUI.getComponent('ManageBuildings').BuildingArray,"抽到啥",SelectedBuildingIndex);

            this.Rewards.getComponent(cc.Sprite).spriteFrame = "";
            if (SelectedBuildingIndex == 6) {

                var node = new cc.Node();
                var sprite = node.addComponent(cc.Sprite);
                sprite.spriteFrame = SelectedBuilding.getChildByName('New Sprite(Splash)').getComponent(cc.Sprite).spriteFrame;
                this.Rewards.addChild(node);
                var cnode = new cc.Node();
                var csprite = cnode.addComponent(cc.Sprite);
                cnode.y = 20;
                csprite.spriteFrame = SelectedBuilding.getChildByName('New Sprite(Splash)').getChildByName('Labour_01_2').getComponent(cc.Sprite).spriteFrame;
                node.addChild(cnode);


            }else{
                this.Rewards.getComponent(cc.Sprite).spriteFrame = SelectedBuilding.getChildByName('New Sprite(Splash)').getComponent(cc.Sprite).spriteFrame;
            }


            // console.log("现在是什么",SelectedBuildingIndex);
            // SelectedBuildingIndex
            this.Rewards.scale=this.myScales[SelectedBuildingIndex];

         
            break;
        case 2:
            GlobalD.GameData.PlusGolden(15000);
            this.Rewards.getComponent(cc.Sprite).spriteFrame = this.Golden50;
            this.Rewards.scale=2;
            break;
        case 3:
        case 7:
            let TerritoryStateArray = GlobalD.GameData.GetTerritoryStateArray();
            // for(let i=0;i<TerritoryStateArray.length;i++)
            // {
            //     // console.log("结构遍历",TerritoryStateArray[i]);
            //     if(TerritoryStateArray[i]==0)
            //     {
            //         TerritoryStateArray[i]=1;
            //
            //         GlobalD.GameData.SetTerritoryStateArray(TerritoryStateArray);
            //
            //         let _ManageMap = this.ManageMap.getComponent('ManageMap');
            //         let Territory = _ManageMap.Territories[i];
            //         //开土地后清空土地的占位信息
            //         _ManageMap.onClearSolidArea(i);
            //
            //
            //         // let Territory = this.ManageMap.getComponent('ManageMap').Territories[i];
            //         Territory.enabled = false;
            //         this.Rewards.getComponent(cc.Sprite).spriteFrame = this.LandDevelopmentCertificate;
            //         // console.log("结构",this.Rewards);
            //         this.Rewards.scale=2;
            //         break;
            //     }
            // }

            if (this.targetID == 3) {
                GlobalD.GameData.PlusDiamond(250);

                UtilsPrefabs.loadResSpriteFrame('taskres/diamond_1',function (texture) {
                    // var prefab = cc.instantiate(texture);
                    this.Rewards.getComponent(cc.Sprite).spriteFrame = texture;
                    this.Rewards.scale=2;
                }.bind(this));
            }else if (this.targetID == 7) {
                GlobalD.GameData.PlusDiamond(350);

                UtilsPrefabs.loadResSpriteFrame('taskres/diamond_2',function (texture) {
                    // var prefab = cc.instantiate(texture);
                    this.Rewards.getComponent(cc.Sprite).spriteFrame = texture;
                    this.Rewards.scale=2;
                }.bind(this));
            }


            break;
        case 5:
            GlobalD.GameData.PlusGolden(30000);
            this.Rewards.getComponent(cc.Sprite).spriteFrame = this.Golden100;
            this.Rewards.scale=2;
            break;
        // case 7:
        //
        //     var BuildingStateArray = GlobalD.GameData.BuildingStateArray;
        //
        //     for(let i=3;i<BuildingStateArray.length;i++)
        //     {
        //         cc.log('BuildingStateArray[i]='+BuildingStateArray[i]);
        //         if(BuildingStateArray[i]==0)
        //         {
        //             BuildingStateArray[i]=1;
        //             GlobalD.GameData.SetBuildingStateArray(BuildingStateArray);
        //
        //             let Building = this.ManageUI.getComponent('ManageBuildings').BuildingArray[i];
        //             Building.active = true;
        //             this.Rewards.getComponent(cc.Sprite).spriteFrame = Building.getChildByName('New Sprite(Splash)').getComponent(cc.Sprite).spriteFrame;
        //             this.Rewards.scale=1;
        //
        //             break;
        //         }
        //     }
        //
        //     break;

        default:
            break;
    }

        // console.log("结果是",this.RewardDetail[this.targetID]);
        this.showDialog();
    },

 
    isTask : function(){
        if (task.TaskIconCountClick == 5) {
            task.addTaskIconCountClick();

            task.removeTaskNodes();
        }
    },

  

    _showShareDialog: function (callback) {
        cc.loader.loadRes("prefab/share", function (err, texture) {
            this.shares = cc.instantiate(texture);
            this._closeShareDialog();
            this.node.parent.addChild(this.shares);

            this.gosharebtn = this.getNode("gosharebtn",this.shares);
            // this.close = this.getNode("close",this.dialogLuckView);
            this.gosharebtn.off(cc.Node.EventType.TOUCH_END);

            var img1 = UtilsPrefabs.getNode("img1",this.shares);
            var NewLabel1 = UtilsPrefabs.getNode("New Label",img1);
            var img2 = UtilsPrefabs.getNode("img2",this.shares);
            var NewLabel2 = UtilsPrefabs.getNode("New Label",img2);
            NewLabel1.getComponent(cc.Label).string = 'x'+GlobalD.GameData.shareGive[0];
            NewLabel2.getComponent(cc.Label).string = 'x'+GlobalD.GameData.shareGive[1];

            if (callback != null) {
                callback();
            }
        }.bind(this));
    },
    showDialog: function () {

        this.node.active = false;
        var Sunshine = this.ShowRewards.getChildByName('GivePrize').getChildByName('Sunshine');
        var GivePrize = this.ShowRewards.getChildByName('GivePrize');
        Sunshine.scaleX = 0;
        Sunshine.scaleY = 0;
        GivePrize.scaleX = 0;
        GivePrize.scaleY = 0;
        Sunshine.stopAllActions();
        GivePrize.stopAllActions();
            this.scheduleOnce(function () {
            this.ShowRewards.opacity = 255;
                this.ShowRewards.active = true;
                var sc2 = cc.scaleTo(0.5,1.2,1.2);
                Sunshine.runAction(sc2);
                var sc3 = cc.scaleTo(0.5,1,1);
                GivePrize.runAction(sc3);


                var repeat = cc.repeatForever(cc.rotateBy(5.0, 360));
                Sunshine.runAction(repeat);
        }, 0.1);

    },
    GetRandomRange(n, m){
        var random = Math.floor(Math.random()*(m-n+1)+n);
        return random;
    },

    _showDialog: function (callback) {
        cc.loader.loadRes("prefab/dialogLuckView", function (err, texture) {
            this.dialogLuckView = cc.instantiate(texture);
            if (this.node.getChildByName(this.dialogLuckView.name) != null) {
                this.node.getChildByName(this.dialogLuckView.name).destroy();
            }
            this.node.addChild(this.dialogLuckView);
            // this.dialogLuckView.active = false;
            this.dialogLuckView.y=-100;
            this.watchvideo = this.getNode("watchvideo",this.dialogLuckView);
            this.close = this.getNode("close",this.dialogLuckView);



            if (callback != null) {
                callback();
            }
        }.bind(this));
    },
    _closeDialog: function () {
            if (this.node.getChildByName(this.dialogLuckView.name) != null) {
                this.node.getChildByName(this.dialogLuckView.name).destroy();
            }
    },
    _closeShareDialog: function () {
            if (this.node.parent.getChildByName(this.shares.name) != null) {
                this.node.parent.getChildByName(this.shares.name).destroy();
            }
    },
    getNode: function (name, parent) {
        if (parent == null) {
            return this.node.getChildByName(name);
        } else {
            return parent.getChildByName(name);
        }

    },


});

class GLRandom {
    /**
     * 构造函数
     * @param {number} min  最小整数值
     * @param {number} max  最大整数值
     * @param {Map} percentage 概率数 [值,百分比]
     */
    constructor(min, max, percentage = new Map()) {
        this.min = Math.trunc(min);
        this.max = Math.trunc(max);
        this.MATH_RANGE = 100;  // 分成100份
        this.percentage = percentage;
    }

    get percentage() {
        if (!this._percentage) {
            this._percentage = new Map();
        }
        return this._percentage;
    }

    /**
     * 分配比例
     * @param {Map} map 设置 值-百分比
     */
    set percentage(map) {
        let result = Array.from(map.values()).reduce((p, v, a) => {
            return p - v;
        }, 1);
        for (let i = this.min; i < this.max; i++) {
            if (map.has(i)) {
                this.percentage.set(i, map.get(i));
            } else {
                this.percentage.set(i, result / (this.max - this.min - map.size));
            }
        }
    }

    /**
     * 根据比例生成取值范围
     */
    range() {
        let [start, random, keys] = [0, this.MATH_RANGE, Array.from(this.percentage.keys())];
        for (let i = 0; i < keys.length; i++) {
            let temp = this.percentage.get(keys[i]);
            this.percentage.set(keys[i], [start, start += temp * random]);
        }
    }

    /**
     * 生成随机数
     */
    create() {
        let num = Math.random() * this.MATH_RANGE;
        for (let data of this.percentage.entries()) {
            if (num >= data[1][0] && num < data[1][1]) {
                return data[0];
            }
        }
        return null;
    }
}