import Stage from "./stage/Stage";
import Pack from "./pack/Pack";
import ViewObject from "../../main/ViewObject";
import { HttpStateType, ReveData } from "../../util/CHttp";
import { AudioMgr, GameViewType } from "../../main/ViewManage";
import ShopView from "./shop/ShopView";
import Equip from "./equip/Equip";
import FFCalAttr from "../data/FFCalAttr";
import { PetAttr } from "../data/udata/Player";
import RedPoint from "../data/RedPoint";
import FirstPay from "./activity/FirstPay";
import TopMenu from "./TopMenu";
import Wish from "./activity/Wish";
import Revenge from "./activity/Revenge";
import CUtilTime from "../../util/CUtilTime";

/**
 * 主页home
 */
const { ccclass, property } = cc._decorator;

@ccclass
export default class Home extends ViewObject {

    @property(cc.Label)
    mZdl: cc.Label = null;

    @property(cc.Label)
    mPower: cc.Label = null;

    @property(cc.Label)
    mMoney: cc.Label = null;

    @property(cc.Label)
    mGold: cc.Label = null;

    @property(cc.Sprite)
    mIcon: cc.Sprite = null;

    @property(cc.Sprite)
    mFrame: cc.Sprite = null;

    @property(cc.Node)
    activityNode: cc.Node = null;

    @property(cc.Node)
    mEmailNode: cc.Node = null;

    @property(sp.Skeleton)
    mRole1: sp.Skeleton = null;
    @property(sp.Skeleton)
    mRole2: sp.Skeleton = null;
    @property(sp.Skeleton)
    mRole3: sp.Skeleton = null;


    @property(cc.Node)
    mEquipNode: cc.Node = null;

    @property(cc.Node)
    revengeBtn: cc.Node = null;

    public revengeTime: number = 0;
    public topMenu: TopMenu = null;
    public revengeView: Revenge = null;

    /**
     * 用户点击了冒险按钮回调
     */
    private mxCallback: () => void;

    onLoad() {
        //心跳60秒执行一次
        this.hit()
        this.schedule(this.hit, 15)
        this.flushActivity();
        this.topMenu = this.main.topNode.getComponent(TopMenu);
        this.topMenu.main = this.main;
        this.topMenu.home = this;
        this.main.topNode.active = true;
        this.main.playMusicByPath(AudioMgr.homeMusic);
        this.node.getChildByName("activity").getChildByName("1002").active = !this.main.player.isNew;

        this.getPay()
    }
    public hit() {
        this.main.gameHttp.sendJson('role/v1/resumePower', {}, (state, reve: ReveData) => { });
    }
    public onEnable() {
        this.flush()
        this.flushZdl()
        this.flushRole()
        this.flushEquipRedPoint();

        if (cc.sys.localStorage.getItem("showRevenge" + this.main.player.role.id) == 1) {
            this.activiteRevenge();
        } else {
            this.getRevengeData();
        }
    }


    private getPay() {
        let msg = {
        }
        this.main.gameHttp.sendJson('pay/v1/checkPay1', msg, (state, reve: ReveData) => {
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    this.main.showReward(reve)
                }
            } else {
            }
        });
    }

    public flushZdl() {
        this.main.player.flushZdl(this.main)
        let role = this.main.player.role;
        this.mZdl.string = '' + role.zdl;
    }
    public flush() {
        let role = this.main.player.role;

        let roleIcon = this.main.sManage.getRoleIconById(role.icon)
        if (roleIcon) {
            cc.resources.load('icon/role_head/' + roleIcon.icon, cc.SpriteFrame, (err, spriteFrame: cc.SpriteFrame) => {
                if (err) {
                    cc.error(err);
                } else {
                    this.mIcon.spriteFrame = spriteFrame;
                }
            });
        }
        let roleFrame = this.main.sManage.getRoleIconById(role.frame)
        if (roleFrame) {
            cc.resources.load('icon/role_head/txk/' + roleFrame.icon, cc.SpriteFrame, (err, spriteFrame: cc.SpriteFrame) => {
                if (err) {
                    cc.error(err);
                } else {
                    this.mFrame.spriteFrame = spriteFrame;
                }
            });
        }
    }
    public flushRole() {
        let pet1 = this.main.player.getPet(1)
        this.updateRole(pet1, this.mRole1);
        let pet2 = this.main.player.getPet(2)
        this.updateRole(pet2, this.mRole2);
        let pet3 = this.main.player.getPet(3)
        this.updateRole(pet3, this.mRole3);
    }

    public flushActivity() {
        this.main.gameHttp.sendJson(`firstPay/v1/data`, {}, (state, reve: ReveData) => {
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    if (reve.data.firstPay.count == 3) {
                        this.activityNode.getChildByName("1001").active = false;
                    }
                } else {
                    this.main.showTips(reve.message);
                }
            } else {
                this.main.showTips('网络异常');
            }
        });

    }
    private updateRole(pet: PetAttr, spine: sp.Skeleton) {
        if (pet == null) {
            spine.node.active = false
        } else {
            spine.node.active = true
            let mWeapon1: sp.spine.Bone = spine.findBone('control');
            if (mWeapon1) {
                // mWeapon1.data.rotation = 45;
                mWeapon1.rotation = -45;
            }
            // let attrData = FFCalAttr.getAttr(this.main, pet);
            // if (attrData.skin) {
            //     spine.setSkin(attrData.skin)
            // }
            // if (attrData.weapon) {
            //     Equip.chaneWeapon(spine, attrData.weapon)
            // }
        }
    }
    /**
     * 监听网络
     * @param reveData 
     */
    public httpEvent(reveData: ReveData) {
        let data = reveData.data;
        if (data._role != undefined) {
            // this.flush();
            this.topMenu.refresh();
        }
        this.flushZdl();

        if (data._equip != undefined) {
            this.flushEquipRedPoint(true);
        }
        //['email']
        if (data._msgPush != undefined) {
            if (data._msgPush.indexOf('email') >= 0) {//有新邮件
                RedPoint.addRed(this.main, this.topMenu.mEmailNode, true)
            }
        }

    }
    /**
     * 刷新角色红点
     */
    public flushEquipRedPoint(force?: boolean) {
        if (RedPoint.petsRedPoint(this.main)) {
            RedPoint.addRed(this.main, this.mEquipNode, force)
        } else {
            RedPoint.removeRed(this.mEquipNode)
        }
    }
    /**
     * 角色查看
     */
    public onclickRoleIcon() {
        this.main.playerEffectByPath(AudioMgr.click);
        this.main.viewManage.loadFunc(GameViewType.tap_role, (viewObject: ViewObject) => {
            viewObject.show();
        });
    }

    public setMxCallback(callback: () => void) {
        this.mxCallback = callback
    }

    /**
     * 地图
     */
    public onclickMap() {
        this.main.playerEffectByPath(AudioMgr.click);
        let isNewGuide = false
        if (this.mxCallback) {
            this.mxCallback()
            isNewGuide = true
        }
        this.main.viewManage.loadFunc(GameViewType.stageView, (viewObject: ViewObject) => {
            let stage = viewObject as Stage;
            stage.load((result: number) => {
                if (result == 0) {
                    if (isNewGuide) {
                        stage.inGuide = 1
                    }
                    viewObject.show(this);
                } else {
                    this.main.showTips('载入地图失败')
                }
            });
        });

    }
    /**
     * 背包
     */
    public onclickPack() {
        // if (Pack.instance) {
        //     Pack.instance.flush();
        //     Pack.instance.show();
        // } else {

        // }
        this.main.playerEffectByPath(AudioMgr.click);
        this.main.startLoad();
        this.main.viewManage.loadFunc(GameViewType.pack, (viewObject: ViewObject) => {
            viewObject.show(this);
        });
    }
    /**
     * 神卡
     */
    public onclickJitan() {
        this.main.playerEffectByPath(AudioMgr.click);
        this.main.viewManage.loadFunc(GameViewType.god_card, (viewObject: ViewObject) => {
            viewObject.show(this);
        });
    }

    /**
     * 装备
     */
    public onclickEquip() {
        this.main.playerEffectByPath(AudioMgr.click);
        this.main.startLoad();
        RedPoint.removeRed(this.mEquipNode)
        this.main.viewManage.loadFunc(GameViewType.equip, (viewObject: ViewObject) => {
            viewObject.show(this);
        });
    }
    /**
     * 魔盒
     */
    public onclickMohe() {
        this.main.playerEffectByPath(AudioMgr.click);
        this.main.viewManage.loadFunc(GameViewType.mohe, (viewObject: ViewObject) => {
            viewObject.show(this);
        });
    }

    /**
     * 商城
     */
    public openShop(eventTouch: cc.Event.EventTouch, data: string) {
        this.main.playerEffectByPath(AudioMgr.click);
        this.main.startLoad();
        this.main.viewManage.loadFunc(GameViewType.tap_shop, (viewObject: ViewObject) => {
            let shopView = viewObject as ShopView;
            shopView.init(Number(data));
            shopView.show();
        });
    }

    /**
     * 首冲
     */
    public openFirstPay(eventTouch: cc.Event.EventTouch, data: string) {
        this.main.playerEffectByPath(AudioMgr.click);
        this.main.startLoad();
        this.main.viewManage.loadFunc(GameViewType.firstPay, (viewObject: ViewObject) => {
            let firstPayView = viewObject as FirstPay;
            firstPayView.getFirstPayData("data");
        });
    }

    /**
     * 每日祝福
     */
    public openWish(eventTouch: cc.Event.EventTouch, data: string) {
        this.main.playerEffectByPath(AudioMgr.click);
        this.main.startLoad();
        this.main.viewManage.loadFunc(GameViewType.wish, (viewObject: ViewObject) => {
            let wishView = viewObject as Wish;
            wishView.getWishData();
        });
    }

    /**
     * 复仇礼包
     */
    public openRevenge() {
        this.main.playerEffectByPath(AudioMgr.click);
        this.main.startLoad();
        this.main.viewManage.loadFunc(GameViewType.revenge, (viewObject: ViewObject) => {
            let revengeView = viewObject as Revenge;
            this.revengeView = revengeView;
            revengeView.getRevengeData();
            revengeView.refreshTime(this.revengeTime);
            revengeView.setBuyClickFunc(() => {
                this.showRevengeBtn(false);
            })
        });
    }

    // 激活复仇礼包
    public activiteRevenge() {
        let msg = {
            id: 1001,
        };
        this.main.gameHttp.sendJson(`revenge/v1/open`, msg, (state, reve: ReveData) => {
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    console.log("====复仇礼包激活成功===");
                    this.getRevengeData();
                } else {
                    this.main.showTips(reve.message);
                }
            } else {
                this.main.showTips('网络异常');
            }
        })
    }

    public getRevengeData() {
        let msg = {};
        let nowTime1 = CUtilTime.getNowTime();
        this.main.gameHttp.sendJson(`revenge/v1/data`, msg, (state, reve: ReveData) => {
            let nowTime2 = CUtilTime.getNowTime() - nowTime1;
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    console.log("=home=reve=revengeData===", reve)
                    let data = reve.data.data[reve.data.list[0].id];
                    if (data) {
                        if (data.value == 2) {    // 购买过
                            this.showRevengeBtn(false);
                            return
                        }
                        let time = data.time;
                        if (time > 0) {
                            this.showRevengeBtn(true);
                            this.revengeTime = time - nowTime2;
                            this.revengeBtn.getChildByName("time").getComponent(cc.Label).string = `剩余 ${CUtilTime.getTimeString2(time - nowTime2)}`;
                        } else {
                            this.showRevengeBtn(false);
                        }
                    }

                    if (cc.sys.localStorage.getItem("showRevenge" + this.main.player.role.id) == 1) {
                        cc.sys.localStorage.setItem("showRevenge" + this.main.player.role.id, 2);
                        this.main.viewManage.loadFunc(GameViewType.revenge, (viewObject: ViewObject) => {
                            let revengeView = viewObject as Revenge;
                            this.revengeView = revengeView;
                            revengeView.revengeData = reve.data.list[0];
                            revengeView.show();
                            revengeView.initItem();
                            revengeView.refreshTime(this.revengeTime);
                            revengeView.setBuyClickFunc(() => {
                                this.showRevengeBtn(false);
                            })
                        });
                    }
                } else {
                    this.main.showTips(reve.message);
                }
            } else {
                this.main.showTips('网络异常');
            }
        });
    }

    showRevengeBtn(show = false) {
        this.revengeBtn.active = show;
    }

    tempTime: number = 0;
    update(dt) {
        if (this.revengeTime <= 0) {
            this.showRevengeBtn(false);
            if (this.revengeView) {
                this.revengeView.exitDistroy();
            }
            return
        }
        this.tempTime += dt;
        if (this.tempTime >= 1) {
            this.revengeTime -= 1;
            this.revengeBtn.getChildByName("time").getComponent(cc.Label).string = `剩余 ${CUtilTime.getTimeString2(Math.floor(this.revengeTime))}`;
            this.tempTime = 0;
            if (this.revengeView) {
                this.revengeView.refreshTime(this.revengeTime);
            }
        }
    }
}