import {getSkinPath, getSvga} from "../../../utils";
import TimeProgressBar from "../TimeProgressBar";
import {MainIns} from "../MainScene";
import {loadSvga} from "../../../comm/loadSvga";
import {NetManager} from "../../../../libs/tw/manager/NetManager";
import {showToast} from "../../../comm/UtilsConst";
import {M_HideOption} from "./OptionPanel";
import {M_UpdateLand} from "../LandMgr";
import {G_GetHomeDataByKey, G_UpdateHomeData, HOME} from "../../Home";
import {CROP_TYPE, detectionDiamond, petData} from "../Const";
import Tween = egret.Tween;
import MovieClip = egret.MovieClip;
import Event = egret.Event;
import TouchEvent = egret.TouchEvent;
import Ease = egret.Ease;
import Image = eui.Image;

enum CROP_STATE {
    NONE = 0,  // 啥也没有
    LEVEL1 = 1,
    LEVEL2 = 2,
    LEVEL3 = 3,   // 植物成熟
    LEVEL4 = 4,   // 动物成熟
}

enum OPTION {
    NONE = 0,
    GATHER = 1,
    FEED = 2,
    PROGRESS = 3
}


/**
 * 作物类
 */
export default class Crop extends eui.Component {
    private progressBar: TimeProgressBar;

    private data = null;

    private petId: CROP_TYPE;
    private state: CROP_STATE;
    private option: OPTION;

    private index;

    private optionMv;
    private cropMv;
    private changeMv: boolean = false;
    private speedMv;

    private lastG = false;
    private showP = true;

    constructor(data?) {
        super();
        this.skinName = getSkinPath('Objs/Crop');
        this.data = data || null;
        this.index = this.data.index;
        this.changePetId(CROP_TYPE.NONE);
        this.changeState(CROP_STATE.NONE);
        this.initUI();

    }

    private reset() {
        this.progressBar && Tween.removeTweens(this.progressBar);
        MainIns().progressMgr.removeProgress(this.data.index);
        this.progressBar = null;
        this.speedMv && this.removeChild(this.speedMv) && (this.speedMv = null);
    }

    public touchEnable(enable) {
        this.parent.touchEnabled = enable;
        this.parent.touchChildren = enable;
    }

    public async plant(data) {
        this.touchEnable(false);
        const plantMv = await loadSvga(getSvga(`${petData[data.petId].key}_plant`));
        if (data.petId == CROP_TYPE.POTATO || data.petId == CROP_TYPE.WALNUT) {
            plantMv.x = -40;
            plantMv.y = -135;
        } else {
            plantMv.x = 130;
            plantMv.y = -40;
        }

        this.addChild(plantMv);
        plantMv.addEventListener(Event.COMPLETE, () => {
            plantMv.stop();
            this.removeChild(plantMv);
            this.touchEnable(true);
            M_UpdateLand(this.index);
        }, this);
    }

    public updateDate(data) {
        this.data = data;
        this.reset();
        this.initUI();
    }

    public destroy() {
        this.cropMv && (() => {
            Tween.removeTweens(this.cropMv);
            this.removeChild(this.cropMv);
            this.cropMv = null;
        })();

        this.optionMv && (() => {
            Tween.removeTweens(this.optionMv);
            this.removeChild(this.optionMv);
            this.optionMv = null;
        })();

        this.progressBar && (() => {
            Tween.removeTweens(this.progressBar);
            this.progressBar.destroy();
            MainIns().progressMgr.removeProgress(this.index);
        })();
    }

    private async initUI() {
        let {petId, level, canFeed, canGather} = this.data.data;
        this.changePetId(petId || 0);
        this.changeState(level || 0);

        if (!this.lastG && canGather) {
            this.changeMv = true;
        }
        this.lastG = canGather;

        await this.addCropSvga();
        if (this.petId != CROP_TYPE.NONE) {
            if (canGather) {
                this.changeOption(OPTION.GATHER);
            } else if (canFeed) {
                this.changeOption(OPTION.FEED);
            } else if (!canGather && !canFeed) {
                this.changeOption(OPTION.PROGRESS);
            }
        } else {
            this.changeOption(OPTION.NONE);
        }
    }

    private changeOption(option: OPTION) {
        if (option == OPTION.PROGRESS) { // 进度条单独处理
            this.option = option;
            this.optionMv && this.removeChild(this.optionMv) && (this.optionMv = null);
            this.removeEventListener(TouchEvent.TOUCH_TAP, this.doSpeed, this);
            this.removeEventListener(TouchEvent.TOUCH_TAP, this.dOp, this);
            this.touchEnabled = true;
            this.touchChildren = true;
            this.addProgress(this.data.data.feedLeftSeconds);
            this.addEventListener(TouchEvent.TOUCH_TAP, this.dOp, this);
            this.optionMv && this.optionMv.addEventListener(TouchEvent.TOUCH_TAP, this.dOp, this);
            return;
        }else {
            MainIns() && (MainIns().progressMgr.removeProgress(this.index));
        }

        if (this.option === option) {
            return;
        }
        this.option = option;
        this.optionMv && this.optionMv.removeEventListener(TouchEvent.TOUCH_TAP, this.dOp, this);
        this.optionMv && this.removeChild(this.optionMv) && (this.optionMv = null);
        this.removeEventListener(TouchEvent.TOUCH_TAP, this.doSpeed, this);
        this.removeEventListener(TouchEvent.TOUCH_TAP, this.dOp, this);

        switch (this.option) {
            case OPTION.GATHER:
                this.touchEnabled = true;
                this.touchChildren = true;
                this.addOption('ready_get');
                break;
            case OPTION.FEED:
                this.touchEnabled = true;
                this.touchChildren = true;
                this.addOption(petData[this.petId].optionSvga);
                break;
            case OPTION.NONE:
                this.touchChildren = false;
                this.touchEnabled = false;
                this.lastG = false;
                break;
        }
        this.addEventListener(TouchEvent.TOUCH_TAP, this.dOp, this);
        this.optionMv && this.optionMv.addEventListener(TouchEvent.TOUCH_TAP, this.dOp, this);

    }

    private dOp(e) {
        /* TODO ios14像素点击不能用 手动检测菱形包围盒 */
        if (!detectionDiamond(e.localX, e.localY, this.width, this.height)) return;
        /* TODO ios14像素点击不能用 手动检测菱形包围盒 */

        M_HideOption();  // 隐藏操作面板
        this.doOption(this.option);
    }

    private doOption(option) {
        switch (option) {
            case OPTION.GATHER:
                this.touchEnable(false);
                NetManager.ins.doHarvest((success) => {
                    if (!success) {
                        this.touchEnable(true);
                        return;
                    }
                    this.cropMv && this.removeChild(this.cropMv) && (this.cropMv = null);

                    const catherImg = new Image(`${petData[this.petId].catherImg}_png`);
                    const dy = MainIns().mainUI.height - MainIns().group.height;

                    catherImg.anchorOffsetX = 57 / 2;
                    catherImg.anchorOffsetY = 63 / 2;

                    const cx = MainIns().landMgr.lands[this.index - 1].x + this.width / 2;
                    const cy = MainIns().landMgr.lands[this.index - 1].y - 30 - dy / 2 + this.height / 2;
                    catherImg.x = cx;
                    catherImg.y = cy;
                    catherImg.scaleX = 0;
                    catherImg.scaleY = 0;
                    MainIns().mainUI.addChild(catherImg);

                    // 移动
                    const _x = MainIns().mainUI.warehouseBtn.x;
                    const _y = MainIns().mainUI.warehouseBtn.y;
                    Tween.get(catherImg)
                        .to({y: cy - 10}, 170)
                        .to({y: cy + 10}, 160, Ease.quadInOut)
                        .to({y: cy - 10}, 160, Ease.quadInOut)
                        .to({y: cy + 10}, 160, Ease.quadInOut)
                        .wait(500)
                        .to({x: _x, y: _y}, 680);

                    // 缩放
                    Tween.get(catherImg)
                        .to({scaleX: 1, scaleY: 1}, 170)
                        .wait(820)
                        .to({scaleX: 0.8, scaleY: 1.2}, 500)
                        .to({x: 0.8, y: 0.8}, 330);

                    // 透明度
                    Tween.get(catherImg)
                        .wait(1790)
                        .to({alpha: 0}, 30)
                        .call(() => {
                            Tween.removeTweens(catherImg);
                            MainIns().mainUI.removeChild(catherImg);
                            this.touchEnable(true);
                            M_UpdateLand(this.index);
                            MainIns().mainUI.warehouseEffect();

                            G_UpdateHomeData();
                            // Tools.judgeMedalPanel();    // 检查是否可以弹出勋章 TODO 2020.12.26 这期成就只有种植，先去掉

                        });

                    this.changePetId(CROP_TYPE.NONE);
                    this.changeState(CROP_STATE.NONE);
                    this.changeOption(OPTION.NONE);
                }, this.index);
                break;

            case OPTION.FEED:
                this.touchEnable(false);
                let feedNum = this.data.data.feedNum;
                let haveNum = G_GetHomeDataByKey(HOME.PROP)[petData[this.petId]['propId']];
                if (feedNum > haveNum) {
                    this.touchEnable(true);
                    let msg = ((petData[this.petId]['propId'] == 'sp_food_1') ? '饲料' : '水壶') + '不够了，快去做任务吧';
                    showToast(msg);
                } else {
                    this.touchEnabled = false;
                    NetManager.ins.doFeed(async (success) => {
                        if (!success) {
                            let msg = ((petData[this.petId]['propId'] == 'sp_food_1') ? '饲料' : '水壶') + '不够了，快去做任务吧';
                            showToast(msg);
                            this.touchEnable(true);
                            return;
                        }
                        this.optionMv && this.removeChild(this.optionMv) && (this.optionMv = null);
                        const optionMv = await loadSvga(getSvga(petData[this.petId].option));
                        optionMv.x = petData[this.petId].type == 'animal' ? 10 : 58;
                        optionMv.y = petData[this.petId].type == 'animal' ? 0 : -120;
                        this.addChild(optionMv);
                        optionMv.addEventListener(Event.COMPLETE, () => {
                            optionMv.stop();
                            this.removeChild(optionMv);
                            this.touchEnable(true);
                            this.changeOption(OPTION.NONE);
                            M_UpdateLand(this.index);

                            G_UpdateHomeData();
                            // Tools.judgeMedalPanel();    // 检查是否可以弹出勋章 TODO 2020.12.26 这期成就只有种植，先去掉

                            this.showP = true;  // 可以显示进度条
                        }, this);
                    }, this.index);
                }
                break;
            case OPTION.PROGRESS:
                this.showProgress();
                break;
        }
    }

    private async showProgress() {
        if (this.progressBar) {
            Tween.removeTweens(this.progressBar);
            this.removeEventListener(TouchEvent.TOUCH_TAP, this.dOp, this);
            await this.addSpeed();
            Tween.get(this.progressBar)
                .wait(3000)
                .call(() => {
                    this.speedMv && this.removeChild(this.speedMv) && (this.speedMv = null);
                    this.touchEnabled = true;
                    this.touchChildren = true;
                    this.addEventListener(TouchEvent.TOUCH_TAP, this.dOp, this);
                });
        }
    }

    private doSpeed() {
        console.log('加速');
        NetManager.ins.useProp((success) => {
            if (!success) {
                return;
            }
            this.touchEnabled = false;
            this.touchChildren = false;
            this.touchEnable(false);
            Tween.removeTweens(this.progressBar);
            this.speedMv && this.removeChild(this.speedMv) && (this.speedMv = null);
            // this.speedMv.removeEventListener( TouchEvent.TOUCH_TAP, this.doSpeed, this);
            this.progressBar.alpha = 1;
            this.progressBar.addSpeed(() => {
                this.touchEnable(true);
                M_UpdateLand(this.index);

                G_UpdateHomeData();
                // Tools.judgeMedalPanel();    // 检查是否可以弹出勋章 TODO 2020.12.26 这期成就只有种植，先去掉

            });
        }, 'sp_prop_1', this.index);
    }

    private async addSpeed() {
        let props = G_GetHomeDataByKey(HOME.PROP);
        if (props.sp_prop_1 <= 0) {
            return;
        }
        const speedMv = await loadSvga(getSvga('ready_speed'));
        this.speedMv && this.removeChild(this.speedMv) && (this.speedMv = null);
        this.speedMv = speedMv;
        this.addChild(speedMv);
        speedMv.x = 122;
        speedMv.y = -70;
        // this.speedMv.touchEnabled = false;
        speedMv.addEventListener(Event.COMPLETE, () => {
            this.speedMv && this.speedMv.gotoAndPlay(11, 1);
        }, this);
        setTimeout(() => {
            this.touchEnabled = true;
            this.touchChildren = true;
            speedMv.touchEnabled = true;
            this.speedMv.touchChildren = false;
            speedMv.addEventListener(TouchEvent.TOUCH_TAP, this.doSpeed, this);
        }, 600);

        return;
    }

    /**
     * 添加植物的svga
     */
    private async addCropSvga() {
        if (!this.changeMv || this.petId == CROP_TYPE.NONE || this.state == CROP_STATE.NONE) {
            return;
        }
        this.cropMv && this.removeChild(this.cropMv) && (this.cropMv = null);
        this.optionMv && this.removeChild(this.optionMv) && (this.optionMv = null);
        let upName = '';
        const petD: any = petData[this.petId];
        if ((petD.type == 'plant' && this.state == 3)
            || (petD.type == 'animal' && this.state == 4)
            || this.data.data.canGather) {
            upName = 'up2';
        } else {
            upName = 'up1';
        }
        /// TODO 坑爹，1级展示未成熟，2级展示未成熟, 三级展示半成熟，只有可收取才展示成熟
        let mvId = (this.state == 1) ? this.state : this.state - 1;
        // console.log(this.data.data.canGather);
        (this.data.data.canGather) ? mvId = (petD.type == 'animal' ? 4 : 3) : mvId;
        /// TODO 坑爹，1级展示未成熟，2级展示未成熟, 三级展示半成熟，只有可收取才展示成熟

        this.changeMv = false;

        // 加载升级动画
        const upMv: MovieClip = await loadSvga(getSvga(upName));

        // 加载出生动画
        const birthMv: MovieClip = await loadSvga(getSvga(`${petD.key}${mvId}_birth`));

        // 加载动画
        const cropMv = await loadSvga(getSvga(`${petD.key}${mvId}`));

        upMv.x = 55;
        upMv.y = (upName == 'up2') ? -35 : 35;
        upMv.gotoAndPlay(1, 1);
        this.addChild(upMv);
        upMv.addEventListener(Event.COMPLETE, () => {
            this.removeChild(upMv);
        }, this);

        this.addChild(birthMv);
        const pos = (mvId == 3 && this.petId == 3) ? petD.catherPos : petD.pos;
        birthMv.x = pos[0];
        birthMv.y = pos[1];

        return new Promise((resolve) => {
            birthMv.addEventListener(Event.COMPLETE, async () => {
                birthMv.stop();
                this.removeChild(birthMv);
                this.addChildAt(cropMv, 0);
                this.cropMv = cropMv;
                cropMv.x = pos[0];
                cropMv.y = pos[1];
                resolve();
            }, this);
        });

    }

    /**
     * 添加操作的svga
     * @param name
     */
    private async addOption(name) {
        this.optionMv && this.removeChild(this.optionMv) && (this.optionMv = null);
        const optionMv = await loadSvga(getSvga(name));
        this.optionMv = optionMv;
        this.addChild(optionMv);
        optionMv.x = 122;
        optionMv.y = -85;
        optionMv.touchEnabled = true;
        optionMv.addEventListener(Event.COMPLETE, () => {
            this.optionMv && this.optionMv.gotoAndPlay(11, 1);
        }, this);
    }

    private addProgress(nTime) {
        let label: string;
        if (petData[this.petId].type == 'animal') {
            label = (this.state == 4) ? '收获' : '喂食';
        } else {
            label = (this.state == 3) ? '收获' : '浇水';
        }
        MainIns() && (this.progressBar = MainIns().progressMgr.addProgress({
            index: this.data.index,
            title: petData[this.petId].name,
            label: label,
            sTime: 8 * 60 * 60,
            nTime: nTime,
            eTime: 0
        }));

        // this.parent.addChild(this.progressBar);

        this.progressBar.x = this.data.x + 90;
        this.progressBar.y = this.data.y + 90;
    }

    // 改变状态积
    private changeState(state: CROP_STATE) {
        if (state == this.state) {
            return;
        }
        this.changeMv = true;
        this.state = state; // 设置状态

        /// TODO 定义详细的状态积
        switch (this.state) {
            case CROP_STATE.NONE:   // 啥也没有
                this.cropMv && this.removeChild(this.cropMv) && (this.cropMv = null);
                this.optionMv && this.removeChild(this.optionMv) && (this.optionMv = null);
                break;
            case CROP_STATE.LEVEL1: // 刚种

                break;
            case CROP_STATE.LEVEL2:  // 半成熟

                break;
            case CROP_STATE.LEVEL3: // 植物成熟

                break;
            case CROP_STATE.LEVEL4: // 动物成熟

                break;
            default:
                break;
        }
    }

    // 改变类型
    private changePetId(petId: CROP_TYPE) {
        if (petId == this.petId) {
            return;
        }
        this.changeMv = true;
        this.petId = petId; // 设置Id

        /// TODO 定义详细类型积
        switch (petId) {
            case 0:   // 啥也没有
                this.cropMv && this.removeChild(this.cropMv) && (this.cropMv = null);
                this.optionMv && this.removeChild(this.optionMv) && (this.optionMv = null);
                break;
            case 1: // 鸡

                break;

            case 2: // 水稻

                break;

            case 3:  // 牛

                break;
            case 4: // 玉米

                break;
            default:
                break;
        }
    }
}
