import Scene from "../../views/Scene";
import SceneCtrl from "../../ctrls/sceneCtrl";
import { ModuleTypes } from "../../types/sceneTypes";
import { NetManager } from "../../../libs/tw/manager/NetManager";
import PanelCtrl from "../../ctrls/panelCtrl";
import { GDispatcher } from "../../../libs/tc/util/GDispatcher";
import { getSkinPath } from "../../utils";
import { btnDelay, deepClone } from "../../comm/UtilsConst";
import { G_GetHomeDataByKey, HOME } from "../Home";
import { getlogDpm, getlogItem } from "../../comm/getlogItem";

export const shopSpData = {
    sp_prop_1: { // 加速卡
        spId: 'sp_prop_1',
        name: 'speed',
        title: '加速卡',
        price: 0,
        stock: 0,
        introduce: '加速'
    },
    sp_food_1: { // 饲料
        spId: 'sp_food_1',
        name: 'food',
        title: '饲料',
        price: 0,
        stock: 0,
        introduce: '喂食'
    },
    sp_food_2: { // 水
        spId: 'sp_food_2',
        name: 'water',
        title: '水',
        price: 0,
        stock: 0,
        introduce: '浇水'
    },
};

const ruNum = 20;   // 发奖规则的个数

export default class ShopScene extends Scene {
    public group: eui.Group;
    public shopLayer: eui.Group;
    public backBtn: eui.Image;
    public goodsBtn: eui.Image;
    public propBtn: eui.Image;
    public goodsGroup: eui.Group;
    public list: eui.List;

    public propGroup: eui.Group;
    public speedGroup: eui.Group;
    public speedLabel: eui.Label;
    public speedBtn: eui.Image;
    public waterGroup: eui.Group;
    public waterLabel: eui.Label;
    public waterBtn: eui.Image;
    public foodGroup: eui.Group;
    public foodLabel: eui.Label;
    public foodBtn: eui.Image;

    private prizeData = {};
    private canShow: boolean = true;

    constructor(data?) {
        super(data);
    }

    protected start() {
        super.start();
        this.initUI();
    }

    private reset() {
        this.getPropInfo();     // 获得道具详情
        this.setGoods();
    }

    private initUI(): void {
        this.group.height = 750 / window.innerWidth * window.innerHeight;
        NetManager.ins.showLog(getlogItem(19));
        NetManager.ins.showLog(getlogItem(20));

        NetManager.ins.showLog(getlogItem(22));
        NetManager.ins.showLog(getlogItem(23));
        NetManager.ins.showLog(getlogItem(24));
        this.reset();
    }

    protected getTapEvts(): any[] {
        return super.getTapEvts().concat([
            [this.backBtn, this.onTouchTap, this],
            [this.goodsBtn, this.onTouchTap, this],
            [this.propBtn, this.onTouchTap, this],
        ]);
    }

    private buyProp(e: egret.TouchEvent) {
        btnDelay(e.target);
        let data = null;
        switch(e.target) {
            case this.speedBtn: // 买加速卡
                NetManager.ins.clickLog(getlogItem(22));
                data = shopSpData['sp_prop_1'];
                break;
            case this.waterBtn: // 买水
                NetManager.ins.clickLog(getlogItem(23));
                data = shopSpData['sp_food_2'];
                break;
            case this.foodBtn:  // 买饲料
                NetManager.ins.clickLog(getlogItem(24));
                data = shopSpData['sp_food_1'];
                break;
            default:
                break;
        }
        PanelCtrl.instance.show(ModuleTypes.SHOP_BUY_PANEL, data);
    }

    private onTouchTap(e: egret.TouchEvent) {
        switch(e.target) {
            case this.backBtn:
                btnDelay(this.backBtn);
                egret.Tween.get(this.backBtn)
                    .to({scaleX: 1.2, scaleY: 0.8}, 80)
                    .to({scaleX: 1, scaleY: 1}, 80)
                    .call(() => {
                        SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
                    });
                break;

            case this.goodsBtn:
                NetManager.ins.clickLog(getlogItem(19));
                this.goodsBtn.source = '商品w_png';
                this.propBtn.source = '道具b_png';
                this.goodsGroup.visible = true;
                this.propGroup.visible = false;
                this.setGoods();
                break;

            case this.propBtn:
                NetManager.ins.clickLog(getlogItem(20));
                this.goodsBtn.source = '商品b_png';
                this.propBtn.source = '道具w_png';
                this.goodsGroup.visible = false;
                this.propGroup.visible = true;
                this.getPropInfo();
                break;

            default:
                break;
        }
    }

    /**
     * 设置商品列表
     */
    private setGoods() {
        this.getGoodsInfo().then(() => {
            let _d = [];
            for(let k in this.prizeData) {
                _d.push(this.prizeData[k]);
            }
            this.list.useVirtualLayout = false;
            this.list.itemRenderer = ShopItem;
            this.list.dataProvider = new eui.ArrayCollection(_d);
        }).catch(() => {

        });
    }

    /**
     * 查询商品并设置好信息
     * @returns {Promise}
     */
    private getGoodsInfo() {
        // 聚合查询
        let querys = {};
        for(let i = 1; i <= ruNum; i++) {
            querys[`ru_item_${i}`] = {
                path: `/ru_item_${i}.query`,
                params: {},
            }
        }
        // /projectx/${window['projectId']}

        return new Promise((resolve, reject) => {
            ///////////////////////// 查询商店列表 /////////////////////////
            NetManager.ins.mergeQuery((success, res) => {
                if(!success) {
                    reject();
                    return;
                }
                const data = res.data;
                let rePrizeInfo = {};   // prizeId 和 strategyId 的反向映射
                let prizeIds = '';
                for(let k in data) {
                    let _d = JSON.parse(data[k]);
                    if(!_d.success) {
                        continue;
                    }
                    this.prizeData[_d.data[0]['prizeId']] = deepClone(_d.data[0]); // 保存商品信息
                    this.prizeData[_d.data[0]['prizeId']]['strategyId'] = k;    // 保存规则Id
                    rePrizeInfo[k] = _d.data[0]['prizeId'];
                    prizeIds += `${k}:${_d.data[0]['prizeId']},`;
                    this.prizeData[_d.data[0]['prizeId']]['canGet'] = true;

                    (this.canShow) ? NetManager.ins.showLog(getlogDpm(21, +k.slice(8))) : 0;
                }
                this.canShow = false;
                prizeIds = prizeIds.slice(0, prizeIds.length - 1);
                ///////////////////////// 查询库存和需要的道具信息 /////////////////////////
                NetManager.ins.prizeInfo((success, res) => {
                    if(!success) {
                        reject();
                        return;
                    }
                    const _data = res.data;
                    for(let k in _data) { // 设置库存
                        this.prizeData[k]['stock'] = _data[k]['stock'];
                        this.prizeData[k]['spMap'] = _data[k]['spMap'];
                    }
                    ///////////////////////// 查询是否合成过 /////////////////////////
                    NetManager.ins.queryRecords((success, res) => {
                        if(!success) {
                            reject();
                            return;
                        }
                        const __data = res.data;
                        for(let v of __data){
                            let prizeId = v.prizeId;
                            if(this.prizeData.hasOwnProperty(prizeId)){
                                this.prizeData[prizeId]['canGet'] = false;
                            }
                        }
                        resolve();
                    });
                    // let _querys = {};
                    // for(let i = 1; i <= ruNum; i++) {
                    //     _querys[`ru_item_${i}`] = {
                    //         path: `/strategyRecords.query`,
                    //         params: {strategyId: `ru_item_${i}`, limit: 5},
                    //     }
                    // }
                    // NetManager.ins.mergeQuery((success, res) => {
                    //     if(!success) {
                    //         reject();
                    //         return;
                    //     }
                    //     const __data = res.data;
                    //     for(let k in __data) {
                    //         let __d = JSON.parse(__data[k]);
                    //         if(!rePrizeInfo[k]) {
                    //             continue;
                    //         }
                    //         this.prizeData[rePrizeInfo[k]]['canGet'] = (!__d.success) || (__d.data.length <= 0);
                    //     }
                    //     resolve();
                    // }, _querys);
                    ///////////////////////// 查询是否合成过 /////////////////////////
                }, prizeIds);
                ///////////////////////// 查询库存和需要的道具信息 /////////////////////////
            }, querys);
            ///////////////////////// 查询商店列表 /////////////////////////
        });
    }

    // shop_buy_png    shop_none_png    shop_done_png
    /**
     * 获得道具库存价格信息
     */
    private getPropInfo() {
        NetManager.ins.propInfo((success, res) => {
            if(!success) {
                return;
            }
            let data = {};
            res.data.forEach((v) => {
                data[v.spId] = {};
                data[v.spId]['stock'] = v.stock;
                data[v.spId]['price'] = v.price;
            });
            for(let k in shopSpData) {
                let spd = shopSpData[k];
                let d = data[k] || null;
                shopSpData[k].price = d.price;
                shopSpData[k].stock = d.stock;
                this[`${spd.name}Label`].text = `所需欢趣豆：${d ? d.price : 0}`;
                (d && d.stock > 0)
                    ? function() {  // 有库存
                        this[`${spd.name}Btn`].source = 'shop_buy_png';
                        this[`${spd.name}Btn`].addEventListener(egret.TouchEvent.TOUCH_TAP, this.buyProp, this);
                    }.bind(this)()
                    : function() {  // 无库存
                        if(this[`${spd.name}Btn`].hasEventListener(egret.TouchEvent.TOUCH_TAP)) {
                            this[`${spd.name}Btn`].removeEventListener(egret.TouchEvent.TOUCH_TAP, this.buyProp, this);
                        }
                        this[`${spd.name}Btn`].source = 'shop_none_png';
                    }.bind(this)();
            }
        });
    }

    protected initEvents() {
        super.initEvents();
        GDispatcher.addEvent('docVisible', this.reset, this);
        GDispatcher.addEvent('shopUpdate', this.reset, this);
    }

    protected removeEvents() {
        super.removeEvents();
        GDispatcher.removeEvent('docVisible', this.reset, this);
        GDispatcher.removeEvent('shopUpdate', this.reset, this);
    }

    destroy() {
        super.destroy();
    }

    public get skinKey() {
        return 'ShopScene'
    }

    public get groupName() {
        return 'shop'
    }
}


const posArr = [
    [154, 64],
    [154, 64],
    [154, 64],
    [154, 64],
];

// 商店列表
class ShopItem extends eui.ItemRenderer {
    public btn: eui.Group;
    public icon: eui.Image;
    public title: eui.Label;
    public add1: eui.Label;
    public add2: eui.Label;
    public add3: eui.Label;
    public sp_1_group: eui.Group;
    public sp_1_label: eui.Label;
    public sp_2_group: eui.Group;
    public sp_2_label: eui.Label;
    public sp_3_group: eui.Group;
    public sp_3_label: eui.Label;
    public sp_4_group: eui.Group;
    public sp_4_label: eui.Label;
    public stock_label: eui.Label;
    public mk: eui.Rect;

    constructor() {
        super();
        this.skinName = getSkinPath('ShopItem');
    }

    dataChanged() {
        this.mk.visible = !this.data.canGet;
        this.title.text = this.data.name;
        this.icon.source = this.data.icon;
        this.stock_label.text = `剩余${this.data.stock}份`;

        this.setNeed();
        this.setBtn();
    }

    // 设置按钮
    private setBtn() {
        this.btn.anchorOffsetX = 261;
        this.btn.anchorOffsetY = 103;
        this.btn.touchChildren = false;

        if(!this.data.canGet) { // 已经合成过则不设置监听
            return;
        }
        this.btn.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
            btnDelay(this.btn);
            NetManager.ins.clickLog(getlogDpm(21, +this.data.strategyId.slice(8)));
            egret.Tween.get(this.btn)
                .to({scaleX: 0.9, scaleY: 0.9}, 80, egret.Ease.quadIn)
                .to({scaleX: 1, scaleY: 1}, 80, egret.Ease.quadOut)
                .call(() => {
                    PanelCtrl.instance.show(ModuleTypes.EXCHANGE_PANEL, this.data);
                });
        }, this);
    }

    // 显示需要的道具
    private setNeed() {
        let showList = [];
        for(let spk in this.data['spMap']) {
            showList.push(spk);
        }
        // 设置道具下的label
        const products: {} = G_GetHomeDataByKey(HOME.PRODUCT);
        showList.forEach((v, i) => {
            this[`${v}_group`].visible = true;
            this[`${v}_group`].x = 150 + 80 * i;
            this[`${v}_label`].textFlow = <Array<egret.ITextElement>>[
                {
                    text: products[v].toString(),
                    style: {"textColor": (products[v] < this.data['spMap'][v]) ? 0xed3330 : 0x855933}
                },
                {text: '/' + this.data['spMap'][v], style: {"textColor": 0x855933}}
            ];
        });

        // 显示+号
        for(let i = 1; i < showList.length; i++) {
            this[`add${i}`].visible = true;
        }
    }
}