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";
import { getlogItem } from "../../../comm/getlogItem";
import ShopPanel from "../../../Panels/ShopPanel";

// 触发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',   // 核桃
    sp_seed_7: 'apple',   // 土豆
    sp_seed_8: 'papaya',   // 核桃
}

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

    private data = null;

    public appleBtn: eui.Group;
    public papayaBtn: eui.Group;
    ////////////////////// 单例 //////////////////////
    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.appleBtn,
            this.papayaBtn,
            this.leftBtn,
            this.rightBtn
        ].forEach((v) => {
            if (v instanceof eui.Group) {
                v.touchChildren = false;
            }
            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.appleBtn,
            this.papayaBtn,
            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);
        let haveidx = [];
        let nohaveidx = [];
        for (let k in seeds) {
            if (seeds[k] > 0) {
                this[`${seedKV[k]}Btn`].filters = [];
                haveidx.push(this[`${seedKV[k]}Btn`]);
            } else {
                this[`${seedKV[k]}Btn`].filters = [colorFilter];
                nohaveidx.push(this[`${seedKV[k]}Btn`]);
            }

            this[`${seedKV[k]}Btn`].seedNum = seeds[k];
        }
        let itemgro: eui.Group = this.petScroll.viewport as eui.Group;
        let childidx = 0;
        for (let hitem of haveidx) {
            itemgro.setChildIndex(hitem, childidx);
            childidx++;
        }
        for (let nitme of nohaveidx) {
            itemgro.setChildIndex(nitme, childidx);
            childidx++;
        }
    }

    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('这个没有了，快去商店购买吧');
            NetManager.ins.clickLog(getlogItem(6));
            PanelCtrl.instance.show(ShopPanel);
            M_HideOption();
            return;
        }
        btnDelay(target);
        let petId;
        console.log("aaaaa-->>", target)
        switch (target) {
            case this.chickBtn: // 鸡
                console.log('????????fku')
                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.appleBtn: // 土豆
                petId = CROP_TYPE.APPLE;
                break;

            case this.papayaBtn: // 核桃
                petId = CROP_TYPE.PAPAYA;
                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();
        console.log("点击了---》》", petId)
        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;
    }
}
