import Scene from "../../views/Scene";
import MainUI from "./MainUI";
import LandMgr from "./LandMgr";
import OptionPanel, { M_HideOption } from "./Objs/OptionPanel";
import Dispatcher from "../../comm/Dispatcher";
import ProgressMgr from "./ProgressMgr";
import SceneCtrl from "../../ctrls/sceneCtrl";
import { ModuleTypes } from "../../types/sceneTypes";
import Group = eui.Group;
import Image = eui.Image;
import { preLoadRes } from "../../comm/UtilsConst";
import M_EVENT from "./MSceneEnum";
import Label = eui.Label;
import { Tools } from "../../Tools";
import TouchEvent = egret.TouchEvent;
import { NetManager } from "../../../libs/tw/manager/NetManager";
import { getlogItem } from "../../comm/getlogItem";
import Tween = egret.Tween;

////////////////// Instance //////////////////
let instance: MainScene = null;
const MainIns = function (): MainScene {
    return instance;
};
const SetMainInstance = function (ins: MainScene) {
    instance = ins;
};
const DestroyMainInstance = function () {
    instance = null;
};

export { MainIns };
////////////////// Instance //////////////////

// Index场景的事件收发器
let MainDispatcher: Dispatcher = null;
export { MainDispatcher };

const NewMainDispatcher = function () {
    MainDispatcher = new Dispatcher()
};
const DestroyMainDispatcher = function () {
    MainDispatcher = null;
};

/**
 * 主场景
 * Tips：
 *   1.在本场景中因为需求坑爹（需要上下居中适配并加固定导航栏），所以进行手动适配
 *   2.在MainScene中：
 *       group 为适配层，该层 height = 实际画布高度
 *       gameLayer 为游戏层，该层在 group 中上下居中
 *       获得高度差可用 gameLayer.height - group.height
 *       需要将非 gameLayer 层中对象准确定位可将定位高度减去 上面的值/2 -> (1624 - 750 / window.innerWidth * window.innerHeight) / 2
 *   3.使用上面的 MainIns() 可取得IndexScene的场景单例，该单例在MainScene场景销毁时会自动销毁，MainScene场景生成时自动赋值
 *   4.使用上面的 MainDispatcher 可取得独立在MainScene的场景中的事件收发器单例，该单例在MainScene场景销毁时会自动销毁，MainScene场景生成时自动赋值
 */
export default class MainScene extends Scene {
    public group: Group;
    public bg: Image;
    public gameLayer: Group;
    public rule: Image;

    public mainUI: MainUI;
    public optionPanel: OptionPanel;
    public progressMgr: ProgressMgr;

    public houseBtn: Group;

    public xiaoE: eui.Group;
    advertBtn: eui.Group
    public xiaoEGroup: eui.Group;
    public xiaoEGroupList: eui.List;

    public xiaoEAnswer: eui.Group;
    public answerTitle: eui.Label;
    public answerTxt: eui.Label;
    public xiaoETip: eui.Group;
    public xiaoETipImg: eui.Image;
    public xiaoEIKnow: eui.Label;

    public posterImg:eui.Image;
    public posterGroup:eui.Group;
    public posterLabel:eui.Label;


    constructor(data?) {
        super(data);
    }

    public landMgr: LandMgr = null;

    protected start() {
        super.start();
        SetMainInstance(this); // 设置单例
        NewMainDispatcher();   // 创建一个局部事件收发器
        this.initUI();

        // 预加载资源
        preLoadRes('exchange', 'introduce_panel', 'task_panel', 'warehouse', 'medals', 'room');
    }

    private initUI(): void {
        this.height = 750 / window.innerWidth * window.innerHeight;

        // 创建UI层
        this.mainUI = new MainUI();
        this.addChild(this.mainUI);

        this.gameLayer.touchThrough = true; // 点击穿透。。防止设计touchEnable后无法点击bg

        // 创建进度条管理器
        this.progressMgr = new ProgressMgr();

        // 创建土地管理器
        this.gameLayer.touchEnabled = false;
        this.landMgr = new LandMgr(this);

        // 创建操作Panel（初始为隐藏状态）
        this.optionPanel = OptionPanel.getInstance();
        this.addChild(this.optionPanel);

        

        MainDispatcher.addEvent(M_EVENT.HIDE_OPTION, () => {
            this.xiaoEGroup.visible = false;
            this.xiaoEAnswer.visible = false;
            // this.hideXiaoETip();
        }, this);

        const question = JSON.parse(JSON.stringify(Tools.xiaoEQuestion));
        for (let i = 0; i < Tools.xiaoEQuestion.length; i++) {
            question[i]['showAnswer'] = this.showAnswer;
        }
        this.xiaoEGroupList.itemRenderer = QuestionItem;
        this.xiaoEGroupList.dataProvider = new eui.ArrayCollection(question);

        NetManager.ins.showLog(getlogItem(7));
        NetManager.ins.showLog(getlogItem(9));
        this.changePoster();

    }

    /**修改广告位 */
    private changePoster() {
        let balloonUrl = Tools.frontInfo.data.balloonUrl;
        console.log('rgreg--->>',balloonUrl);
        const { body, link, bodyType } = balloonUrl;
        if(bodyType == 1){
            this.posterLabel.text = body;
            this.posterGroup.visible = true;
        }else{
            RES.getResByUrl(link,(data)=>{
                this.posterImg.source = data;
                this.posterGroup.visible = true;
            },this)
        }
    }

    private showAnswer = (data) => {
        this.answerTitle.text = data.content;
        this.answerTxt.text = data.answer;
        this.xiaoEAnswer.visible = true
        this.xiaoEGroup.visible = false;
        this.hideXiaoETip();
    }

    private showQuestion = () => {
        this.xiaoEAnswer.visible = false
        this.xiaoEGroup.visible = true;
        this.hideXiaoETip();
    }

    public hideXiaoETip() {
        Tween.removeTweens(this.xiaoETip);
        this.xiaoETipType = null;
        this.xiaoETip.visible = false;
    }

    private xiaoETipType: string = null;
    public showXiaoETip = (type: string) => {
        this.xiaoEAnswer.visible = false
        this.xiaoEGroup.visible = false;

        if (this.xiaoETipType == type) return;

        this.xiaoETipType = type;

        this.xiaoETipImg.source = `xiaoETip_${type}_png`;

        Tween.removeTweens(this.xiaoETip);
        Tween.get(this.xiaoETip)
            .set({ visible: true, alpha: 0 })
            .to({ alpha: 1 }, 300)
            .wait(2000)
            .to({ alpha: 0 }, 300)
            .call(() => {
                this.xiaoETip.visible = false;
                this.xiaoETipType = null;
            });

        // xiaoETip_whooo_png   // 随机
        // xiaoETip_miss_png    // 随机

        // xiaoETip_plant_png   // 种植
        // xiaoETip_get_png     // 收获
    }

    destroy() {
        super.destroy();
        /// TODO 可能的需要清除的东西
        OptionPanel.destroy();
        this.mainUI.destroy();
        this.progressMgr.destroy();
        this.landMgr.destroy();
        DestroyMainDispatcher();    // 删除局部收发器
        DestroyMainInstance(); // 清除单例
        egret.Tween.removeAllTweens();
    }

    protected getTapEvts(): any[] {
        return super.getTapEvts().concat([
            [this.bg, this.onTouchTap, this],   // 点到bg触发Option隐藏，因为在游戏层中其他游戏元素都在bg上层
            [this.houseBtn, this.onTap, this],
            [this.xiaoE, this.onTap, this],
            [this.xiaoEAnswer, this.onTap, this],
            [this.xiaoEIKnow, this.onTap, this],
            [this.xiaoETip, this.onTap, this],
            [this.posterGroup, this.onTap, this],
        ]);
    }

    private onTouchTap(e: egret.TouchEvent) {
        switch (e.target) {
            case this.bg:
                M_HideOption();
                break;

            default:
                break;
        }
    }

    private onTap(e: egret.TouchEvent) {
        switch (e.target) {
            case this.houseBtn:
                NetManager.ins.clickLog(getlogItem(9));
                SceneCtrl.instance.change(ModuleTypes.ROOM_SCENE);
                break;

            case this.xiaoE:
                NetManager.ins.clickLog(getlogItem(7));
            case this.xiaoEAnswer:
            case this.xiaoEIKnow:
                M_HideOption();
                this.hideXiaoETip();
                this.showQuestion();
                break;

            case this.xiaoETip:
                this.hideXiaoETip();
                M_HideOption();
                break;
            case this.posterGroup:
                console.error("广告数据====？", Tools.frontInfo);
                if (Tools.frontInfo && Tools.frontInfo.data && Tools.frontInfo.data.balloonUrl) {
                    let balloonUrl = Tools.frontInfo.data.balloonUrl;
                    console.log("热气球广告位---》》", balloonUrl)
                    const { body, link, bodyType } = balloonUrl;
                    if(link&&link.length>4){
                        window.location.href = link;
                    }
                }

                break;
            default:
                break;
        }
    }

    protected async preLoadRes() {

    }

    public get skinKey() {
        return 'MainScene'
    }

    public get groupName() {
        return 'main_scene'
    }

}

// 问题列表
class QuestionItem extends eui.ItemRenderer {

    label: Label;

    constructor() {
        super();

        this.height = 40;

        const label = this.label = new Label()
        this.addChild(label);
        label.textColor = 0xe06200;
        label.size = 20;
        label.y = 10;

        const img = new Image();
        img.source = 'xiaoETip_item_btn_png';
        this.addChild(img);
        img.x = 370;
        img.y = 10;

        this.addEventListener(TouchEvent.TOUCH_TAP, this.onTap, this);
    }

    dataChanged() {
        this.label.text = this.data.content;
    }

    onTap() {
        if (+this.data.type == 0) {  // 跳链接的
            window.location.href = this.data.redirect;
        } else if (+this.data.type == 1) {
            this.data.showAnswer(this.data);
        }
    }
}

