import { Buried } from './../../libs/tw/util/Buried';
import { NetManager } from './../../libs/tw/manager/NetManager';
import { weidianNet } from './../NetConst';
import { ModuleTypes } from './../types/sceneTypes';
import { DataManager } from './../../libs/tw/manager/DataManager';
import Scene from "../views/Scene";
import ToastCtrl from '../ctrls/toastCtrl';
import SceneCtrl from '../ctrls/sceneCtrl';
import Waiting from '../waiting/Waiting';
import PanelCtrl from '../ctrls/panelCtrl';
import GameConst from '../GameConst';

export default class ShopScene extends Scene {
    public get skinKey() { return "Shop" }

    public friendsGroup: eui.Group;
    public inviteBtn: eui.Image;
    public stealBtn: eui.Group;
    public stealNum: eui.Label;
    public getConponBtn: eui.Button;
    public myCoffeeStoreBtn: eui.Button;
    public shopName: eui.Label;
    public avatarMask: eui.Image;
    public avatar: eui.Image;
    public shopLevel: eui.Label;
    public type: eui.Label;
    public reduce: eui.Label;
    public full: eui.Label;
    public time: eui.Label;
    public itemsGroup: eui.Group;
    public noCouponTips: eui.Image;


    constructor() {
        super();
        this.percentHeight = 100;
        this.percentWidth = 100;
        this.initBuried();
        this.initUI();

    }

    private inviteBtnExposure: any;
    private myBtnExposure: any;
    private stealBtnExposure: any;
    initBuried() {
        // 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);
        // 38 返回我的店铺
        let myBtnDpm = Buried.connectDpm(110, 38, 1); // 点击埋点   
        let myBtnDcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
        this.myBtnExposure = Buried.createExposure(myBtnDpm, myBtnDcm);
        NetManager.ins.showLog(this.myBtnExposure);
        // 39 偷金币
        let stealBtnDpm = Buried.connectDpm(110, 39, 1); // 点击埋点   
        let stealBtnDcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
        this.stealBtnExposure = Buried.createExposure(stealBtnDpm, stealBtnDcm);
        NetManager.ins.showLog(this.stealBtnExposure);


    }

    initUI() {
        const { coupon, items, shop } = DataManager.ins.getData("getShopDetail").data;
        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 ? DataManager.ins.getData("getFriendsInfo").data : [];
        const stealable = DataManager.ins.getData("getShopStatus").data;

        if (shop.shopLogo) {
            this.avatar.source = shop.shopLogo;
        }

        this.stealNum.text = "+" + GameConst.tranNumber(50000);

        this.avatar.mask = this.avatarMask;
        this.shopName.text = this.fixName(shop.shopName, 4, "shop") + "的咖啡店";

        if (coupon) {
            this.type.text = coupon.type
            this.full.text = coupon.full;
            this.reduce.text = coupon.reduce;
            this.time.text = coupon.time;

            let Dpm = Buried.connectDpm(110, 41, 1); // 点击埋点   
            let Dcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
            let Exposure = Buried.createExposure(Dpm, Dcm);
            NetManager.ins.showLog(Exposure);
            this.onTap(this.getConponBtn, () => {
                NetManager.ins.clickLog(Exposure)
                setTimeout(() => {
                    window.location.href = `weidianbuyer://wdb/webview?url=${encodeURIComponent(coupon.couponUrl)}`;
                }, 500);
            })
        } else {
            this.noCouponTips.visible = true;
        }

        if (items && items.length > 0) {
            for (let i = 0; i < Math.min(items.length, 3); i++) {
                // let item = items[i];
                let goodsItem = new eui.Component();
                goodsItem.skinName = "ShopItemSkin";
                goodsItem.x = i * 184 + 4;
                goodsItem['itemPic'].source = items[i].itemPic;
                goodsItem['itemPic'].mask = goodsItem['itemMask'];
                goodsItem['itemName'].text = this.fixName(items[i].itemName, 16);
                goodsItem['itemPrice'].text = "￥" + (items[i].itemPrice / 100).toFixed(1);
                if (items[i].itemPrice < items[i].itemOriginalPrice) {
                    goodsItem['itemOriginalPrice'].visible = true;
                    goodsItem['itemOriginalPrice'].text = (items[i].itemOriginalPrice / 100).toFixed(1);
                    goodsItem['itemOriginalPrice'].x = goodsItem['itemPrice'].x + goodsItem['itemPrice'].width + 10;
                    goodsItem['line'].width = goodsItem['itemOriginalPrice'].width + 8;
                    goodsItem['line'].x = goodsItem['itemOriginalPrice'].x - 3;
                } else {
                    goodsItem['itemOriginalPrice'].visible = false;
                    goodsItem['line'].visible = false;
                }
                // goodsItem['idx'] = i;
                let dpm = Buried.connectDpm(110, 40, i + 1); // 点击埋点   
                let dcm = Buried.connectDcm(202, 0, 0); // 曝光埋点
                let Exposure = Buried.createExposure(dpm, dcm);
                NetManager.ins.showLog(Exposure);
                this.itemsGroup.addChild(goodsItem);
                this.onTap(goodsItem, () => {
                    NetManager.ins.clickLog(Exposure);
                    setTimeout(() => {
                        window.location.href = items[i].itemUrl;
                    }, 500);
                })
            }
        }

        if (stealable) {
            this.stealBtn.visible = true;
            this.onTap(this.stealBtn, this.onTap_stealBtn)
        } else {
            this.stealBtn.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;

    }


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

    onTap_stealBtn() {
        NetManager.ins.clickLog(this.stealBtnExposure);
        Waiting.instance.show();
        weidianNet.stealShopGold((s) => {
            Waiting.instance.hide();
            if (!s) {
                ToastCtrl.instance.show(DataManager.ins.getData("stealShopGold").message)
                return
            }
            ToastCtrl.instance.show(`成功偷取${50000}金币`);
            this.stealBtn.visible = false;
        }, DataManager.ins.getData("getShopDetail").data.shop.shopId, 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(DataManager.ins.getData("getFriendDetail").message)
                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
            }

            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();
    }

    fixName(name: string, num = 4, type?) {
        if (!name || name == "") {
            if (type == "shop") {
                return "微店"
            } else if (type == "friend") {
                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;
        }

    }

}