import Panel from "../views/Panel";
import { DataManager } from "../../libs/tw/manager/DataManager";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import { NetManager } from "../../libs/tw/manager/NetManager";
import SceneCtrl from "../ctrls/sceneCtrl";
import { GDispatcher } from "../../libs/tc/util/GDispatcher";
import { Buried } from "../../libs/tw/util/Buried";
import GuidePanel from "../guidePanel/GuidePanel";
import Loading from "../loading/Loading";
/**
 * 出游界面
 */
export default class TourPanel extends Panel {
    public closeBtn: eui.Button;
    private tabBtn_0: eui.Button;//标题按钮
    private tabBtn_1: eui.Button;
    private tabBtn_2: eui.Button;
    private bgGroup: eui.Group;//背景图容器
    private bg_0: eui.Image;//背景图
    private bg_1: eui.Image;
    private bg_2: eui.Image;
    private flagGroup: eui.Group;//旗帜层，去过的地方都会插上旗帜
    private controlGroup: eui.Group;//地图控制层(拖动地图实际是在这一层控制的，地图层必须禁用鼠标事件---因为地图移动会把别的按钮盖住导致无法点击)
    private mapUnlock: eui.Group;//开放的地图
        private mapUnlockImg0: eui.Image;//开放地图1（中国）
        private mapUnlockImg1: eui.Image;//开放地图2（亚洲）
        private mapUnlockImg2: eui.Image;//开放地图3（欧洲-暂无）
    private mapLock: eui.Group;//锁住的地图
        private mapLockImg0: eui.Image;//锁住地图1（中国-无）
        private mapLockImg1: eui.Image;//锁住地图2（亚洲）
        private mapLockImg2: eui.Image;//锁住地图3（欧洲）
    private lock: eui.Group;//地图锁图标
    private maskGroup: eui.Group;//地图遮罩
    private albumBtn: eui.Button;//相册按钮
    private tourBtn: eui.Button;//出游按钮
    private surePanel: eui.Group;//出游确认框
    private popCloseBtn: eui.Button;//出游确认框关闭按钮
    private sureBtn: eui.Button;//出游确认框确认按钮
    private costTxt: eui.Label;//出游消耗提示文字
    private txt: eui.Label;//其他提示文字

    private tourCost;//出游的消耗

    private curMapName: string;//当前地图名字
    private curCollectRuleID: number;//当前页对应的集卡规则ID
    private isUnLock: boolean;//当前地图是否解锁
    private startPos:egret.Point;//开始坐标

    // public guideBack: Function;
    // private guideLayer: GuidePanel;
	public get skinKey() { return 'Tour' }
	public get groupName() { return 'tour_panel'}
    constructor(data?){
        super(data);
    }

    private init():void{
        this.onHidePop();//出游确认提示框默认不显示
        this.flagGroup = new eui.Group();
        this.mapUnlock.addChild(this.flagGroup);
        this.startPos = new egret.Point();
        this.mapUnlock.mask = this.maskGroup;
        this.mapUnlock.touchEnabled = this.mapUnlock.touchChildren = false;
        this.bgGroup.touchEnabled = this.bgGroup.touchChildren = false;
        this.curMapName = '中国'
        this.changeMap();
    }

    /**
     * 初始化tab按钮和背景图和地图
     */
    initMapAndBg(){
        this.mapUnlock.x = 0;
        this.mapUnlock.y = 0;
        for(var i=0; i<3; i++){
            this['tabBtn_'+i].currentState = 'up';
            this['bg_'+i].visible = false;
            if(this['mapUnlockImg'+i]){
                this['mapUnlockImg'+i].visible = false;
            }
            if(this['mapLockImg'+i]){
                this['mapLockImg'+i].visible = false;
            }
        }
    }

	start(data?:any){
        this.percentHeight = 100;
        // this.guideBack = data;
    }
    
    protected onSkinComplete():void{
        super.onSkinComplete();

        //出游界面曝光埋点
        const dpm = Buried.connectDpm(110, 2, 1);
        const dcm = Buried.connectDcm(230, window['skinID'], 0);
        const embedDomain = DataManager.ins.petIndexData.embedDomain;
        const exposure = Buried.createExposure(dpm, dcm, embedDomain);
        NetManager.ins.showLog(exposure);

        this.init();
        // if(this.guideBack){
		// 	this.showGuide(6);
        // }
    }

    /**
     * 切换地图
     * @param e 
     */
    private changeMap(e?:egret.TouchEvent):void{
        if(e){
            if(this.curMapName == e.currentTarget.label){//重复点击
                return;
            }
            this.curMapName = e.currentTarget.label;
        }
        this.curCollectRuleID = window['collectRuleIdList'] ? window['collectRuleIdList'][this.curMapName=='中国' ? 0 : (this.curMapName=='亚洲' ? 1 : 2)] : 1;
        this.initMapAndBg();
        var mapLockCFG = window['mapLockCFG'] ? window['mapLockCFG'] : {};
        //地图解锁的最小等级
        var minLv = mapLockCFG[this.curMapName];
        console.log(777777777);
        if(DataManager.ins.petHomeInfoData.petLevel >= minLv && this.curCollectRuleID != 0){
            //当前地图场景已解锁开放
            this.isUnLock = true;
            this.controlGroup.visible = true;
            this.mapUnlock.visible = true;
            this.mapLock.visible = false;
            this.lock.visible = false;
            //获取当前地图集卡
            NetManager.ins.getCollectRule(()=>{
                this.updateFlag();
            }, this.curCollectRuleID);
        }else{//未解锁
            this.isUnLock = false;
            this.controlGroup.visible = false;
            this.mapUnlock.visible = false;
            this.mapLock.visible = true;
            this.lock.visible = true;
        }
        if(this.curMapName == '中国'){
            //点击埋点，中国
            const dpm = Buried.connectDpm(110, 2, 3);
            const dcm = Buried.connectDcm(230, window['skinID'], 0);
            const embedDomain = DataManager.ins.petIndexData.embedDomain;
            const exposure = Buried.createExposure(dpm, dcm, embedDomain);
            NetManager.ins.clickLog(exposure);
            NetManager.ins.showLog(exposure);

            this.bg_0.visible = true;
            this.tabBtn_0.currentState = 'down';
            this.mapUnlockImg0.visible = true;
        }else if(this.curMapName == '亚洲'){
            //点击埋点，亚洲
            const dpm = Buried.connectDpm(110, 2, 4);
            const dcm = Buried.connectDcm(230, window['skinID'], 0);
            const embedDomain = DataManager.ins.petIndexData.embedDomain;
            const exposure = Buried.createExposure(dpm, dcm, embedDomain);
            NetManager.ins.clickLog(exposure);
            NetManager.ins.showLog(exposure);

            this.bg_1.visible = true;
            this.tabBtn_1.currentState = 'down';
            this.mapUnlockImg1.visible = this.mapLockImg1.visible = true;
        }else if(this.curMapName == '欧洲'){
            //点击埋点，欧洲
            const dpm = Buried.connectDpm(110, 2, 5);
            const dcm = Buried.connectDcm(230, window['skinID'], 0);
            const embedDomain = DataManager.ins.petIndexData.embedDomain;
            const exposure = Buried.createExposure(dpm, dcm, embedDomain);
            NetManager.ins.clickLog(exposure);
            NetManager.ins.showLog(exposure);

            this.bg_2.visible = true;
            this.tabBtn_2.currentState = 'down';
            this.mapLockImg2.visible = true;
        }
    }

    /**
     * 插旗
     */
    private updateFlag():void{
        this.flagGroup.removeChildren();
        const mapPosCFG = window['mapPosCFG'] ? window['mapPosCFG'] : {};
        // const rule = DataManager.ins.getCollectRuleData.collectRules[0].rule;
        const rule = DataManager.ins.getCollectRuleData.collectGoods;
        for (const obj of rule) {
            const group = new eui.Group();
            const flag = new eui.Image();
            if(obj.count > 0){
                flag.source = '立牌_png';
                group.addChild(flag);
                const nameLab = new eui.Label();
                nameLab.width = 77;
                nameLab.height = 32;
                nameLab.textAlign = 'center';
                nameLab.verticalAlign = 'middle';
                nameLab.fontFamily = 'Helvetica';
                nameLab.textColor = 0x4a2f09;
                if(obj.name.length > 3){//字数大于3个用16号字
                    nameLab.size = 16;
                }else{
                    nameLab.size = 22;
                }
                nameLab.text = obj.name;
                group.addChild(nameLab);
                nameLab.x = 0;
                nameLab.y = 0
                
            }else{
                flag.source = '地点锁_png';
                group.addChild(flag);
                flag.x = 24;
                flag.y = 20;
            }
            this.flagGroup.addChild(group);
            if(mapPosCFG[this.curMapName][obj.name]){
                group.x = mapPosCFG[this.curMapName][obj.name][0];
                group.y = mapPosCFG[this.curMapName][obj.name][1];
            }
        }
    }

    /**
     * 按下地图
     */
    private onDown_Map(e:egret.TouchEvent):void{
        this.startPos.x = e.stageX;
        this.startPos.y = e.stageY;
    }

    /**
     * 移动地图
     */
    private onMove_Map(e:egret.TouchEvent):void{
        var deviationX = this.startPos.x - e.stageX;
        var deviationY = this.startPos.y - e.stageY;
        if(this.mapUnlock.x - deviationX > this.maskGroup.x){
            this.mapUnlock.x = this.maskGroup.x;
        }else if(this.mapUnlock.x - deviationX < (this.maskGroup.x+this.maskGroup.width) - this.mapUnlock.width){
            this.mapUnlock.x = (this.maskGroup.x+this.maskGroup.width) - this.mapUnlock.width;
        }else{
            this.mapUnlock.x = this.mapUnlock.x - deviationX;
        }
        if(this.mapUnlock.y - deviationY > this.maskGroup.y){
            this.mapUnlock.y = this.maskGroup.y;
        }else if(this.mapUnlock.y - deviationY < (this.maskGroup.y+this.maskGroup.height) - this.mapUnlock.height){
            this.mapUnlock.y = (this.maskGroup.y+this.maskGroup.height) - this.mapUnlock.height;
        }else{
            this.mapUnlock.y = this.mapUnlock.y - deviationY;
        }
    }

    /**
     * 打开相册界面
     */
    private onClick_albumBtn(e:egret.TouchEvent):void{
        if(!this.isUnLock){
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, ['地图还未解锁'], false);
            return;
        }
        NetManager.ins.getCollectGoodsInfo(() => {
            this.hidePanel();
            PanelCtrl.instance.show(ModuleTypes.ALBUM_PANEL);
        }, this.curCollectRuleID);
        
        //点击埋点，相册
        const dpm = Buried.connectDpm(110, 2, 1);
        const dcm = Buried.connectDcm(230, window['skinID'], 0);
        const embedDomain = DataManager.ins.petIndexData.embedDomain;
        const exposure = Buried.createExposure(dpm, dcm, embedDomain);
        NetManager.ins.clickLog(exposure);
    }

    /**
     * 出游
     */
    private onClick_tourBtn(e:egret.TouchEvent):void{
        if(!this.isUnLock){
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, ['地图还未解锁'], false);
            return;
        }

		if(DataManager.ins.petHomeInfoData.status == 1 && !DataManager.ins.petHomeInfoData.isFull){
			PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,["小海豚太饿了，没力气出去玩啦", "快去喂食吧~"], false);
			return;
        }
        
        console.log('出游');
        this.surePanel.visible = true;
        this.tourCost = window['tourCost'] ? window['tourCost'] : 0;
        this.costTxt.text = '即将花费' + this.tourCost + DataManager.ins.petIndexData.creditsUnitName + '出游';
        this.txt.text = '收集旅游相册，记录足迹';

        //点击埋点，出游
        const dpm = Buried.connectDpm(110, 2, 2);
        const dcm = Buried.connectDcm(230, window['skinID'], 0);
        const embedDomain = DataManager.ins.petIndexData.embedDomain;
        const exposure = Buried.createExposure(dpm, dcm, embedDomain);
        NetManager.ins.clickLog(exposure);

        //曝光埋点，确认出游按钮
        const dpm1 = Buried.connectDpm(110, 3, 1);
        const dcm1 = Buried.connectDcm(230, window['skinID'], 0);
        const embedDomain1 = DataManager.ins.petIndexData.embedDomain;
        const exposure1 = Buried.createExposure(dpm1, dcm1, embedDomain1);
        NetManager.ins.showLog(exposure1);


        // if(this.guideBack){
        //     this.showGuide(7);
        // }
    }

    /**
     * 确认出游
     * @param e 
     */
    private onClick_sureBtn(e:egret.TouchEvent):void{
        Loading.instace.show();
        this.onHidePop();
        if(DataManager.ins.petIndexData.credits < this.tourCost){
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, [ DataManager.ins.petIndexData.creditsUnitName + '不足'], false);
            return;
        }
        let mapType;
        if(this.curMapName == '中国'){
            mapType = 1;
        }else if(this.curMapName == '亚洲'){
            mapType = 2;
        }else if(this.curMapName == '欧洲'){
            mapType = 3;
        }
        NetManager.ins.petGoout(this.petGoout_Back.bind(this), DataManager.ins.petIndexData.activityId, DataManager.ins.petHomeInfoData.petId, mapType);
    
        //点击埋点，确认出游
        const dpm = Buried.connectDpm(110, 3, 1);
        const dcm = Buried.connectDcm(230, window['skinID'], 0);
        const embedDomain = DataManager.ins.petIndexData.embedDomain;
        const exposure = Buried.createExposure(dpm, dcm, embedDomain);
        NetManager.ins.clickLog(exposure);

        // if(this.guideBack){
        //     this.guideBack(8);
        // }
    }
    private petGoout_Back(success:boolean):void{
        if(!success){
            Loading.instace.hide();
            return;
        }
        console.log('出游回调成功');
        NetManager.ins.petGooutResult(()=>{
            DataManager.ins.petIndexData.credits -= this.tourCost;
            GDispatcher.dispatchEvent('onTour');
            Loading.instace.hide();
        }, DataManager.ins.petIndexData.activityId, 
            DataManager.ins.petHomeInfoData.petId, 
            DataManager.ins.gooutData.recordId, 
            this.pollingCheck.bind(this), 10);
        this.hidePanel();
    }

    //轮询
    private pollingCheck(data: any):boolean{
        return data.status!=2;
	}
    
    /**
     * 隐藏出游确认弹框
     */
    private onHidePop():void{
        this.surePanel.visible = false;
    }

    initEvents():void{
        this.closeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.hidePanel, this);
        for(var i=0; i<3; i++){
            this['tabBtn_'+i].addEventListener(egret.TouchEvent.TOUCH_TAP, this.changeMap, this);
        }
        this.controlGroup.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onDown_Map, this);
        this.controlGroup.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_Map, this);
        this.albumBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_albumBtn, this);
        this.tourBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_tourBtn, this);
        this.popCloseBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onHidePop, this);
        this.sureBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_sureBtn, this);
    }

    removeEvents() {
        this.closeBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.hidePanel, this);
        for(var i=0; i<3; i++){
            this['tabBtn_'+i].removeEventListener(egret.TouchEvent.TOUCH_TAP, this.changeMap, this);
        }
        this.controlGroup.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onDown_Map, this);
        this.controlGroup.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_Map, this);
        this.albumBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_albumBtn, this);
        this.tourBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_tourBtn, this);
        this.popCloseBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onHidePop, this);
        this.sureBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_sureBtn, this);
    }

    // private showGuide(index:number):void{
    //     this.hideGuide();
	// 	if(!this.guideLayer){
	// 		this.guideLayer = new GuidePanel();
	// 		this.addChild(this.guideLayer);
    //     }
        
    //     const thisH = Math.floor(750 / document.body.clientWidth * document.body.clientHeight)
    //     let w;
    //     let h;
    //     let x;
    //     let y;
    //     if(index == 6){//指向出游按钮
    //         w = 422;
    //         h = 125;
    //         x = this.tourBtn.x;
    //         y = thisH - this.tourBtn.bottom - h;
    //     }else if(index == 7){//指向确认出游按钮
    //         w = 422;
    //         h = 115;
    //         x = this.sureBtn.x;
    //         y = this.surePanel.y + this.sureBtn.y;
    //     }
    //     this.guideLayer.updateData(index, x, y, w, h)
    // }

	// private hideGuide():void{
	// 	if(this.guideLayer){
	// 		this.guideLayer.dispose();
	// 		this.removeChild(this.guideLayer);
	// 		this.guideLayer = null;
	// 	}
	// }
}