import { NetManager } from '../../libs/tw/manager/NetManager';
import { DataManager } from '../../libs/tw/manager/DataManager';
import Scene from "../views/Scene";
import layers from "../../src/views/layers";
import GameConst from '../GameConst';
import PanelCtrl from '../ctrls/panelCtrl';
import SceneCtrl from '../ctrls/sceneCtrl';
import { ModuleTypes } from '../types/sceneTypes';
import Waiting from '../waiting/Waiting';

import { Buried } from './../../libs/tw/util/Buried';

export default class PigVipLevelScene extends Scene {

    get skinKey() { return 'PigVipLevel' }

    public bg: eui.Image;
    public dark: eui.Rect;
    public panelBg: eui.Image;
    public maskPic: eui.Image;
    public title: eui.Image;
    public reChooseBtn: eui.Button;
    public chooseBtn: eui.Button;
    public warnTips: eui.Image;
    public giftTips: eui.Label;
    public vipTxt: eui.Label;
    public vip: eui.Image;
    public pigMask: eui.Rect;
    public pigList: eui.Component;
    public point: eui.Image;
    public toast: eui.Image;


    private pigTheme: string;
    private userLevel: number;
    private scene: any;
    private currChooseLevel: string = 'Lv1';
    private optional_vip1: boolean = true;
    private optional_vip2: boolean = false;
    private optional_vip3: boolean = false;

    private exposures;

    start(data) {
        this.pigList.mask = this.pigMask;
        this.pigTheme = data.pigTheme;
        console.log(data.pigTheme)

        this.percentWidth = 100;
        this.percentHeight = 100;

        this.updatePigs();

        this.initBuired();
    }

    initBuired() {

        this.exposures = {};
        var dpmReChoose = Buried.connectDpm(40, 3, 1);
        var dpmChoose = Buried.connectDpm(40, 3, 2);
        var num;
        switch (this.pigTheme) {
            case "wastonA":
                num = 1;
                break;
            case "wastonB":
                num = 2;
                break;
            case "wastonC":
                num = 3;
                break;
        }
        var dcm = Buried.connectDcm(230, window['skinID'], num);

        this.exposures["reChoose"] = Buried.createExposure(dpmReChoose, dcm);
        this.exposures["choose"] = Buried.createExposure(dpmChoose, dcm);

        //发送曝光埋点
        NetManager.ins.showLog(this.exposures["reChoose"]);
        NetManager.ins.showLog(this.exposures["choose"]);
    }

    updatePigs() {
        // 更新等级
        // let vip = GameConst.getCookie('vip');
        // let vip = GameConst.getCookie('dcustom');

        var str = GameConst.getCookie('dcustom') + "";
        var strs = str.split("&")
        var aaa = "null";
        for (var i = 0; i < strs.length; i++) {
            if (strs[i].indexOf("vip") >= 0) {
                aaa = strs[i]
            }
        }
        let vip = aaa.replace(/[^0-9]/ig, "");
        if (vip) {
            // let vipL = vip.split('').length;
            // if (vipL == 4) {
            //     this.userLevel = 1;
            // } else if (vipL == 5) {
            //     this.userLevel = 2;
            // } else if (vipL == 6) {
            //     this.userLevel = 3;
            // }
            switch (parseInt(vip)) {
                case 4:
                    this.userLevel = 1
                    break
                case 8:
                    this.userLevel = 2
                    break
                case 7:
                    this.userLevel = 3
                    break
                default:
                    this.userLevel = 1
                    break
            }
        } else {
            this.userLevel = 1;
        }
        console.log("vip:" + this.userLevel);

        this.vip.source = `vip${this.userLevel}_emblem_png`;
        if (this.userLevel == 3) {
            this.pigList['vip2'].lockMask.visible = false;
            this.pigList['vip3'].lockMask.visible = false;
            this.optional_vip1 = true;
            this.optional_vip2 = true;
            this.optional_vip3 = true;
        } else if (this.userLevel == 2) {
            this.pigList['vip2'].lockMask.visible = false;
            this.optional_vip1 = true;
            this.optional_vip2 = true;
        } else {
            this.optional_vip1 = true;
        }

        // 更新种类
        if (this.pigTheme == 'wastonA') {
            this.giftTips.text = `累计打卡14天，养成这只运动猪，\n即有机会赢取变美小礼包哦~`;
            for (let i = 1; i <= 3; i++) {
                this.pigList[`vip${i}`][`vip${i}Pig`].source = `cho_ath_vip${i}_png`;
            }
        } else if (this.pigTheme == 'wastonB') {
            this.giftTips.text = `累计打卡14天，养成这只臭美猪，\n即有机会赢取变美小礼包哦~`;
            for (let i = 1; i <= 3; i++) {
                this.pigList[`vip${i}`][`vip${i}Pig`].source = `cho_bea_vip${i}_png`;
            }
        } else if (this.pigTheme == 'wastonC') {
            this.giftTips.text = `累计打卡14天，养成这只社会猪，\n即有机会赢取变美小礼包哦~`;
            for (let i = 1; i <= 3; i++) {
                this.pigList[`vip${i}`][`vip${i}Pig`].source = `cho_soc_vip${i}_png`;
            }
        }
    }

    initEvents() {
        super.initEvents();
        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin_view, this);
        this.addEventListener(egret.TouchEvent.TOUCH_END, this.onEnd_view, this);
        this.addEventListener(egret.TouchEvent.TOUCH_CANCEL, this.onEnd_view, this);

        this.reChooseBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_reChooseBtn, this);
        this.chooseBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_chooseBtn, this);
    }

    removeEvents() {
        super.removeEvents();
        this.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin_view, this);
        this.removeEventListener(egret.TouchEvent.TOUCH_END, this.onEnd_view, this);
        this.removeEventListener(egret.TouchEvent.TOUCH_CANCEL, this.onEnd_view, this);

        this.reChooseBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_reChooseBtn, this);
        this.chooseBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_chooseBtn, this);
    }

    private startX: number;
    private startY: number;
    onBegin_view(e) {
        egret.Tween.removeAllTweens();
        this.startX = e.stageX;
        this.startY = e.stageY;
        this.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_view, this);
    }

    onMove_view(e) {
        let endX = e.stageX;
        let endY = e.stageY;

        let offsetX = this.startX - endX;

        if (this.pigList['vip1'].x <= 313.5 && this.pigList['vip3'].x >= 313.5) {
            this.pigList['vip1'].x -= offsetX;
            this.pigList['vip2'].x -= offsetX;
            this.pigList['vip3'].x -= offsetX;
            this.startX = endX;

            this.updatePigScale();
        }


    }

    onEnd_view(e) {
        // 吸附位置

        if (this.pigList['vip1'].x > 313.5) {
            this.currChooseLevel = 'Lv1';
            let tw1 = egret.Tween.get(this.pigList['vip1']).to({ x: 313.5 }, 100);
            let tw2 = egret.Tween.get(this.pigList['vip2']).to({ x: 678.5 }, 100);
            let tw3 = egret.Tween.get(this.pigList['vip3'], { onChange: this.updatePigScale.bind(this) }).to({ x: 1043.5 }, 100).call(() => {
                this.point.source = 'point1_png';
                this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_view, this);
            });
        } else if (this.pigList['vip3'].x < 313.5) {
            this.currChooseLevel = 'Lv3';
            let tw1 = egret.Tween.get(this.pigList['vip1']).to({ x: -416.5 }, 100);
            let tw2 = egret.Tween.get(this.pigList['vip2']).to({ x: -51.5 }, 100);
            let tw3 = egret.Tween.get(this.pigList['vip3'], { onChange: this.updatePigScale.bind(this) }).to({ x: 313.5 }, 100).call(() => {
                this.point.source = 'point3_png';
                this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_view, this);
            });
        } else {
            let currChoosePig = null;
            let offset1 = Math.abs(this.pigList['vip1'].x - 313.5);
            let offset2 = Math.abs(this.pigList['vip2'].x - 313.5);
            let offset3 = Math.abs(this.pigList['vip3'].x - 313.5);
            let minOffset = Math.min(offset1, offset2, offset3);
            if (minOffset == offset1) {
                this.currChooseLevel = 'Lv1';
                let tw1 = egret.Tween.get(this.pigList['vip1']).to({ x: 313.5 }, 100);
                let tw2 = egret.Tween.get(this.pigList['vip2']).to({ x: 678.5 }, 100);
                let tw3 = egret.Tween.get(this.pigList['vip3'], { onChange: this.updatePigScale.bind(this) }).to({ x: 1043.5 }, 100).call(() => {
                    this.point.source = 'point1_png';
                    this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_view, this);
                });
            } else if (minOffset == offset2) {
                this.currChooseLevel = 'Lv2';
                let tw1 = egret.Tween.get(this.pigList['vip1']).to({ x: -51.5 }, 100);
                let tw2 = egret.Tween.get(this.pigList['vip2']).to({ x: 313.5 }, 100);
                let tw3 = egret.Tween.get(this.pigList['vip3'], { onChange: this.updatePigScale.bind(this) }).to({ x: 678.5 }, 100).call(() => {
                    this.point.source = 'point2_png';
                    this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_view, this);
                });
            } else if (minOffset == offset3) {
                this.currChooseLevel = 'Lv3';
                let tw1 = egret.Tween.get(this.pigList['vip1']).to({ x: -416.5 }, 100);
                let tw2 = egret.Tween.get(this.pigList['vip2']).to({ x: -51.5 }, 100);
                let tw3 = egret.Tween.get(this.pigList['vip3'], { onChange: this.updatePigScale.bind(this) }).to({ x: 313.5 }, 100).call(() => {
                    this.point.source = 'point3_png';
                    this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_view, this);
                });
            }
        }
    }

    onTap_reChooseBtn() {
        //点击埋点
        NetManager.ins.clickLog(this.exposures["reChoose"]);

        this.reChooseBtn.touchEnabled = false;
        setTimeout(() => {
            this.reChooseBtn.touchEnabled = true;
        }, 1000);
        SceneCtrl.instance.change(ModuleTypes.PIGTHEME_SCENE);
    }

    onTap_chooseBtn() {
        //点击埋点
        NetManager.ins.clickLog(this.exposures["choose"]);

        this.chooseBtn.touchEnabled = false;
        switch (this.currChooseLevel) {
            case 'Lv1':
                Waiting.instance.show();
                GameConst.adoptePig(1, this.pigTheme, (success) => {
                    Waiting.instance.hide();
                    this.chooseBtn.touchEnabled = true;
                    if (success) {
                        window["currentPigData"] = {
                            "petId": DataManager.ins.getData('adoptePig').data,
                            "vipLevel": 1,
                            "identifier": this.pigTheme,
                            "alredyReward": false,
                            "loveValue": 0,
                            "petLevel": 0,
                            "usingToys": [

                            ]
                        }
                        SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE)
                    } else {
                        // 领养失败
                        setTimeout(() => {
                            this.chooseBtn.touchEnabled = true;
                        }, 500)
                        let msgData = { msg: '啊哦，领养失败，请稍后再试~', type: 'tips', title: '很遗憾' }
                        PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, msgData);
                    }
                })
                break;
            case 'Lv2':
                if (this.optional_vip2) {
                    Waiting.instance.show();
                    GameConst.adoptePig(2, this.pigTheme, (success) => {
                        Waiting.instance.hide();
                        this.chooseBtn.touchEnabled = true;
                        if (success) {
                            window["currentPigData"] = {
                                "petId": DataManager.ins.getData('adoptePig').data,
                                "vipLevel": 2,
                                "identifier": this.pigTheme,
                                "alredyReward": false,
                                "loveValue": 0,
                                "petLevel": 0,
                                "usingToys": [

                                ]
                            }
                            SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE)
                        } else {
                            // 领养失败
                            setTimeout(() => {
                                this.chooseBtn.touchEnabled = true;
                            }, 500)
                            let msgData = { msg: '啊哦，领养失败，请稍后再试~', type: 'tips', title: '很遗憾' }
                            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, msgData);
                        }
                    })
                } else {
                    // 出toast
                    this.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin_view, this);
                    this.removeEventListener(egret.TouchEvent.TOUCH_END, this.onEnd_view, this);
                    this.removeEventListener(egret.TouchEvent.TOUCH_CANCEL, this.onEnd_view, this);
                    this.toast.visible = true;
                    this.touchEnabled = false;
                    this.reChooseBtn.touchEnabled = false;
                    setTimeout(() => {
                        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin_view, this);
                        this.addEventListener(egret.TouchEvent.TOUCH_END, this.onEnd_view, this);
                        this.addEventListener(egret.TouchEvent.TOUCH_CANCEL, this.onEnd_view, this);
                        this.toast.visible = false;
                        this.touchEnabled = true;
                        this.reChooseBtn.touchEnabled = true;
                        this.chooseBtn.touchEnabled = true;
                    }, 1000);
                }
                break;
            case 'Lv3':
                if (this.optional_vip3) {
                    Waiting.instance.show();
                    GameConst.adoptePig(3, this.pigTheme, (success) => {
                        Waiting.instance.hide();
                        this.chooseBtn.touchEnabled = false;
                        if (success) {
                            window["currentPigData"] = {
                                "petId": DataManager.ins.getData('adoptePig').data,
                                "vipLevel": 3,
                                "identifier": this.pigTheme,
                                "alredyReward": false,
                                "loveValue": 0,
                                "petLevel": 0,
                                "usingToys": [

                                ]
                            }
                            SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE)
                        } else {
                            // 领养失败
                            setTimeout(() => {
                                this.chooseBtn.touchEnabled = true;
                            }, 500)
                            let msgData = { msg: '啊哦，领养失败，请稍后再试~', type: 'tips', title: '很遗憾' }
                            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, msgData);
                        }
                    })
                } else {
                    // 出toast
                    this.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin_view, this);
                    this.removeEventListener(egret.TouchEvent.TOUCH_END, this.onEnd_view, this);
                    this.removeEventListener(egret.TouchEvent.TOUCH_CANCEL, this.onEnd_view, this);
                    this.toast.visible = true;
                    this.touchEnabled = false;
                    this.reChooseBtn.touchEnabled = false;
                    setTimeout(() => {
                        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin_view, this);
                        this.addEventListener(egret.TouchEvent.TOUCH_END, this.onEnd_view, this);
                        this.addEventListener(egret.TouchEvent.TOUCH_CANCEL, this.onEnd_view, this);
                        this.toast.visible = false;
                        this.touchEnabled = true;
                        this.reChooseBtn.touchEnabled = true;
                        this.chooseBtn.touchEnabled = true;
                    }, 1000);
                }
                break;

        }
    }

    updatePigScale() {
        for (let i = 1; i <= 3; i++) {
            try {
                if (this.pigList[`vip${i}`].x < 313.5) {
                    // console.log(this.pigList['vip1'].x)
                    if (this.pigList[`vip${i}`].x > 0) {
                        let offset = 313.5 - this.pigList[`vip${i}`].x;
                        let rate = offset / 313.5;
                        this.pigList[`vip${i}`].scaleX = 1.1 - 0.2 * rate;
                        this.pigList[`vip${i}`].scaleY = 1.1 - 0.2 * rate;
                    }
                } else {
                    let offset = this.pigList[`vip${i}`].x - 313.5;
                    let rate = offset / 313.5 < 1 ? offset / 313.5 : 1;
                    this.pigList[`vip${i}`].scaleX = 1.1 - 0.2 * rate;
                    this.pigList[`vip${i}`].scaleY = 1.1 - 0.2 * rate;
                }
            } catch{

            }

        }

    }

}