import {getSkinPath} from "../../../utils";
import {MainDispatcher, MainIns} from "../MainScene";
import {NetManager} from "../../../../libs/tw/manager/NetManager";
import {btnDelay, showToast} from "../../../comm/UtilsConst";
import {M_Plant} from "../LandMgr";
import M_EVENT from "../MSceneEnum";
import {G_GetHomeDataByKey, G_UpdateHomeData, HOME} from "../../Home";
import PanelCtrl from "../../../ctrls/panelCtrl";
import IntroducePanel from "../../../Panels/IntroducePanel";
import Tween = egret.Tween;
import Ease = egret.Ease;
import {CROP_TYPE} from "../Const";
import TouchEvent = egret.TouchEvent;
import Component = eui.Component;
import {Tools} from "../../../Tools";

// 触发Option隐藏
const M_HideOption = function () {
    MainDispatcher.dispatchEvent(M_EVENT.HIDE_OPTION);
};
// 显示Option
const M_ShowOption = function (data: { index: number }) {
    MainDispatcher.dispatchEvent(M_EVENT.SHOW_OPTION, data);
};
export {M_HideOption, M_ShowOption};

const seedKV = {
    sp_seed_1: 'chick',   // 鸡
    sp_seed_2: 'wheat',   // 麦子
    sp_seed_3: 'corn',   // 玉米
    sp_seed_4: 'cattle',   // 牛
    sp_seed_5: 'potato',   // 土豆
    sp_seed_6: 'walnut',   // 核桃
}

/**
 * 操作面板
 */
export default class OptionPanel extends Component {
    public chickBtn: eui.Group;
    public cattleBtn: eui.Image;
    public cornBtn: eui.Image;
    public wheatBtn: eui.Group;
    public walnutBtn: eui.Image;
    public potatoBtn: eui.Image;
    public leftBtn:eui.Image;
    public rightBtn:eui.Image;
    public petScroll:eui.Scroller;

    private data = null;

    ////////////////////// 单例 //////////////////////
    private static _instance: OptionPanel = null;

    public static getInstance(data?) {
        return OptionPanel._instance || (OptionPanel._instance = new OptionPanel(data))
    }

    public static destroy() {
        this._instance.removeEvents();
        this._instance = null;
    }

    ////////////////////// 单例 //////////////////////

    constructor(data?) {
        super();
        this.skinName = getSkinPath('Objs/OptionPanel');
        this.data = data || null;

        this.initEvents();
        this.initUI()
    }

    private initEvents() {
        [
            this.wheatBtn,
            this.chickBtn,
            this.cattleBtn,
            this.cornBtn,
            this.potatoBtn,
            this.walnutBtn,
            this.leftBtn,
            this.rightBtn
        ].forEach((v) => {
            v.addEventListener(TouchEvent.TOUCH_TAP, this.onTap, this);
        });
        MainDispatcher.addEvent(M_EVENT.SHOW_OPTION, this.showOption, this);
        MainDispatcher.addEvent(M_EVENT.HIDE_OPTION, this.hideOption, this);
    }

    private removeEvents() {
        [
            this.wheatBtn,
            this.chickBtn,
            this.cattleBtn,
            this.cornBtn,
            this.potatoBtn,
            this.walnutBtn,
            this.leftBtn,
            this.rightBtn
        ].forEach((v) => {
            v.removeEventListener(TouchEvent.TOUCH_TAP, this.onTap, this);
        });
        MainDispatcher.removeEvent(M_EVENT.SHOW_OPTION, this.showOption, this);
        MainDispatcher.removeEvent(M_EVENT.HIDE_OPTION, this.hideOption, this);
    }

    private showOption(data?) {
        console.log(data);
        this.data = data;

        M_HideOption();   // 先触发隐藏，保证地块正常显示

        this.showSeed();    // 根据有的种植展示

        Tween.removeTweens(this);

        this.touchEnabled = true;
        this.touchChildren = true;
        this.alpha = 1;
        if (this.visible) {
            return;
        }
        this.visible = true;
        Tween.get(this).set({alpha: 0}).to({alpha: 1}, 170);
    }

    // 查查有几个种子
    private showSeed() {
        let colorMatrix = [
            0.3, 0.3, 0.3, 0, 0,
            0.3, 0.3, 0.3, 0, 0,
            0.3, 0.3, 0.3, 0, 0,
            0, 0, 0, 1, 0
        ];
        let colorFilter = new egret.ColorMatrixFilter(colorMatrix);

        const seeds = G_GetHomeDataByKey(HOME.SEED);
        for (let k in seeds) {
            if (seeds[k] > 0) {
                this[`${seedKV[k]}Btn`].filters = [];
            } else {
                this[`${seedKV[k]}Btn`].filters = [colorFilter];
            }

            this[`${seedKV[k]}Btn`].seedNum = seeds[k];
        }


    }

    private hideOption() {
        if (!this.visible) {
            return;
        }
        this.touchEnabled = false;
        this.touchChildren = false;
        Tween.removeTweens(this);
        Tween.get(this).to({alpha: 0}, 170).call(() => {
            this.visible = false;
        });
    }

    private onTap(e: TouchEvent) {
        const target = e.target;
        if (e.target.seedNum <= 0) {
            showToast('这个没有了，快去商店购买吧');
            return;
        }
        btnDelay(target);
        let petId;
        switch (target) {
            case this.chickBtn: // 鸡
                petId = CROP_TYPE.CHICKEN;
                break;

            case this.wheatBtn: // 小麦
                petId = CROP_TYPE.WHEAT;
                break;

            case this.cornBtn:  // 玉米
                petId = CROP_TYPE.CORN;
                break;

            case this.cattleBtn: // 牛
                petId = CROP_TYPE.CATTLE;
                break;

            case this.potatoBtn: // 土豆
                petId = CROP_TYPE.POTATO;
                break;

            case this.walnutBtn: // 核桃
                petId = CROP_TYPE.WALNUT;
                break;
            case this.leftBtn:
                var contentWidth = this.petScroll.viewport.contentWidth;
                var toscrollh = this.petScroll.viewport.scrollH - 150;
                if(toscrollh<0)toscrollh=0;
                this.petScroll.viewport.scrollH = 0;
                return;
            case this.rightBtn:
                var contentWidth = this.petScroll.viewport.contentWidth;
                var toscrollh = this.petScroll.viewport.scrollH+150;
                if(toscrollh>contentWidth-531)toscrollh=contentWidth-531;
                this.petScroll.viewport.scrollH = contentWidth-531;
                return;
            default:
                break;
        }

        const call = () => {
            // 0s（100%,100%）-0.1s(120%,120%)-0.2s(100%,100%)
            Tween.get(target).to({scaleX: 1.2, scaleY: 1.2}, 100, Ease.quadIn)
                .to({scaleX: 1, scaleY: 1}, 100, Ease.quadOut).call(() => {
                M_HideOption();
                console.log(this.data.index, petId);
                NetManager.ins.doPlant((success) => {
                    if (!success) {
                        return;
                    }
                    M_Plant({landId: this.data.index, petId: petId});

                    G_UpdateHomeData();
                    Tools.judgeMedalPanel();    // 检查是否可以弹出勋章

                }, this.data.index, petId);
            });
        }

        M_HideOption();
        PanelCtrl.instance.show(IntroducePanel, {
            call: call,
            petId: petId,
            landId: this.data.index
        });

    }

    private initUI() {
        this.visible = false;
        this.x = 170 + 190;
        this.y = 669 + 50 - (MainIns().gameLayer.height - MainIns().group.height) / 2;
        this.anchorOffsetX = this.width / 2;
        this.anchorOffsetY = this.height;
    }
}
