import { DataManager } from './../../libs/tw/manager/DataManager';
import GameConst, { arr, wait } from '../consts/GameConst';
import { GDispatcher } from '../../libs/tc/util/GDispatcher';
import { TwFun } from '../../libs/tw/util/TwFun';

import { ModuleTypes } from '../types/ModuleTypes';
import { NetPromise } from '../promises/NetPromise';
import Scene from "../views/Scene";
import SVGACtrl from "../ctrls/svgaCtrl";
import ToastCtrl from '../ctrls/toastCtrl';
import PanelCtrl from '../ctrls/panelCtrl';
import Waiting from '../waiting/Waiting';
import SceneCtrl from '../ctrls/sceneCtrl';
import PrizeItem from './PrizeItem';

export default class MainScene extends Scene {
    public get skinKey() { return "Main" }

    public bg: eui.Image;
    public prizeMinTitle: eui.Image;
    public title: eui.Image;
    public logo: eui.Image;
    public plate: eui.Image;
    public winnerList: eui.Group;
    public msgList: eui.Group;
    public msgListMask: eui.Rect;
    public prizeList: eui.Scroller;
    public prizeListGroup: eui.Group;
    public main: eui.Group;
    public startBtnBg: eui.Image;
    public costTxt: eui.Label;
    public startDrawBg: eui.Image;
    public thanks: eui.Group;
    public thanksBg: eui.Rect;
    public prizeImg: eui.Image;
    public startBtn: eui.Button;
    public ruleBtn: eui.Button;
    public recordBtn: eui.Button;

    public mainMask: egret.Shape;

    get allUserRecords() { return DataManager.ins.getData("queryAllUserRecords") && DataManager.ins.getData("queryAllUserRecords").data && DataManager.ins.getData("queryAllUserRecords").data || [] }
    get remainTimes() { return DataManager.ins.getData("getRemainTimes") && DataManager.ins.getData("getRemainTimes").data }
    get allPrize() { return DataManager.ins.getData("getPrizeInfo") && DataManager.ins.getData("getPrizeInfo").data }
    get prize() { return DataManager.ins.getData("doJoin") && DataManager.ins.getData("doJoin").data }
    start() {

        super.start()
        this.initUI()

    }

    initUI() {

        // this.mainMask = new egret.Shape()

        // this.main.mask = this.mainMask

        if (this.remainTimes && this.remainTimes > 0) {
            this.costTxt.text = `剩余抽奖次数：${this.remainTimes}`
        } else {
            this.startBtn.icon = `startBtn_d_png`
            this.costTxt.text = `没有抽奖机会了`
        }

        this.winnerList.mask = this.msgListMask
        if (this.allUserRecords.length > 0) {
            let data = DataManager.ins.getData("queryAllUserRecords").data;

            for (let i = 0; i < data.length - 1; i++) {
                let name = null;
                let prizeName = data[i].name;
                if (data[i].nickname) {
                    let stars = "***";
                    let namesplit = data[i].nickname.split("");
                    if (namesplit.length > 2) {
                        let length = data[i].nickname.split("").length
                        // for (let i = 0; i < length - 2; i++) {
                        // stars += "*"
                        // }
                        name = data[i].nickname.split("")[0] + stars + data[i].nickname.split('')[data[i].nickname.split('').length - 1];
                    }
                    name = data[i].nickname.split("")[0] + stars + data[i].nickname.split('')[data[i].nickname.split('').length - 1];
                } else {
                    let stars = "***";
                    if ((data[i].userId + "").split("").length > 2) {
                        // let length = data[i].nickname.split("").length
                        // for (let i = 0; i < length - 2; i++) {
                        //     stars += "*"
                        // }
                        name = (data[i].userId + "").split("")[0] + stars + (data[i].userId + "").split('')[(data[i].userId + "").split('').length - 1];
                    }


                }

                if (name && prizeName) {
                    let msg = name + "成功获得了" + prizeName;
                    let label = new eui.Label();
                    label.size = 26;
                    label.textColor = 0xf0ca91;
                    label.verticalCenter = 0;
                    label.text = msg;
                    if (i == 0) {
                        label.x = 780;
                    } else {
                        label.x = 30 + this.msgPool[this.msgPool.length - 1].x + this.msgPool[this.msgPool.length - 1].width
                    }

                    this.msgList.addChild(label);
                    this.msgPool.push(label);
                }
            }
        } else {
            this.winnerList.y = -60;
        }

        if (this.allPrize && this.allPrize.length > 0) {
            this.allPrize.forEach((prize, idx) => {
                let prizeItem = new PrizeItem()
                prizeItem.prizeImg.source = `${prize.icon}`
                prizeItem.prizeName.text = `${prize.name}`
                prizeItem.x = idx * 220
                this.prizeListGroup.addChild(prizeItem)
            });
        }


        this.snowAni()


        ToastCtrl.instance.show(`恭喜你，获得${this.remainTimes}次抽奖次数`)
    }


    initEvents() {
        super.initEvents()
        this.onTap(this.startBtn, this.onTap_startBtn)
        this.onTap(this.ruleBtn, this.onTap_ruleBtn)
        this.onTap(this.recordBtn, this.onTap_recordBtn)
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    onTap_ruleBtn() {
        NetPromise.getRule()
            .then(() => {
                PanelCtrl.instance.show(ModuleTypes.RULE_PANEL)
            })
            .catch(e => {
                console.error(e);
                ToastCtrl.instance.show("获取规则失败，请稍后重试~")
            })
    }

    onTap_recordBtn() {
        window.location.href = window['recordUrl']
    }

    onTap_startBtn() {
        if (this.remainTimes && this.remainTimes > 0) {
            Waiting.instance.show()
            NetPromise.doJoin()
                .then(() => {
                    Waiting.instance.hide()
                    this.resetGame()
                })
                .catch(e => {
                    console.error(e);
                    Waiting.instance.hide()
                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, { msg: "网络异常，请稍后再试~", type: "tips" })
                })
        } else {
            ToastCtrl.instance.show("您暂无抽奖次数~\n消费任意金额后即可免费参与刮奖", 3000)
        }
    }

    private msgPool: any[] = []
    private isHideMsg: boolean = false;
    onEnterFrame() {
        if (this.msgPool && this.msgPool.length > 0 && !this.isHideMsg) {
            if (this.msgPool[this.msgPool.length - 1].x < -this.msgPool[this.msgPool.length - 1].width - 30) {
                this.isHideMsg = true;
                egret.Tween.get(this.winnerList)
                    .to({ y: -60 }, 500)
            } else {
                this.msgPool.forEach((msg) => {
                    msg.x -= 1;
                })
            }
        }

    }


    removeEvents() {
        super.removeEvents
        this.clearTap(this.startBtn, this.onTap_startBtn)
        this.clearTap(this.ruleBtn, this.onTap_ruleBtn)
        this.clearTap(this.recordBtn, this.onTap_recordBtn)
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    distance = 0;
    resetGame() {
        this.startBtn.visible = false;
        this.costTxt.visible = false;
        this.startDrawBg.visible = true;
        this.distance = 0;

        if (this.prize) {
            // 有奖
            this.thanks.visible = false;

            this.prizeImg.visible = true;
            let icon = null;
            this.allPrize.forEach(prize => {
                if (prize.id == this.prize.prizeId) {
                    icon = prize.icon
                }
            });
            this.prizeImg.source = icon;
            this.mainMask = new egret.Shape();
            this.mainMask.graphics.beginFill(0xff0000, 0);
            this.mainMask.graphics.drawRect(127, 180, 494, 258);
            this.mainMask.graphics.endFill();
            this.addChild(this.mainMask);
            this.mainMask.graphics.lineStyle(50, 0xff0000, 1);
            this.startDrawBg.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onDrawBegin, this)
            this.startDrawBg.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onDrawMove, this)

            this.prizeImg.mask = this.mainMask;
        } else {
            // 没奖
            this.prizeImg.visible = false;
            this.thanks.visible = true;
            this.mainMask = new egret.Shape();
            this.mainMask.graphics.beginFill(0xff0000, 0);
            this.mainMask.graphics.drawRect(127, 180, 494, 258);
            this.mainMask.graphics.endFill();
            this.addChild(this.mainMask);
            this.mainMask.graphics.lineStyle(50, 0xff0000, 1);

            this.thanks.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onDrawBegin, this)
            this.thanks.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onDrawMove, this)

            this.thanks.mask = this.mainMask;
        }

        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame_draw, this)
    }

    onEnterFrame_draw() {
        if (this.distance > 2500) {
            if (this.prize) {
                PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL)
            } else {
                PanelCtrl.instance.show(ModuleTypes.NOPRIZE_PANEL)
            }
            this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame_draw, this)
        }
    }

    startPoint: any = {}
    onDrawBegin(e) {
        this.mainMask.graphics.moveTo(e.stageX, e.stageY);
        this.startPoint = { x: e.stageX, y: e.stageY }
    }

    onDrawMove(e) {
        this.mainMask.graphics.lineTo(e.stageX, e.stageY);
        let endPoint = { x: e.stageX, y: e.stageY }
        this.distance += GameConst.distance(this.startPoint, endPoint)
        this.startPoint = endPoint
    }

    snowAni() {
        for (let i = 0; i < 100; i++) {
            let snow = new eui.Image()
            let sourceIdx = arr.getRandomOne([0, 1, 2])
            snow.source = [`smallSnow_png`, `snow_png`, `emptyStar_png`][sourceIdx]
            snow.anchorOffsetX = [3.5, 42, 21][sourceIdx]
            snow.anchorOffsetY = [3.5, 42, 21][sourceIdx]
            snow.x = Math.random() * 750
            snow.y = Math.random() * -1000
            let scale = Math.random() * [1.2, .6, .5][sourceIdx]
            snow.scaleX = scale;
            snow.scaleY = scale;
            let idx = arr.getRandomOne([1, 1, 1, 101])
            this.addChildAt(snow, idx)
            egret.Tween.get(snow, { loop: true })
                .to({ y: 1800, rotation: 360 }, Math.max(Math.random() * 30000, Math.max(Math.random() * 10000, 6000)))
        }

        this.addChild(this.winnerList)
        this.addChild(this.main)
        this.addChild(this.startBtn)
    }
}