import wait from "../../libs/new_tc/wait";
import Scene from "../../libs/new_wx/components/Scene";
import PanelCtrl from "../../libs/new_wx/ctrls/panelCtrl";
import { ModuleTypes } from "../../libs/new_wx/types/sceneTypes";
import { IElementData } from "../../libs/tw/data/custom/ajaxElement/IElementData";
import { DataManager } from "../../libs/tw/manager/DataManager";
import { NetManager } from "../../libs/tw/manager/NetManager";
import { showToast } from "../../libs/new_wx/ctrls/toastCtrl";
import Loading from "../../libs/new_wx/components/Loading";
import { Buried } from "../../libs/tw/util/Buried";

export default class StartScene extends Scene {
    ruleBtn: eui.Button;
    rewardBtn: eui.Button;
    optionBtn: eui.Button;
    startBtn: eui.Button;
    inviteBtn: eui.Button;
    elements: eui.Group;
    guide: eui.Image;
    hand: eui.Image;
    guideTag = false;
    private freeLimit: number;
    private _isLightWord = false;

    async start(d?) {
        this.showlog();
        this['bgimg'].source = 'https://yun.duiba.com.cn/db_games/startscenebg2.png';
        const { data } = DataManager.ins.getData('yyh_baseInfo');
        const { element } = DataManager.ins.ajaxElementData;
        this.freeLimit = element.freeLimit;
        const getRemainingTimes = DataManager.ins.getData('getRemainingTimes');
        this.freeLimit = getRemainingTimes.data;
        this.updateCountTxt();

        if (this.freeLimit <= 0) {
            NetManager.ins.showLog(getlogItem(4));//邀请
        } else {
            NetManager.ins.showLog(getlogItem(1));//浇水
        }

        super.start();
        this.initProgress();
        this.initTree(data.wateringTimes);
        this.setProgress(data.wateringTimes);
        this.showWord(data.isLightWord);
        this._isLightWord = data.isLightWord;
        //引导
        const { actId } = DataManager.ins.customCfgData;
        // if (localStorage.getItem(actId + 'guide')) {
        if (localStorage.getItem(actId + 'guide') || data.wateringTimes > 0) {
            this.guide.visible = false;
            this.hand.visible = false;
            this['tips'].visible = false;
        } else {
            this.guideTag = true;
            localStorage.setItem(actId + 'guide', '1');
            this['tips'].alpha = 0;
            this['hand'].alpha = 0;
            egret.Tween.get(this.guide).set({ scaleX: 10, scaleY: 10, alpha: 1 }).to({ scaleX: 1, scaleY: 1 }, 300, egret.Ease.sineIn).call(() => {
                egret.Tween.get(this['tips']).to({ alpha: 1, y: this['tips'].y + 20 }, 300);
                egret.Tween.get(this['hand'], { loop: true }).set({ alpha: 1, scaleX: 1, scaleY: 1 })
                    .to({ scaleX: .8, scaleY: .8 }, 300)
                    .to({ scaleX: 1, scaleY: 1 }, 300).wait(700);
            });
        }
        this.setTips(data.wateringTimes, data.isLightWord);
        this.initGiftGroup(data.remainGiftsNum);
        if (data.remainGiftsNum > 0)
            NetManager.ins.showLog(getlogItem(2));

        this.initShake();
        NetManager.ins.yyh_recentlyGetJoinTimes(() => {
            const { data } = DataManager.ins.getData('yyh_recentlyGetJoinTimes');
            if (data) showToast('恭喜你获得浇水次数，快来浇水吧')
        });


    }

    setTips(num, isLightWord) {
        if (num > 5) num = 5;
        this['rewardTipsTxt'].text = '浇水1次即可收获幼苗'
        if (num == 1) {
            this['rewardTipsTxt'].text = '再浇水4次即可点亮为字';
        }
        if (num == 2) {
            this['rewardTipsTxt'].text = '再浇水3次即可点亮为字'
        }
        if (num == 3) {
            this['rewardTipsTxt'].text = '再浇水2次即可点亮为字'
        }
        if (num == 4) {
            this['rewardTipsTxt'].text = '再浇水1次即可点亮为字'
        }
        if (num == 5) {
            this['rewardTipsTxt'].text = '巨树次日会变成小树，今日再浇水还能继续拿3个礼物哦'
        }
        if (isLightWord) {
            this['rewardTipsTxt'].text = '浇水3次即可获得1个礼物'
            if (num == 1) {
                this['rewardTipsTxt'].text = '再浇水2次即可获得1个礼物';
            }
            if (num == 2) {
                this['rewardTipsTxt'].text = '再浇水1次即可获得1个礼物'
            }
            if (num == 3) {
                this['rewardTipsTxt'].text = '再浇水1次即可获得2个礼物'
            }
            if (num == 4) {
                this['rewardTipsTxt'].text = '再浇水1次即可获得3个礼物'
            }
            if (num == 5) {
                this['rewardTipsTxt'].text = '巨树次日会变成小树，今日再浇水还能继续拿3个礼物哦'
            }
        }
    }

    initProgress() {
        this['progressfront'].mask = this['progressfrontmask'];
    }

    lightShowbox0(light = true) {
        this['box00'].visible = !light;
        this['box01'].visible = light;
    }
    lightShowbox1(light = true) {
        this['box10'].visible = !light;
        this['box11'].visible = light;
    }
    lightShowbox2(light = true) {
        this['box20'].visible = !light;
        this['box21'].visible = light;
    }
    setProgress(num) {
        if (num > 5) num = 5;
        this.lightShowbox0(false);
        this.lightShowbox1(false);
        this.lightShowbox2(false);
        if (num == 0)
            this['progressfrontmask'].scaleY = 0;
        if (num == 1) {
            this['progressfrontmask'].scaleY = 0.22;
        }
        if (num == 2) {
            this['progressfrontmask'].scaleY = 0.42;
        }
        if (num == 3) {
            this['progressfrontmask'].scaleY = 0.62;
        }
        if (num == 4) {
            this['progressfrontmask'].scaleY = 0.805;
        }
        if (num == 5) {
            this['progressfrontmask'].scaleY = 1;
        }
        if (num >= 3) this.lightShowbox2(true);
        if (num >= 4) this.lightShowbox1(true);
        if (num >= 5) this.lightShowbox0(true);
    }

    playJiaoshui() {
        return new Promise((r) => {
            this['shuihu1'].alpha = 1;
            egret.Tween.get(this['shuihu1']).set({ rotation: 25.43 }).to({ rotation: 0 }, 300).call(async () => {
                const interval = 1000 / 10;
                egret.Tween.get(this['jiaoshuiani2'], { loop: true }).set({ alpha: 1 }).wait(interval).to({ alpha: 0 }).wait(interval);
                egret.Tween.get(this['jiaoshuiani1'], { loop: true }).set({ alpha: 0 }).wait(interval).to({ alpha: 1 }).wait(interval);
                await wait(500);
                egret.Tween.removeTweens(this['jiaoshuiani2']);
                egret.Tween.removeTweens(this['jiaoshuiani1']);
                this['jiaoshuiani2'].alpha = 0;
                this['jiaoshuiani1'].alpha = 0;
                egret.Tween.get(this['shuihu1']).to({ rotation: 25.43 }, 200).to({ alpha: 0 }, 200).call(r);
            });
        });
    }

    updateCountTxt() {
        if (this.freeLimit < 0)
            this.freeLimit = 0;
        this.startBtn.labelDisplay.text = '点击浇水x' + this.freeLimit;
        this.inviteBtn.visible = this.freeLimit <= 0;
        this.startBtn.visible = this.freeLimit > 0;
    }

    initEvents() {
        if (this.ruleBtn)
            this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
        if (this.rewardBtn)
            this.rewardBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_rewardBtn, this);
        if (this.startBtn)
            this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn, this);
        if (this.inviteBtn)
            this.inviteBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_invitBtn, this);
        this['giftbtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_giftbtn, this);
    }

    onTap_giftbtn() {
        NetManager.ins.clickLog(getlogItem(2));
        this['giftbtn'].enabled = false;
        Loading.instace.show();
        NetManager.ins.yyh_receivingGifts((success) => {
            Loading.instace.hide();
            this['giftbtn'].enabled = true;
            if (success) {
                const { data } = DataManager.ins.getData('yyh_receivingGifts');
                this.updateGiftGroup(data.remainGiftsNum)
                this['giftbtn'].enabled = false;
                Loading.instace.show();
                const receivingDetailList = data.receivingDetailList.filter(item => item.type != 7);
                if (receivingDetailList.length == 1) {
                    const type = receivingDetailList[0].type;// 发奖类型：123, "能量礼物" 456优惠券
                    let func: any, netname, app;
                    if (type == 1 || type == 2 || type == 3) {
                        func = NetManager.ins.getPlugOrderStatus1;
                        netname = 'getPlugOrderStatus1';
                        app = 'Prize2';
                    }
                    else {
                        func = NetManager.ins.getPlugOrderStatus2;
                        netname = 'getPlugOrderStatus2';
                        app = 'Prize1';
                    };
                    //callback: Function, orderId: number, pollingCheck: Function, pollingCount = 5, prizeLevel?: number
                    func.bind(NetManager.ins)((success) => {
                        Loading.instace.hide();
                        this['giftbtn'].enabled = true;
                        const lottery = DataManager.ins.getData(netname).lottery;
                        if (success && lottery && lottery.type != 'thanks') {
                            PanelCtrl.instance.show(app)
                        } else {
                            PanelCtrl.instance.show(ModuleTypes.NO_PRIZE_PANEL)
                        }
                    }, receivingDetailList[0].orderNum, () => DataManager.ins.getData(netname).result == 0)
                } else if (receivingDetailList.length == 2) {
                    this.getOrderStatus(receivingDetailList);
                } else {

                }
            }
        });
    }

    private getOrderStatus(receivingDetailList) {
        let result1, result2;
        if (receivingDetailList[0].type == 1 || receivingDetailList[0].type == 2 || receivingDetailList[0].type == 3) { //result123是能量,result456是券
            result1 = receivingDetailList[0];
            result2 = receivingDetailList[1];
        } else {
            result1 = receivingDetailList[1];
            result2 = receivingDetailList[0];
        }
        let count = 2;
        let success1, success2;
        const check = () => {
            if (count <= 0) {
                Loading.instace.hide();
                this['giftbtn'].enabled = true;
                const lottery1 = DataManager.ins.getData('getPlugOrderStatus1').lottery;
                const lottery2 = DataManager.ins.getData('getPlugOrderStatus2').lottery;
                const haslottery1 = success1 && lottery1 && lottery1.type != 'thanks';
                const haslottery2 = success2 && lottery2 && lottery2.type != 'thanks';
                if (haslottery1 && haslottery2) {//都有
                    PanelCtrl.instance.show('Prize3')
                } else if (haslottery1 && !haslottery2) {//只有能量
                    PanelCtrl.instance.show('Prize2')
                } else if (!haslottery1 && haslottery2) {//只有券
                    PanelCtrl.instance.show('Prize1')
                } else {
                    PanelCtrl.instance.show(ModuleTypes.NO_PRIZE_PANEL)
                }
            }
        };
        NetManager.ins.getPlugOrderStatus1((success) => {
            success1 = success;
            count--;
            check();
        }, result1.orderNum, () => DataManager.ins.getData('getPlugOrderStatus1').result == 0);
        NetManager.ins.getPlugOrderStatus2((success) => {
            success2 = success;
            count--;
            check();
        }, result2.orderNum, () => DataManager.ins.getData('getPlugOrderStatus2').result == 0);
    }

    onTap_ruleBtn(e: egret.Event) {
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
    }

    onTap_invitBtn(e: egret.Event) {
        console.log('onTap_invitBtn');
        this.inviteBtn.enabled = false;
        NetManager.ins.clickLog(getlogItem(4));
        setTimeout(() => {
            this.inviteBtn.enabled = true;
            PanelCtrl.instance.show('shareAlert')
        }, 2000);
        try {
            const { data } = DataManager.ins.getData('getUserShareCode');
            window['AlipayJSBridge'].call(
                'esportsShare',
                {
                    title: window['shareTitle'],
                    content: window['shareContent'],
                    imgUrl: window['shareImg'],  //'http://yun.duiba.com.cn/duibaManagerWeb/fgzpqk6zzo.png',
                    url: window['shareUrl'] + `?shareCode=${data}&activityId=${CFG.actId}`,//'http://activity.m.duiba.com.cn/customShare/share?id=3327',
                    type: '3'
                }
            );
        } catch (error) {
            console.warn(error)
        }
    }

    onTap_rewardBtn(e: egret.Event) {
        PanelCtrl.instance.show('rewardPanel')
    }

    async onTap_startBtn(e?: egret.Event) {
        NetManager.ins.clickLog(getlogItem(1));
        this.startBtn.enabled = false;
        if (this.guideTag) {
            this.hand.visible = false;
            this['tips'].visible = false;
            egret.Tween.get(this.guide).to({ scaleX: 10, scaleY: 10 }, 300).call(() => {
                this.guide.visible = false;
                this.dostart();
            });
        } else {
            this.dostart();
        }
    }

    async playProgressAni(num) {
        if (num > 5) num = 5;
        return new Promise((r) => {
            let target;
            if (num == 1)
                target = 0.22;
            if (num == 2)
                target = 0.42;
            if (num == 3)
                target = 0.62;
            if (num == 4)
                target = 0.805;
            if (num == 5)
                target = 1;
            egret.Tween.get(this['progressfrontmask']).to({ scaleY: target }, 500).call(() => {
                if (num >= 3) {
                    this.lightShowbox2(true);
                }
                if (num >= 4) {
                    this.lightShowbox1(true);
                }
                if (num >= 5) {
                    this.lightShowbox0(true);
                }
                r();
            });
        })
    }

    initTree(num) { //初始是0
        if (num > 5) num = 5;
        this['tree1'].visible = this['tree2'].visible = this['tree3'].visible = this['tree4'].visible = this['tree5'].visible = this['tree6'].visible = false;
        this['tree' + (num + 1)].visible = true;
    }

    playTreeAni(num) {//初始是0
        if (num > 5) num = 5;
        const d1 = this['tree' + (num)];
        const d2 = this['tree' + (num + 1)];
        egret.Tween.get(d1).to({ scaleX: 0, scaleY: 0 }, 300).call(() => {
            d2.visible = true;
            d2.scaleX = 0;
            d2.scaleY = 0;
            egret.Tween.get(d2).set({ scaleX: 0, scaleY: 0 }).to({ scaleX: 1, scaleY: 1 }, 300).call(() => {

            })
        })
    }

    initGiftGroup(remainGiftsNum: number) {
        this['giftTipsTxt'].text = `获得${remainGiftsNum}份礼物\n点击打开`;
        if (remainGiftsNum > 0) {
            this['giftGroup'].x = 547;
        } else {
            this['giftGroup'].x = 847;
        }
    }

    updateGiftGroup(remainGiftsNum: number) {
        this['giftTipsTxt'].text = `获得${remainGiftsNum}份礼物\n点击打开`;
        if (remainGiftsNum > 0) {
            egret.Tween.get(this['giftGroup']).to({ x: 547 }, 300).call(() => { });
        } else {
            egret.Tween.get(this['giftGroup']).to({ x: 847 }, 300).call(() => { });
        }
    }

    initShake() {
        const stren = 10;
        const freq = 1000 / 30;
        egret.Tween.get(this['giftbtn'], { loop: true })
            .to({ rotation: stren }, freq)
            .to({ rotation: 0 }, freq)
            .to({ rotation: -stren }, freq)
            .to({ rotation: 0 }, freq)
            .to({ rotation: stren }, freq)
            .to({ rotation: 0 }, freq)
            .to({ rotation: -stren }, freq)
            .to({ rotation: 0 }, freq)
            .wait(1000)
    }

    async dostart() {
        NetManager.ins.yyh_doJoin(async (success) => {
            if (success) {
                const { data } = DataManager.ins.getData('yyh_doJoin');
                this.freeLimit--;
                this.updateCountTxt();
                if (this.freeLimit <= 0) {
                    NetManager.ins.showLog(getlogItem(4));//邀请
                }
                await this.playJiaoshui();
                await this.playProgressAni(data.wateringTimes);
                this.showWord(data.isLightWord);
                this.playTreeAni(data.wateringTimes);
                this.setTips(data.wateringTimes, data.isLightWord);
                this.startBtn.enabled = true;
                this.updateGiftGroup(data.remainGiftsNum);
                if (data.remainGiftsNum > 0)
                     NetManager.ins.showLog(getlogItem(2));
                if (data.presentGiftsNum > 0) showToast('恭喜你获得礼物，赶紧打开看看吧');
                if (data.wateringTimes == 5)
                    if (data.isLightWord == this._isLightWord) {//已经是第二天了
                        PanelCtrl.instance.show('Alert2');
                    } else {
                        PanelCtrl.instance.show('Alert1');
                    }
                this._isLightWord = data.isLightWord;
            } else {
                this.startBtn.enabled = true;
            }
        });
    }

    showWord(show = false) {
        this['wordNotGot'].visible = !show;
        this['wordGot'].visible = show;
    }

    onTap_rankBtn(e: egret.Event) {
        PanelCtrl.instance.show(ModuleTypes.RANK_PANEL);
    }

    get skinKey() { return 'Start' }

    showlog() {


        NetManager.ins.showLog(getlogItem(3));

    }


}

export const getlogItem = (i) => {
    const Dpm = Buried.connectDpm(110, i, 1); // 点击埋点
    const Dcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
    return Buried.createExposure(Dpm, Dcm);
}