import { getSkinPath, getSvga } from "../../../utils";
import TimeProgressBar from "../TimeProgressBar";
import { M_SetGameLayerUpdate, 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_JudgeMedalPanel, HOME } from "../../Home";

enum CROP_TYPE {
    NONE = 0,  // 啥也没有
    CHICKEN = 1,
    WHEAT = 2,
    CORN = 3,
    CATTLE = 4,
}

let petData = {
    0: {    // 啥也没有
        key: '',
        name: '',
        type: '',
        pos: [],
        propId: '',
        optionSvga: '',
        option: '',
        catherImg: ''
    },
    1: {    // 鸡
        key: 'chicken',
        name: '鸡',
        type: 'animal',
        pos: [-65, -162],
        propId: 'sp_food_1',
        optionSvga: 'ready_feed',
        option: 'feed',
        catherImg: '鸡蛋'
    },
    2: {    // 小麦
        key: 'wheat',
        name: '小麦',
        type: 'plant',
        pos: [-65, -140],
        propId: 'sp_food_2',
        optionSvga: 'ready_water',
        option: 'water',
        catherImg: '麦粉'
    },
    3: {    // 玉米
        key: 'corn',
        name: '玉米',
        type: 'plant',
        pos: [-65, -140],
        catherPos: [-65, -180],
        propId: 'sp_food_2',
        optionSvga: 'ready_water',
        option: 'water',
        catherImg: '玉米',
    },
    4: {    // 牛
        key: 'cattle',
        name: '牛',
        type: 'animal',
        pos: [-70, -145],
        prop: 'food',
        propId: 'sp_food_1',
        optionSvga: 'ready_feed',
        option: 'feed',
        catherImg: '牛奶',
    },
};

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

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

const CROP_X = 53.5;
const CROP_Y = -18;

/**
 * 作物类
 */
export default class Crop extends eui.Component {
    public group: eui.Group;

    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 = false;

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

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

    public plant(data) {
        M_SetGameLayerUpdate(false);
        loadSvga(getSvga(`${petData[data.petId].key}_plant`)).then(
            (mv: egret.MovieClip) => {
                mv.x = 82;
                mv.y = -40;
                this.addChild(mv);
                mv.addEventListener(egret.Event.COMPLETE, () => {
                    mv.stop();
                    this.removeChild(mv);
                    M_SetGameLayerUpdate(true);
                    M_UpdateLand();
                }, this);
            }
        )
    }

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

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

        this.optionMv && function() {
            egret.Tween.removeTweens(this.optionMv);
            this.group.removeChild(this.optionMv);
            this.optionMv = null;
        }.bind(this)();

        this.progressBar && function() {
            egret.Tween.removeTweens(this.progressBar);
            this.progressBar.destroy();
            MainIns().progressMgr.removeProgress(this.index);
        }.bind(this)();
    }

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

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

        this.addCropSvga().then(() => {
            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.group.removeChild(this.optionMv) && (this.optionMv = null);
            this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.doSpeed, this);
            this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.dOp, this);
            this.touchEnabled = true;
            this.addProgress(this.data.data.feedLeftSeconds);
            if(this.showP) {
                this.showP = false;
                this.progressBar.alpha = 1;
                egret.Tween.removeTweens(this.progressBar);
                egret.Tween.get(this.progressBar).wait(3000).to({alpha: 0}, 200, egret.Ease.quartInOut);
            } else {
                this.progressBar && (this.progressBar.alpha = 0);
            }
            this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.dOp, this);
            return;
        }

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

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

    private doOption(option) {
        switch(option) {
            case OPTION.GATHER:
                M_SetGameLayerUpdate(false);
                NetManager.ins.doHarvest((success) => {
                    if(!success) {
                        M_SetGameLayerUpdate(true);
                        return;
                    }
                    this.cropMv && this.removeChild(this.cropMv) && (this.cropMv = null);
                    let catherImg = new eui.Image(`${petData[this.petId]['catherImg']}_png`);
                    let dy = MainIns().mainUI.height - MainIns().group.height;
                    catherImg.anchorOffsetX = 57 / 2;
                    catherImg.anchorOffsetY = 63 / 2;
                    catherImg.x = MainIns().landMgr.lands[this.index - 1].x + this.x + 100 + 57 / 2;
                    catherImg.y = MainIns().landMgr.lands[this.index - 1].y + this.y - dy / 2 + 20 + 63 / 2;
                    catherImg.scaleX = 0;
                    catherImg.scaleY = 0;
                    MainIns().mainUI.addChild(catherImg);

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

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

                    // 透明度
                    egret.Tween.get(catherImg)
                        .wait(1470 + 160 + 160)
                        .to({alpha: 0}, 30)
                        .call(() => {
                            egret.Tween.removeTweens(catherImg);
                            MainIns().mainUI.removeChild(catherImg);
                            M_SetGameLayerUpdate(true);
                            M_UpdateLand();
                            MainIns().mainUI.warehouseEffect();
                            G_JudgeMedalPanel();    // 检查是否可以弹出勋章
                        });

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

            case OPTION.FEED:
                M_SetGameLayerUpdate(false);
                let feedNum = this.data.data.feedNum;
                let haveNum = G_GetHomeDataByKey(HOME.PROP)[petData[this.petId]['propId']];
                if(feedNum > haveNum) {
                    M_SetGameLayerUpdate(true);
                    let msg = ((petData[this.petId]['propId'] == 'sp_food_1') ? '饲料' : '水壶') + '不够了，快去做任务吧';
                    showToast(msg);
                } else {
                    this.touchEnabled = false;
                    NetManager.ins.doFeed((success) => {
                        if(!success) {
                            let msg = ((petData[this.petId]['propId'] == 'sp_food_1') ? '饲料' : '水壶') + '不够了，快去做任务吧';
                            showToast(msg);
                            M_SetGameLayerUpdate(true);
                            return;
                        }
                        this.optionMv && this.group.removeChild(this.optionMv) && (this.optionMv = null);
                        loadSvga(getSvga(petData[this.petId]['option'])).then(
                            (mv: egret.MovieClip) => {
                                mv.x = petData[this.petId]['type'] == 'animal' ? -30 : 10;
                                mv.y = petData[this.petId]['type'] == 'animal' ? -30 : -120;
                                this.addChild(mv);
                                mv.addEventListener(egret.Event.COMPLETE, () => {
                                    mv.stop();
                                    this.removeChild(mv);
                                    M_SetGameLayerUpdate(true);
                                    this.changeOption(OPTION.NONE);
                                    M_UpdateLand();
                                    G_JudgeMedalPanel();    // 检查是否可以弹出勋章
                                    this.showP = true;  // 可以显示进度条
                                }, this);
                            }
                        );
                    }, this.index);
                }
                break;
            case OPTION.PROGRESS:
                this.showProgress();
                break;
        }
    }

    private showProgress() {
        this.progressBar && (function() {
            egret.Tween.removeTweens(this.progressBar);
            this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.dOp, this);
            this.addSpeed().then(
                () => {
                    egret.Tween.get(this.progressBar)
                        .to({alpha: 1}, 200, egret.Ease.quartInOut)
                        .wait(3000)
                        .call(() => {
                            this.speedMv && this.removeChild(this.speedMv) && (this.speedMv = null);
                        })
                        .to({alpha: 0}, 200, egret.Ease.quartInOut)
                        .call(() => {
                            this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.doSpeed, this);
                            this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.dOp, this);
                        });
                }
            );
        }.bind(this)());
    }

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

    private addSpeed() {
        return new Promise((resolve, reject) => {
            let props = G_GetHomeDataByKey(HOME.PROP);
            if(props['sp_prop_1'] <= 0) {
                resolve();
                return;
            }
            loadSvga(getSvga('ready_speed')).then(
                (mv: egret.MovieClip) => {
                    this.speedMv && this.removeChild(this.speedMv) && (this.speedMv = null);
                    this.speedMv = mv;
                    this.addChild(mv);
                    this.speedMv.x = 80;
                    this.speedMv.y = -85;
                    this.speedMv.touchEnabled = false;
                    this.speedMv.addEventListener(egret.Event.COMPLETE, () => {
                        this.speedMv && this.speedMv.gotoAndPlay(11, 1);
                    }, this);
                    setTimeout(() => {
                        this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.doSpeed, this);
                    }, 700);
                    resolve();
                }
            );
        });
    }

    /**
     * 添加植物的svga
     */
    private addCropSvga() {
        return new Promise(((resolve, reject) => {
            if(!this.changeMv || this.petId == CROP_TYPE.NONE || this.state == CROP_STATE.NONE) {
                resolve();
                return;
            }
            this.cropMv && this.removeChild(this.cropMv) && (this.cropMv = null);
            this.optionMv && this.group.removeChild(this.optionMv) && (this.optionMv = null);
            let upName = '';
            if((petData[this.petId].type == 'plant' && this.state == 3)
                || (petData[this.petId].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 = (petData[this.petId].type == 'animal' ? 4 : 3) : mvId;
            /// TODO 坑爹，1级展示未成熟，2级展示未成熟, 三级展示半成熟，只有可收取才展示成熟
            loadSvga(getSvga(upName)).then(  // 加载升级动画
                (upMv: egret.MovieClip) => {
                    loadSvga(getSvga(`${petData[this.petId].key}${mvId}_birth`)).then(  // 加载出生动画
                        (birthMv: egret.MovieClip) => {
                            upMv.gotoAndPlay(1, 1);
                            upMv.x = (upName == 'up2') ? 0 : 10;
                            upMv.y = (upName == 'up2') ? -35 : 20;
                            this.addChild(upMv);
                            upMv.addEventListener(egret.Event.COMPLETE, () => {
                                this.removeChild(upMv);
                            }, this);

                            this.addChild(birthMv);
                            let pos = (mvId == 3 && this.petId == 3) ? petData[this.petId]['catherPos'] : petData[this.petId]['pos'];
                            birthMv.x = pos[0];
                            birthMv.y = pos[1];
                            birthMv.addEventListener(egret.Event.COMPLETE, () => {
                                birthMv.stop();
                                let name = `${petData[this.petId].key}${mvId}`;
                                loadSvga(getSvga(name)).then(
                                    (mv: egret.MovieClip) => {
                                        this.removeChild(birthMv);
                                        this.addChildAt(mv, 0);
                                        this.cropMv = mv;
                                        this.cropMv.x = pos[0];
                                        this.cropMv.y = pos[1];
                                        this.cropMv.pixelHitTest = true;
                                        resolve();
                                    }
                                );
                            }, this);
                        }
                    );
                }
            );
            this.changeMv = false;
        }));
    }

    /**
     * 添加操作的svga
     * @param name
     */
    private addOption(name) {
        this.optionMv && this.group.removeChild(this.optionMv) && (this.optionMv = null);
        loadSvga(getSvga(name)).then(
            (optionMv: egret.DisplayObject) => {
                this.optionMv = optionMv;
                this.group.addChild(this.optionMv);
                this.optionMv.x = 80;
                this.optionMv.y = -85;
                this.optionMv.touchEnabled = false;
                this.optionMv.addEventListener(egret.Event.COMPLETE, () => {
                    this.optionMv && this.optionMv.gotoAndPlay(11, 1);
                }, this);
            }
        );
    }

    private addProgress(nTime) {
        let label = '';
        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,
            x: this.data.x + 88,
            y: this.data.y + 193,
            title: petData[this.petId].name,
            label: label,
            sTime: 8 * 60 * 60,
            nTime: nTime,
            eTime: 0
        }));
    }

    // 改变状态积
    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.group.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.group.removeChild(this.optionMv) && (this.optionMv = null);
                break;
            case 1: // 鸡

                break;

            case 2: // 小麦

                break;

            case 3:  // 牛

                break;
            case 4: // 玉米

                break;
            default:
                break;
        }
    }
}