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, preLoadRes, showToast} from "../../comm/UtilsConst";
import {G_GetHomeDataByKey, G_UpdateHomeData, HOME} from "../Home";
import ExchangePanel from "../../Panels/ExchangePanel";

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

export default class ExchangeScene extends Scene {
    public group: eui.Group;
    public shopLayer: eui.Group;
    public backBtn: eui.Image;
    public recordBtn: eui.Image;
    public goodsGroup: eui.Group;
    public none: eui.Group;
    public have: eui.Scroller;
    public list: eui.List;

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

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

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

        preLoadRes('exchange_panel', 'exchanged_panel');
    }

    private reset() {
        this.setGoods();
    }

    private initUI(): void {
        this.group.height = 750 / window.innerWidth * window.innerHeight;
        this.reset();
    }

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

    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.recordBtn:
                btnDelay(this.recordBtn);
                egret.Tween.get(this.recordBtn)
                    .to({scaleX: 1.2, scaleY: 0.8}, 80)
                    .to({scaleX: 1, scaleY: 1}, 80)
                    .call(() => {
                        window.location.href = window['record'];
                    });
                break;

            default:
                break;
        }
    }

    /**
     * 设置商品列表
     */
    private setGoods() {
        G_UpdateHomeData().then(() => {
            this.getGoodsInfo().then(() => {
                const _d = [];

                for (let k in this.prizeData) {
                    _d.push(this.prizeData[k]);
                }

                this.none.visible = (_d.length <= 0);
                this.have.visible = !(_d.length <= 0);
                this.list.useVirtualLayout = false;
                this.list.itemRenderer = ExchangeItem;
                this.list.dataProvider = new eui.ArrayCollection(_d);
            }).catch(() => {
                this.none.visible = true;
                this.have.visible = false;
            });
        });
    }

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

        return new Promise<void>((resolve, reject) => {
            ///////////////////////// 查询商店列表 /////////////////////////
            NetManager.ins.mergeQuery((success, res) => {
                if (!success) {
                    reject();
                    return;
                }
                const data = res.data;
                let prizeIds = '';
                for (let k in data) {
                    const _d = JSON.parse(data[k]);

                    if (!_d.success) continue;

                    for (let i = 0; i < _d.data.length; i++) {
                        if (_d.data[i].prizeId == 'thanks') {
                            _d.data.splice(i, 1);
                        }
                    }

                    if (_d.data.length <= 0) continue;

                    const prizeId = _d.data[0].prizeId;
                    this.prizeData[prizeId] = JSON.parse(JSON.stringify(_d.data[0])); // 保存商品信息
                    this.prizeData[prizeId].strategyId = k;    // 保存规则Id
                    prizeIds += `${k}:${prizeId},`;
                    this.prizeData[prizeId].canGet = true;
                }
                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;
                    }
                    ///////////////////////// 查询是否合成过 /////////////////////////
                    /// TODO 2020.11.18, 运营要求所有奖品可以无限制兑换，去掉兑换一次的限制
                    // 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();   /// TODO 移到下面去
                    // });
                    resolve(); /// TODO 上面移下来的

                    ///////////////////////// 查询是否合成过 /////////////////////////
                }, prizeIds);
                ///////////////////////// 查询库存和需要的道具信息 /////////////////////////
            }, querys);
            ///////////////////////// 查询商店列表 /////////////////////////
        });
    }

    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 'ExchangeScene'
    }

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

// 商店列表
class ExchangeItem 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 sp_5_group: eui.Group;
    public sp_5_label: eui.Label;
    public sp_6_group: eui.Group;
    public sp_6_label: eui.Label;
    public stock_label: eui.Label;
    public mk: eui.Rect;

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

    dataChanged() {
        this.mk.visible = !this.data.canGet;
        let title = this.data.name.split('_@_');    // 切分名字和介绍
        this.title.text = title[0];
        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;

        this.btn.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
            if (!this.data.canGet) { // 已经合成过则不设置监听
                showToast("兑换次数已达上限");
                return;
            }
            btnDelay(this.btn);
            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(ExchangePanel, this.data);
                });
        }, this);
    }

    // 显示需要的道具
    private setNeed() {
        const showList = [];
        const spMap = this.data.spMap;
        for (let spk in 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] < spMap[v]) ? 0xed3330 : 0x855933}
                },
                {text: '/' + spMap[v], style: {"textColor": 0x855933}}
            ];
        });
        // 显示+号
        for (let i = 1; i < showList.length; i++) {
            this[`add${i}`].visible = true;
        }
    }
}
