const SkillApi = require('../net/SkillApi');
const DWTool = require("../utils/DWTool");
const GameModule = require("../utils/GameModule");
// const buildingLevel = require('../data/buildingLevel');
const GameNotificationKey = require('../utils/GameEnum').GameNotificationKey;

cc.Class({
    extends: cc.Component,

    properties: {

        userSkillButton: {
            tooltip: '使用技能button',
            default: null,
            type: cc.Button
        },
        
        titleRichText: {
            tooltip: 'title啦',
            default: null,
            type: cc.RichText
        },

        useSkillButtonBgSprite: cc.Sprite,

        subTitleRichText: cc.RichText,

        skillUseTitleRichText: cc.RichText,

        skillIconBg: {
            tooltip: '技能icon的背景',
            default: null,
            type: cc.Sprite
        },

        skillIcon: cc.Sprite,

        fillBuldingNode: cc.Node,
        fillBuldingSprite: cc.Sprite,
        /// 里程碑奖励显示的node
        awardButton: cc.Button,

        investSubNode: cc.Node,

        diamondCount: 0,
        coinCount: 0,

        building: 0,
        _awardCount: 0,

    },

    onLoad () {
    },

    start () {

    },

    onDestroy() {
        GameEvent.off("skill3_use_begain", this);
        GameEvent.off(GameNotificationKey.SkillThreeHasDone, this);
        GameEvent.off("skill_five_use", this);
        GameEvent.off(GameNotificationKey.UpBuildingLevel, this);
    },

    initBuilding(awardCount) {
        this.initAward(awardCount)
        this.updateBuildingData();
        /// 第三个技能开始使用
        GameEvent.on("skill3_use_begain", this, () => {
            this.updateBuildingData();
        });

        /// 第三个技能结束
        GameEvent.on(GameNotificationKey.SkillThreeHasDone, this, () => {
            this.updateBuildingData();
        });
        ////第五个技能开始使用
        GameEvent.on("skill_five_use", this, () => {
            this.updateBuildingData();
        });
        
        // let buildingLevelInfo = buildingLevel[buildingInfo.buildingLevel - 1];
    },

    initAward(awardCount) {
        this._awardCount = awardCount;
        let needAwardCount = parseInt(Global.userData.buildingLevel / 25);
        if (needAwardCount > this._awardCount) {
            this.awardButton.node.active = true;
        } else {
            this.awardButton.node.active = false;
        }
    },

    init(skillData) {
        this.fillBuldingNode.active = false;
        this.awardButton.node.active = false;
        this.loadSpriteFrame(skillData);
        this.skillData = skillData;
        this.updateData();
    },

    updateBuildingData() {
        let buildingInfo = Global.userData;
        let upGold = buildingInfo.buildingLevel * 30;
        let upGet = 25 + buildingInfo.buildingLevel * 5;
        this._upGold = upGold;
        this._upGet = upGet;
        
        this.skillUseTitleRichText.string = '<color=#ffffff>+' + DWTool.coinParse(upGet) + '收益</c>' + `<br/><img src='coin_small'/><color=#ffffff>${DWTool.coinParse(upGold)}</c>`;
        this.fillBuldingNode.active = true;
        this.fillBuldingSprite.fillRange = (buildingInfo.buildingLevel % 25) / 25;
        this.diamondCount = 0;
        this.coinCount = upGold;
        this.building = 0;

        this.titleRichText.string = '<color=#df5400>等级' + buildingInfo.buildingLevel + '</c>' + '<color=#1c1c1c>' + ' 总部大楼' + '</c>';
        this.subTitleRichText.string = `<img src='skill_click_coin'/><color=#df5400> ${DWTool.coinParse(GameModule.userInfo.coinTap)}收益</c><color=#1c1c1c>/点击</c>`;
    },

    updateData() {
        let levelInfo = Global.BuildingManager.getSkillLevelInfo(this.skillData.skillId, this.skillData.skillLevel); 
        let skillInfo = Global.BuildingManager.getSkillInfo(this.skillData.skillId);
         //// 如果是没有拥有的
        if (this.skillData.isHave == 0) {
            /// 说明是用其它的来解锁
            if (skillInfo.buildingLevel == 0) {
                /// 用的砖石 技能4是用砖石或者金币来解锁的
                this.showBuySkill();
            } else {
                /// 说明总部等级不够，还没有解锁
                if (Global.userData.buildingLevel < skillInfo.buildingLevel) {
                    this.coinCount = 0;
                    this.diamondCount = 0;
                    this.building = skillInfo.buildingLevel;
                    this.skillUseTitleRichText.string = "<img src='skill_lock'/><br/><color=#ffffff>等级" + skillInfo.buildingLevel + '</c>';        
                     //// 如果是因为建筑锁住的
                    GameEvent.on(GameNotificationKey.UpBuildingLevel, this, () => {
                        if (Global.userData.buildingLevel >= this.building && this.skillData.isHave == 0) {
                            /// 实时技能直接拥有
                            if (this.skillData.skillId < 4) {
                                 /// 直接解锁它
                                this.unlockedSkill();
                             } else {
                                this.showBuySkill();
                                this.setupGrayBg(this.judgeIsCanUse());
                             }
                            GameEvent.off(GameNotificationKey.UpBuildingLevel, this);
                        }
                    });
                    /// 那就需要去购买了
                } else {
                    this.showBuySkill();
                }  
            }
        } else {
            this.userSkillButton.interactable = true;
            /// 使用金币升级
            let coinCount = levelInfo.bonus[10001];
            let diamondCount = levelInfo.bonus[10002];
            /// 用的砖石
            if (coinCount == undefined && diamondCount != undefined) {
                this.diamondCount = diamondCount;
                this.coinCount = 0;
                this.building = 0;
                this.skillUseTitleRichText.string = `<color=#ffffff>升级</c><br/><img src='skill_diamond'/><color=#ffffff>${diamondCount}钻石</c>`;
            } else if (levelInfo.bonus == 1002) {
                this.coinCount = coinCount;
                this.diamondCount = 0;
                this.building = 0;
                this.skillUseTitleRichText.string = `<color=#ffffff>升级</c><br/><img src='coin_small'/><color=#ffffff>${coinCount}金币</c>`;
            } 
        }

        this.setupGrayBg(this.judgeIsCanUse());
        if (this.skillData.skillLevel > 0) {
            this.titleRichText.string = '<color=#df5400>等级' +  + this.skillData.skillLevel + ' </c>' + '<color=#1c1c1c>' + skillInfo.name + '</c>';
        } else {
            this.titleRichText.string = '<color=#df5400>技能' + ' </c>' + '<color=#1c1c1c>' + skillInfo.name + '</c>';
        }
        if (levelInfo == undefined) {
            this.subTitleRichText.string = '<color=#1c1c1c>' + skillInfo.desc + '</c>';
        } else {
            this.subTitleRichText.string = '<color=#1c1c1c>' + levelInfo.desc + '</c>';

        }
    },

    setupGrayBg(isActive) {
        this.userSkillButton.interactable = isActive;
        let path = !isActive ? './textures/skill/skill_bg_gray' : './textures/skill/skill_bg_green';
        DWTool.loadResSpriteFrame(path)
         .then((spriteFrame) => {
            this.useSkillButtonBgSprite.spriteFrame = spriteFrame;
        });
    },

    loadSpriteFrame(skillData) {
        if (skillData.skillId > 3) {
            return;
        }
        let bgPath = './textures/skill/400' + skillData.skillId + skillData.skillId;
        let iconPath = './textures/skill/4000' + skillData.skillId;
        DWTool.loadResSpriteFrame(bgPath)
        .then((spriteFrame) => {
            this.skillIconBg.spriteFrame = spriteFrame;
        });
        DWTool.loadResSpriteFrame(iconPath)
        .then((spriteFrame) => {
            this.skillIcon.spriteFrame = spriteFrame;
        });
    },
/////////////网络请求

    /// 升级技能
    upSkill(skillId) {
        return new Promise((resolve, reject) => {
            // 获取目标用户的建筑
            SkillApi.upSkill(skillId, (respondData) => {
                resolve(respondData);
            }, (err) => {
                reject(err);
            });
        });
    },
    //// 购买技能
    buySkill(skillId) {
        return new Promise((resolve, reject) => {
            // 获取目标用户的建筑
            SkillApi.buySkill(skillId, (respondData) => {
                resolve(respondData);
            }, (code, msg) => {
                reject(code, msg);
            });
        });
    },

    /// 升级建筑
    upBuildingLevel() {
        return new Promise((resolve, reject) => {
            // 获取目标用户的建筑
            SkillApi.upBuildingLevel((respondData) => {
                resolve(respondData);
            }, (code, msg) => {
                reject(code, msg);
            });
        });
    },

    /// 上报里程碑奖励
    report() {
        return new Promise((resolve, reject) => {
            // 获取目标用户的建筑
            SkillApi.report(3, (respondData) => {
                resolve(respondData);
            }, (code, msg) => {
                reject(code, msg);
            });
        });
    },

    showBuySkill() {
        let levelInfo = Global.BuildingManager.getSkillLevelInfo(this.skillData.skillId, 1);
        /// 使用金币升级
        let coinCount = levelInfo.bonus[10001];
        let diamondCount = levelInfo.bonus[10002];
        /// 用的砖石
        if (coinCount == undefined && diamondCount != undefined) {
            this.diamondCount = diamondCount;
            this.coinCount = 0;
            this.building = 0;
            this.skillUseTitleRichText.string = `<color=#ffffff>购买</c><br/><img src='skill_diamond'/><color=#ffffff>${diamondCount}钻石</c>`;
        } else if (levelInfo.bonus == 1002) {
            this.coinCount = coinCount;
            this.diamondCount = 0;
            this.building = 0;
            this.skillUseTitleRichText.string = `<color=#ffffff>购买</c><br/><img src='coin_small'/><color=#ffffff>${coinCount}金币</c>`;
        } 
    },

    useSkillButtonAction() {
        this.userSkillButton.interactable = false;
        /// 如果是升级建筑
        if (this.fillBuldingNode.active) {
            this.upBuildingLevel().then((respondData) => {
                this.userSkillButton.interactable = true;
                Global.userData.buildingLevel = respondData.level;
                this.initAward(this._awardCount);
                GameEvent.fire(GameNotificationKey.UpBuildingLevel);
                this.updateBuildingData();
              }).catch(({code, msg}) => {
                  console.log(code, msg);
                  this.userSkillButton.interactable = true;
            });
        } else {
            this.skillAction();
        }
    },

    /// 解锁某一个技能
    unlockedSkill() {
        let skillId = this.skillData.skillId;
        this.skillData.isHave = 1;
        this.skillData.skillLevel = 1;
        this.updateData()
        if (skillId <= 3) {
            GameEvent.fire("TopSkill_unLocked", skillId);
        } 
        console.log("解锁技能成功");
    },

    buyFixSkill() {
        this.skillData.skillLevel = 1;
        this.skillData.isHave = 1;
        let skillId = this.skillData.skillId;
        this.updateGloabData();
        this.updateData();
        /// 如果升级永久技能
        let skillLevelInfo = Global.BuildingManager.getSkillLevelInfo(skillId, this.skillData.skillLevel);
        GameEvent.fire(GameNotificationKey.UpdateFixationSkill, skillLevelInfo);
        if (skillId == 5) {
            GameEvent.fire("skill_five_use");
        } else if (skillId == 6) {
            GameEvent.fire("skill_six_use");
        }
    },

    skillAction() {
         /// 那就是解锁啦
         let skillId = this.skillData.skillId;
         /// 说明是购买技能
         if (this.skillData.isHave == 0 && skillId > 3) {
             /// 购买成功
            this.buySkill(skillId).then(() => {
                this.buyFixSkill();
                this.userSkillButton.interactable = true;
                console.log("技能购买成功");
              }).catch((code, msg) => {
                  console.log(code, msg);
                  this.userSkillButton.interactable = true;
            });
         /// 升级技能
        } else {
            this.upSkill(skillId).then(() => {
                this.userSkillButton.interactable = true;
                this.skillData.skillLevel += 1;
                this.updateGloabData();
                this.updateData();
                if (skillId <= 3) {
                    GameEvent.fire("TopSkill_up", skillId);
                } else {
                    /// 如果升级永久技能
                    let skillLevelInfo = Global.BuildingManager.getSkillLevelInfo(skillId, this.skillData.skillLevel);
                    GameEvent.fire(GameNotificationKey.UpdateFixationSkill, skillLevelInfo);
                    if (skillId == 5) {
                        GameEvent.fire("skill_five_use");
                        /// 使用最后一个减cd的
                    } else if (skillId == 6) {
                        GameEvent.fire("skill_six_use");
                    }
                }
                console.log("升级技能成功");
              }).catch((code, msg) => {
                  console.log(code, msg);
                  this.userSkillButton.interactable = true;
            });
        }
    },

    //// 里程碑奖励action
    awardBtnAction() {
        this.awardButton.interactable = false;
        this.report().then((respondData) => {
            this.awardButton.interactable = true;
            this._awardCount += 1;
            let needAwardCount = parseInt(Global.userData.buildingLevel / 25);
            this.awardButton.node.active = needAwardCount > this._awardCount;
            GameModule.userInfo.perpetualClickMt = parseFloat(respondData.clickMt);
            GameEvent.fire(GameNotificationKey.UpBuildingLevel);
            this.updateBuildingData();
            console.log("领取里程碑奖励成功");
          }).catch((code, msg) => {
              console.log(code, msg);
              this.awardButton.interactable = true;
        });
    },

    /// 判断本地是否是解锁状态
    judgeIsCanUse() {
        if (this.coinCount > 0 && GameModule.userInfo.gold >= this.coinCount) {
            return true;
        } else if (this.diamondCount > 0 && GameModule.userInfo.diamond >= this.diamondCount) {
            return true;
        } else if (this.building > 0 && Global.userData.buildingLevel >= this.building) {
            return true;
        } else {
            return false;
        }
    },

    updateGloabData() {
        if (this.coinCount > 0) {
            GameModule.userInfo.gold -= this.coinCount;
        } else if (this.diamondCount > 0) {
            GameModule.userInfo.diamond -= this.diamondCount;
        } 
    },

    update (dt) {

        /// 如果说是建筑 并且没有钱升级的状态
        if (this.fillBuldingNode.active && this.userSkillButton.interactable == false) {
            ///如果能够使用了，那么继续能用
            if (this.judgeIsCanUse()) {
                this.userSkillButton.interactable = true;
                let path = './textures/skill/skill_bg_green';
                DWTool.loadResSpriteFrame(path)
                .then((spriteFrame) => {
                    this.useSkillButtonBgSprite.spriteFrame = spriteFrame;
                });
            }
        }
    },
});
