import { Buried } from './../../libs/tw/util/Buried';
import { equipmentConfig } from './../mainScene/EquipmentConfig';
import { NetManager } from './../../libs/tw/manager/NetManager';
import Scene from "../views/Scene";

import { playBg } from './../ctrls/soundCtrl';
import { weidianNet } from './../NetConst';
import { wait } from './../GameConst';
import { DataManager } from './../../libs/tw/manager/DataManager';
import Ani from "../mainScene/Ani";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import GameConst from "../GameConst";
import SVGACtrl from '../ctrls/svgaCtrl';
import Waiting from '../waiting/Waiting';
import ToastCtrl from '../ctrls/toastCtrl';
import SceneCtrl from '../ctrls/sceneCtrl';
export default class MinorScene extends Scene {
    public get skinKey() { return "Minor" }
    public bg: eui.Image;
    public nickName: eui.Component;
    public barCounter: eui.Image;
    public barCounterCollectBtn: eui.Component;
    public refrigerator: eui.Image;
    public refrigeratorCollectBtn: eui.Component;
    public vase: eui.Image;
    public table0: eui.Image;
    public table1: eui.Image;
    public tableCollectBtn: eui.Component;
    public waitress0: eui.Group;
    public waitressCapacity: eui.Group;
    public waitressCapacityTxt: eui.Label;
    public waitress1: eui.Group;
    public table2: eui.Image;
    public table3: eui.Image;
    public coffeeMakerGroup: eui.Group;
    public coffeeMaker: eui.Image;
    public coffeeMakerCollectBtn: eui.Component;
    public ovenGroup: eui.Group;
    public oven: eui.Image;
    public ovenCollectBtn: eui.Component;
    public redPacketBtn: eui.Button;
    public friendsGroup: eui.Group;
    public inviteBtn: eui.Image;
    public myCoffeeStoreBtn: eui.Button;
    public stealBtn: eui.Group;
    public stealNum: eui.Label;


    public waitress0Base: any;
    public waitress1Base: any;

    private mainConfig = {
        "stealGoldFalg": false,
        "avatar": "",
        "username": "",
        "storeLevel": 0,
        "coin": 0,
        "diamond": 0,
        "table": {
            capacity: 0,
            store: 0,
            level: 0,
            type: 0
        },
        "barCounter": {
            capacity: 0,
            store: 0,
            level: 0,
            type: 0
        },
        "refrigerator": {
            capacity: 0,
            store: 0,
            level: 0,
            type: 0
        },
        "oven": {
            capacity: 0,
            store: 0,
            level: 0,
            type: 0
        },
        "coffeeMaker": {
            capacity: 0,
            store: 0,
            level: 0,
            type: 0
        },
        "waitress": {
            capacity: 0,
            store: 0,
            level: 0,
            type: 0
        }
    }

    private friendUserId
    constructor(data) {
        super();
        this.percentHeight = 100;
        this.percentWidth = 100;

        this.friendUserId = data;

        this.updateData()
        // 初始化UI
        this.updateUI()
        // 初始化埋点
        this.initBuired();
    }


    updateUI() {


        const shopsList = DataManager.ins.getData("getShopsInfo") && DataManager.ins.getData("getShopsInfo").data && DataManager.ins.getData("getShopsInfo").data.shops ? DataManager.ins.getData("getShopsInfo").data.shops : [];
        const friendsList = DataManager.ins.getData("getFriendsInfo") && DataManager.ins.getData("getFriendsInfo").data ? DataManager.ins.getData("getFriendsInfo").data : [];

        if (this.mainConfig.stealGoldFalg) {
            this.stealBtn.visible = true;
        } else {
            this.stealBtn.visible = false;
        }

        if (this.mainConfig.avatar) {
            this['avatar'].source = this.mainConfig.avatar;
        }


        this['avatar'].mask = this['avatarMask'];

        if (window["resImg"]) {
            this.redPacketBtn.icon = window['resImg'];
            this.onTap(this.redPacketBtn, () => {
                NetManager.ins.clickLog(this.redPocketBtnExposure);
                let url = window["resUrl"];
                window.location.href = "weidianbuyer://wdb/webview?url=" + encodeURIComponent(url);
            })
        } else {
            this.redPacketBtn.visible = false;
        }

        let i = 0;
        if (shopsList.length > 0) {
            shopsList.forEach((shopItem, idx) => {
                let shop = new eui.Component();
                shop.skinName = "FriendItemSkin"
                shop.x = i * 120;
                shop.y = 5;
                if (shopItem.shopLogo && shopItem.shopLogo !== "") {
                    shop['avatar'].source = decodeURIComponent(shopItem.shopLogo);
                }
                shop['avatar'].mask = shop['avatarMask'];
                shop['nameTxt'].text = this.fixName(shopItem.shopName, 4, "shop");
                shop['shopId'] = shopItem.shopId;
                shop['idx'] = idx;
                this.friendsGroup.addChild(shop);
                this.onTap(shop, this.onTap_shop);

                // 店铺埋点
                let shopDpm = Buried.connectDpm(110, 10, idx); // 点击埋点   
                let shopDcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
                let shopExposure = Buried.createExposure(shopDpm, shopDcm);
                NetManager.ins.showLog(shopExposure);
                i++;
            });

        }

        if (friendsList.length > 0) {
            friendsList.forEach(friendItem => {
                let friend = new eui.Component();
                friend.skinName = "FriendItemSkin"
                friend.x = i * 120;
                friend.y = 5;
                if (friendItem.avatar && friendItem.avatar !== "") {
                    friend['avatar'].source = decodeURIComponent(friendItem.avatar);
                }
                friend['avatar'].mask = friend['avatarMask'];
                friend['nameTxt'].text = this.fixName(friendItem.nickname, 4, "friend");
                friend['friendUserId'] = friendItem.friendUserId;
                this.friendsGroup.addChild(friend);
                this.onTap(friend, this.onTap_friend)
                i++;
            });
        }

        this.inviteBtn.x = i * 120;
        this['usernametxt'].text = this.fixName(this.mainConfig.username) + "的咖啡店"
        this['levelTxt'].text = "Lv" + this.mainConfig.storeLevel + ""

        this.stealNum.text = "+" + GameConst.tranNumber(Number(DataManager.ins.getData("index").data.storeLevel) * 20000) + ""

        if (Number(this.mainConfig.table.level) > 0) {
            for (let i = 0; i < 4; i++) {
                this['table' + i].visible = true;
                this['table' + i].scaleX = 1;
                this['table' + i].scaleY = 1;
                this['table' + i].source = `table${i}${this.mainConfig.table.level}_png`;
            }
            if (this.mainConfig.table.capacity > 0) {
                this.updateCapacity("table");
            }
        }

        if (Number(this.mainConfig.oven.level) > 0) {
            this.ovenGroup.visible = true;
            this.ovenGroup.scaleX = 1;
            this.ovenGroup.scaleY = 1;
            this.oven.source = `ovenLv${this.mainConfig.oven.level}_png`;
            if (this.mainConfig.oven.level > 2) {
                this.oven.anchorOffsetX = equipmentConfig.oven[`lv${this.mainConfig.oven.level}`].anchorOffsetX;
                this.oven.anchorOffsetY = equipmentConfig.oven[`lv${this.mainConfig.oven.level}`].anchorOffsetY;
            }
            if (this.mainConfig.oven.capacity > 0) {
                this.updateCapacity("oven");
            }
        }

        if (Number(this.mainConfig.refrigerator.level) > 0) {
            this.refrigerator.visible = true;
            this.refrigerator.scaleX = 1;
            this.refrigerator.scaleY = 1;
            this.refrigerator.source = `refrigeratorLv${this.mainConfig.refrigerator.level}_png`
            this.refrigerator.anchorOffsetX = equipmentConfig.refrigerator[`lv${this.mainConfig.refrigerator.level}`].anchorOffsetX;
            this.refrigerator.anchorOffsetY = equipmentConfig.refrigerator[`lv${this.mainConfig.refrigerator.level}`].anchorOffsetY;
            if (this.mainConfig.refrigerator.capacity > 0) {
                this.updateCapacity("refrigerator");
            }
        }

        if (Number(this.mainConfig.coffeeMaker.level) > 0) {
            this.coffeeMakerGroup.visible = true;
            this.coffeeMakerGroup.scaleX = 1;
            this.coffeeMakerGroup.scaleY = 1;
            this.coffeeMaker.source = `coffeeMakerLv${this.mainConfig.coffeeMaker.level}_png`;
            this.coffeeMaker.anchorOffsetX = equipmentConfig.coffeeMaker[`lv${this.mainConfig.coffeeMaker.level}`].anchorOffsetX;
            this.coffeeMaker.anchorOffsetY = equipmentConfig.coffeeMaker[`lv${this.mainConfig.coffeeMaker.level}`].anchorOffsetY;
            if (this.mainConfig.coffeeMaker.capacity > 0) {
                this.updateCapacity("coffeeMaker");
            }
        }

        if (Number(this.mainConfig.barCounter.level) > 0) {
            this.barCounter.visible = true;
            this.barCounter.scaleX = 1;
            this.barCounter.scaleY = 1;
            this.barCounter.source = `barCounterLv${this.mainConfig.barCounter.level}_png`
            this.barCounter.anchorOffsetX = equipmentConfig.barCounter[`lv${this.mainConfig.barCounter.level}`].anchorOffsetX;
            this.barCounter.anchorOffsetY = equipmentConfig.barCounter[`lv${this.mainConfig.barCounter.level}`].anchorOffsetY;
            if (this.mainConfig.barCounter.capacity > 0) {
                this.updateCapacity("barCounter");
            }
        }

        if (this.mainConfig.waitress.level > 0) {
            for (let i = 0; i < 2; i++) {
                let waitress = new window['SVGA'].EgretMovieClip(SVGACtrl.instance.SVGAPool[`waitressLv${this.mainConfig.waitress.level}`]);
                waitress.x = 50;
                waitress.y = 180;
                waitress.anchorOffsetX = 50;
                waitress.anchorOffsetY = 180;

                waitress.scaleX = -1 * Math.pow(-1, i);
                this[`waitress${i}Base`] = waitress;
                this['waitress' + i].scaleX = 1;
                this['waitress' + i].scaleY = 1;
                this['waitress' + i].addChild(waitress);
                this['waitress' + i].dir = -1 * Math.pow(-1, i);
            }
            if (this.mainConfig.waitress.capacity > 0) {
                this.updateCapacity("waitress", 3000);
            }
            this.randomMove();
        }
    }

    /**
     * 更新数据
     */
    updateData() {
        const {
            avatar, goldCoin, diamond, storeLevel, nickname, tableLevel, ovenLevel, freezerLevel, coffeeMakerLevel, checkstandLevel, waiterLevel, stealGoldFalg
        } = DataManager.ins.getData("getFriendDetail").data;

        // const { tableList, ovenList, freezerList, coffeeMakerList, checkstandList, waiterList } = DataManager.ins.getData("getEquipments").data
        this.mainConfig.stealGoldFalg = stealGoldFalg;
        this.mainConfig.avatar = avatar;
        this.mainConfig.username = nickname;
        this.mainConfig.storeLevel = storeLevel;
        this.mainConfig.coin = goldCoin;
        this.mainConfig.diamond = diamond;
        this.mainConfig.table.level = tableLevel;
        this.mainConfig.table.store = 0;
        this.mainConfig.barCounter.level = checkstandLevel;
        this.mainConfig.barCounter.store = 0;
        this.mainConfig.refrigerator.level = freezerLevel;
        this.mainConfig.refrigerator.store = 0;
        this.mainConfig.coffeeMaker.level = coffeeMakerLevel;
        this.mainConfig.coffeeMaker.store = 0;
        this.mainConfig.oven.level = ovenLevel;
        this.mainConfig.oven.store = 0;
        this.mainConfig.waitress.level = waiterLevel;
        this.mainConfig.waitress.store = 0;

        if (avatar) {
            this.mainConfig.avatar = decodeURIComponent(avatar);
        }

    }

    /**
     * 转换产能  从以天为维度转换为以小时、分钟、秒为维度
     * @param capacity 产能
     * @param type 转换类型
     */
    exchangeCapacity(capacity, type = "s", isFloor = true) {
        let result = 0;
        switch (type) {
            case "h":
                result = isFloor ? Math.floor(capacity / 24) : capacity / 24;
                break;
            case "m":
                result = isFloor ? Math.floor(capacity / 24 / 60) : capacity / 24 / 60;
                break;
            case "s":
                result = isFloor ? Math.floor(capacity / 24 / 60 / 60) : capacity / 24 / 60 / 60;
                break;
        }
        return result;
    }



    initAni() {

    }


    private inviteBtnExposure: any;
    private myBtnExposure: any;
    private stealBtnExposure: any;
    private redPocketBtnExposure: any;
    initBuired() {
        // 4 资源位埋点
        let redPocketBtnDpm = Buried.connectDpm(110, 4, 1); // 点击埋点   
        let redPocketBtnDcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
        this.redPocketBtnExposure = Buried.createExposure(redPocketBtnDpm, redPocketBtnDcm);
        if (window["resImg"]) {
            NetManager.ins.showLog(this.redPocketBtnExposure);
        }
        // 11 邀请
        let inviteBtnDpm = Buried.connectDpm(110, 11, 1); // 点击埋点   
        let inviteBtnDcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
        this.inviteBtnExposure = Buried.createExposure(inviteBtnDpm, inviteBtnDcm);
        NetManager.ins.showLog(this.inviteBtnExposure);
        // 43 返回我的店铺
        let myBtnDpm = Buried.connectDpm(110, 43, 1); // 点击埋点   
        let myBtnDcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
        this.myBtnExposure = Buried.createExposure(myBtnDpm, myBtnDcm);
        NetManager.ins.showLog(this.myBtnExposure);
        // 42 偷金币
        let stealBtnDpm = Buried.connectDpm(110, 42, 1); // 点击埋点   
        let stealBtnDcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
        this.stealBtnExposure = Buried.createExposure(stealBtnDpm, stealBtnDcm);
        NetManager.ins.showLog(this.stealBtnExposure);
    }


    initEvents() {
        super.initEvents();
        this.onTap(this.inviteBtn, this.onTap_inviteBtn);
        this.onTap(this.stealBtn, this.onTap_stealBtn)
        this.onTap(this.myCoffeeStoreBtn, this.onTap_myCoffeeStoreBtn);

    }


    onTap_stealBtn() {
        Waiting.instance.show();
        NetManager.ins.clickLog(this.stealBtnExposure);
        weidianNet.stealFriendGold((s) => {
            Waiting.instance.hide();
            if (!s) {
                ToastCtrl.instance.show(DataManager.ins.getData("stealFriendGold").message)
                return
            }
            ToastCtrl.instance.show(`成功偷取${Number(DataManager.ins.getData("index").data.storeLevel) * 20000}金币`);
            this.stealBtn.visible = false;
        }, this.friendUserId, window['projectxId'])
    }

    onTap_friend(e) {
        Waiting.instance.show();
        let friendUserId = e.$target.$parent.friendUserId;
        weidianNet.getFriendDetail((s) => {
            Waiting.instance.hide();
            if (!s) {
                ToastCtrl.instance.show("网络开小差了，再试一次吧~")
                return
            }
            SceneCtrl.instance.change(ModuleTypes.MINOR_SCENE, friendUserId);
        }, friendUserId, window['projectxId'])
    }

    onTap_shop(e) {
        Waiting.instance.show();
        let shopId = e.$target.$parent.shopId;
        let idx = e.$target.$parent.idx;
        // 店铺埋点
        let shopDpm = Buried.connectDpm(110, 10, idx); // 点击埋点   
        let shopDcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let shopExposure = Buried.createExposure(shopDpm, shopDcm);
        NetManager.ins.clickLog(shopExposure);
        weidianNet.getShopDetail((s) => {
            if (!s) {
                Waiting.instance.hide();
                ToastCtrl.instance.show("网络开小差了，再试一次吧~")
                return
            }
            weidianNet.getShopStatus((ss) => {
                Waiting.instance.hide();
                SceneCtrl.instance.change(ModuleTypes.SHOP_SCENE);
            }, shopId, window['projectxId'])
        }, shopId, window["projectxId"])
    }

    // 邀请好友
    onTap_inviteBtn() {
        NetManager.ins.clickLog(this.inviteBtnExposure)
        weidianNet.getInviteCode((s) => {
            if (!s) {
                ToastCtrl.instance.show("获取邀请码失败，请重试~")
                return
            }
            // let data = { scene: this }
            PanelCtrl.instance.show(ModuleTypes.INVITE_PANEL)
        })
    }

    onTap_myCoffeeStoreBtn() {
        NetManager.ins.clickLog(this.myBtnExposure)
        weidianNet.index((s) => {
            if (!s) {
                ToastCtrl.instance.show("网络开小差了，再试一次吧~")
                return
            }
            SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
        }, window['projectxId'])
    }




    removeEvents() {
        super.removeEvents();


        this.clearTap(this.inviteBtn, this.onTap_inviteBtn);
        this.clearTap(this.stealBtn, this.onTap_stealBtn)
        this.clearTap(this.myCoffeeStoreBtn, this.onTap_myCoffeeStoreBtn);
    }


    /**
         * 更新产能，默认5s更新一次
         * @param name 设备名字
         * @param time 更新间隔
         */
    updateCapacity(name: string, time = 5000) {


        // 取到目标产值 5秒的产值
        let capacity = Math.floor(this.exchangeCapacity(this.mainConfig[name].capacity, "s", false) * 5);
        if (capacity < 1) {
            // 目标产值小于1 则取每分钟产值
            capacity = this.exchangeCapacity(this.mainConfig[name].capacity, "m")
            //????
            time = 60 * 1000
        }
        if (name == "waitress") {
            wait(time).then(async () => {
                this.waitressCapacityTxt.text = "+" + capacity;
                let ty = this.waitressCapacity.y;
                egret.Tween.get(this.waitressCapacity)
                    .to({ alpha: 1 }, 330)
                    .wait(200)
                    .to({ y: ty - 10, alpha: 0 }, 330)
                    .call(() => {
                        this.waitressCapacity.y = ty;
                    })
                this.updateCapacity(name, time);
            })
            return
        }
        let collectBtn = this[`${name}CollectBtn`];
        // debugger
        if (collectBtn.scaleX == 0 && collectBtn.scaleY == 0) {
            // 如果按钮处于消失状态 展示按钮    
            wait(time).then(async () => {
                this.mainConfig[name].store += capacity;
                collectBtn.collectNumTxt.text = "+" + this.mainConfig[name].store;
                collectBtn.touchEnabled = false;
                await Ani.instance.createCoinTips(collectBtn);
                collectBtn.touchEnabled = true;
                this.updateCapacity(name, time);
            })
        } else {
            // 如果按钮未收取 更新数字
            wait(time).then(async () => {
                this.mainConfig[name].store += capacity;
                collectBtn.touchEnabled = false;
                await Ani.instance.updateCoinTips(collectBtn.collectNumTxt, this.mainConfig[name].store);
                collectBtn.touchEnabled = true;
                this.updateCapacity(name, time)
            })
        }

    }

    // 随机走动
    randomMove() {
        // if (this.mainConfig.waitress.level > 0) {
        for (let i = 0; i < 2; i++) {
            let x = Math.max(310 + Math.random() * 5, Math.random() * 463)
            let y = Math.max(500, Math.random() * 950)
            let distance = GameConst.distance(this[`waitress${i}`], { x: x, y: y })

            if (x > this[`waitress${i}`].x) {
                this[`waitress${i}Base`].scaleX = 1
            } else if (x < this[`waitress${i}`].x) {
                this[`waitress${i}Base`].scaleX = -1
            }
            egret.Tween.removeTweens(this[`waitress${i}`]);
            egret.Tween.get(this[`waitress${i}`], { onChange: this.onMove.bind(this) })
                .to({ x: x, y: y }, 40 * distance)
                .call(() => {
                    this.randomMove()
                })
        }
        // }
    }

    onMove() {
        if (this.waitress1.y > this.waitress0.y) {
            this.addChildAt(this.waitress1, 16)
        } else if (this.waitress1.y < this.waitress0.y) {
            this.addChildAt(this.waitress0, 16)
        }
    }

    fixName(name: string, num = 4, type?) {
        if (!name || name == "") {
            if (type == "shop") {
                return "微店"
            } else if (type == "friend") {
                return "我的好友"
            } else {
                return "好友"
            }
        }

        try{
            name = decodeURIComponent(name);
        }
        catch{
            name = unescape(name);
        }
        let nameArr = name.split("");
        if (nameArr.length <= num) {
            return name;
        } else {
            let _name = ""
            for (let i = 0; i < num; i++) {
                _name += nameArr[i];
            }
            _name += "..."
            return _name;
        }

    }


}