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

const SkillState = cc.Enum({
    /// 使用中
    usingState: 1,
    /// 技能cd状态
    cdState: 2,
    /// 技能可以使用的状态
    canUseState: 3,
    /// 技能锁住的状态
    lockedState: 4
});

cc.Class({
    extends: cc.Component,

    properties: {
        titleRichText: {
            tooltip: '技能时间time ,锁住状态的text',
            default: null,
            type: cc.RichText
        },

        skillBg: {
            tooltip: '技能的黑色遮罩',
            default: null,
            type: cc.Sprite
        },

        skillBgOutSide: {
            tooltip: '技能的黑色外遮罩，这里只有是三个哦，最后一个刷新技能的是没有的',
            default: null,
            type: cc.Sprite
        },

        skillBgBottom: {
            tooltip: '技能的底部黑色遮罩',
            default: null,
            type: cc.Sprite
        },

        button: cc.Button,

    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        ///技能解锁啦
        GameEvent.on("TopSkill_unLocked", this, (skillId) => {
            if (this.skillInfo != undefined && skillId === this.skillInfo.skillId) {
                this.setUpSkillState(SkillState.canUseState);
                /// 技能等级 + 1
                this.skillInfo.skillLevel += 1;
                /// 设置为可以使用
                this.skillInfo.skillStatus = 0;
                this.updataData();
            } else if (this.skillInfo == undefined && this._isAlllLocked) {
                this._isAlllLocked = false;
                this.setUpSkillState(SkillState.canUseState);
            }
        });
},

    start () {

    },

    onDestroy() {
        GameEvent.off("TopSkill_unLocked", this);
        GameEvent.off(GameNotificationKey.ResetSkill, this);
        GameEvent.off("TopSkill_up", this);
        GameEvent.off(GameNotificationKey.UpBuildingLevel, this);
        GameEvent.off("skill_six_use", this);
    },

    init(skillInfo) {
        this.skillInfo = skillInfo;
        this.setupTopSkillNotification();
        if (skillInfo.isHave == 0) {
            this.setUpSkillState(SkillState.lockedState);
            let skillData = Global.BuildingManager.getSkillInfo(skillInfo.skillId);
            this.titleRichText.string = "<img src='skill_lock'/><br/><color=#ffffff>等级" + skillData.buildingLevel + '</c>';    
            return;
        }
        this.updataData();
    },

    setupTopSkillNotification() {

        GameEvent.on(GameNotificationKey.ResetSkill, this, () => {
            if (this.skillState !== SkillState.lockedState) {
                this.setUpSkillState(SkillState.canUseState);
            }
        });

        /// 第六个技能使用  需要更新cd时间
        GameEvent.on("skill_six_use", this, () => {
            Global.rcdSkillLevel += 1;
            let lastLevelInfo = Global.BuildingManager.getSkillLevelInfo(6, Global.rcdSkillLevel);
            this.cd = levelInfo.cd * (1 - lastLevelInfo.rcd / 100);
        });

        GameEvent.on("TopSkill_up", this, (skillId) => {
            if (this.skillInfo != undefined && skillId === this.skillInfo.skillId) {
                /// 技能等级 + 1
                this.skillInfo.skillLevel += 1;
                ///如果是重置技能的 而且是锁住了
            } 
        });
    },

    updataData() {
        let levelInfo = Global.BuildingManager.getSkillLevelInfo(this.skillInfo.skillId, this.skillInfo.skillLevel);
        this._levelInfo = levelInfo;
        if (Global.rcdSkillLevel == 0) {
            this.cd = levelInfo.cd;
        } else {
            let lastLevelInfo = Global.BuildingManager.getSkillLevelInfo(6, Global.rcdSkillLevel);
            this.cd = levelInfo.cd * (1 - lastLevelInfo.rcd / 100);
        }
        /// 技能cd
        /// 持续时间
        let td = levelInfo.td;
        let hasCd = this.skillInfo.cdStarTime / 1000;
        this.td = td;
        /// 技能使用cd中
        if (this.skillInfo.skillStatus == 2) {
            this.setUpSkillState(SkillState.cdState);
            this.timeLabelCount = hasCd;
            this.titleRichText.string = DWTool.calculateTime(hasCd);
            this.skillBg.fillRange = - hasCd / this.cd;
            /// 技能使用中
        } else if (this.skillInfo.skillStatus == 1) {
            this.setUpSkillState(SkillState.usingState);
            this.timeLabelCount = hasCd;
            this.titleRichText.string = DWTool.calculateTime(hasCd);
            this.skillBgOutSide.fillRange = - hasCd / td;
        } else {
            this.setUpSkillState(SkillState.canUseState);
        }
    },

    /// 初始化刷新技能的item
    initUpdateSkill(isAllLocked) {
        ///是否所有的技能锁住
        this._isAlllLocked = isAllLocked;
        // 20分钟
        this.cd = 10;
        if (isAllLocked) {
            this.setUpSkillState(SkillState.lockedState);
            return;
        }
        let resetSkillTime = Global.userData.resetSkillTime;
        let timestamp = new Date().getTime();

        let totalCd = (timestamp - resetSkillTime) / 1000;
        if (this.cd <= totalCd) {
            this.setUpSkillState(SkillState.canUseState);
        } else {
            this.setUpSkillState(SkillState.cdState);
            this.skillBg.fillRange = totalCd / this.cd - 1;
            this.timeLabelCount = this.cd - totalCd;
            this.titleRichText.string = DWTool.calculateTime(this.timeLabelCount);
        }
    },

    updateTime() {
        if (this.skillState === SkillState.canUseState || this.skillState === SkillState.lockedState) {
            return;
        }
        /// 使用中的状态
        if (this.skillState === SkillState.usingState) {
            this.timeLabelCount -= 1;
            this.skillBgOutSide.fillRange += 1 / this.td;
            if(this.skillBgOutSide.fillRange >= 0 || this.timeLabelCount <= 0) {
                this.setUpSkillState(SkillState.cdState);
                this.timeLabelCount = this.cd - this.td;
                this.skillBg.fillRange = this.td / this.cd - 1;
                this.titleRichText.string = DWTool.calculateTime(this.timeLabelCount);
            } else {
                this.titleRichText.string = DWTool.calculateTime(this.timeLabelCount);
            }
            /// 技能cd 的状态
        } else {
            this.skillBg.fillRange += 1 / this.cd;
            this.timeLabelCount -= 1;
            if (this.skillBg.fillRange >= 0 || this.timeLabelCount <= 0) {
                this.setUpSkillState(SkillState.canUseState);
            }else {
                this.titleRichText.string = DWTool.calculateTime(this.timeLabelCount);
            }
        }
    },

    setUpSkillState(skillState) {
        this.skillState = skillState;        
        this.skillBg.node.active = skillState !== SkillState.canUseState;
        if (this.skillBgOutSide != null) {
            this.skillBgOutSide.node.active = skillState === SkillState.usingState;
        }
        this.skillBgBottom.node.active = skillState !== SkillState.canUseState;
        this.titleRichText.node.active = skillState !== SkillState.canUseState;
        this.button.interactable = skillState === SkillState.canUseState;

    },

    sendNotification() {
        let skillLevelInfo = Global.BuildingManager.getSkillLevelInfo(this.skillInfo.skillId, this.skillInfo.skillLevel);
        GameEvent.fire(GameNotificationKey.UseTimeSkill, skillLevelInfo);
    },

    skillAction1() {
      this.button.interactable = false;
      this.useSkill(this.skillInfo.skillId).then(() => {
        this.button.interactable = true;
        this.setUpSkillState(SkillState.usingState);
        this.timeLabelCount = this.td;
        this.titleRichText.string = DWTool.calculateTime(this.td);
        this.skillBgOutSide.fillRange = -1;  
        this.sendNotification();
      }).catch((code, msg) => {
          console.log(code, msg);
          this.button.interactable = true;
      });
    },

    skillAction2() {
        this.button.interactable = false;
        this.useSkill(this.skillInfo.skillId).then(() => {
            this.button.interactable = true;
            this.setUpSkillState(SkillState.cdState);
            this.timeLabelCount = this.cd;
            this.titleRichText.string = DWTool.calculateTime(this.cd);
            this.skillBg.fillRange = -1;
            this.sendNotification();
          }).catch((code, msg) => {
              console.log(code, msg);
              this.button.interactable = true;
          });
    },

    skillAction3() {
        this.button.interactable = false;
        this.useSkill(this.skillInfo.skillId).then(() => {
            this.button.interactable = true;
            this.setUpSkillState(SkillState.usingState);
            this.timeLabelCount = this.td;
            this.titleRichText.string = DWTool.calculateTime(this.td);
            this.skillBgOutSide.fillRange = -1; 
            this.sendNotification();
            GameEvent.fire("skill3_use_begain");
          }).catch((code) => {
              console.log(code);
              this.button.interactable = true;
          });
    },

    skillAgainAction() {
        this.button.interactable = false;
        this.resetSkill().then((respondData) => {
            this.button.interactable = true;
            Global.userData.resetSkillTime = respondData.curSystemTime;
            this.setUpSkillState(SkillState.cdState);
            this.timeLabelCount = this.cd;
            this.titleRichText.string = DWTool.calculateTime(this.cd);
            this.skillBg.fillRange = -1;
            GameEvent.fire(GameNotificationKey.ResetSkill);
          }).catch((code) => {
              console.log(code);
              this.button.interactable = true;
          });
    },

    /// 网络请求
    useSkill(skillId) {
        return new Promise((resolve, reject) => {
            // 获取目标用户的建筑
            SkillApi.useSkill(skillId, (respondData) => {
                resolve(respondData);
            }, (code, msg) => {
                reject(code, msg);
            });
        });
    },

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