import ViewObject from "../../../main/ViewObject";
import FqPay, { UM_EVENT_ID } from "../../../pay/FqPay";
import { HttpStateType, ReveData } from "../../../util/CHttp";
import { __FirstPayRewardData, __PayData, __WishData } from "../../data/sdata/SManage";

const { ccclass, property } = cc._decorator;

interface WishData {
    playerPay: Map<string, number>,
    hdPayData: Array<__WishData>
}

@ccclass
export default class Wish extends ViewObject {

    @property([cc.Node])
    itemList: cc.Node[] = [];

    @property(cc.Prefab)
    goodItem: cc.Prefab = null;

    wishData: WishData = null;
    curHdPayData = null;
    target: cc.Node = null;

    /**
     * 
     * @param prev 父界面
     */
    public show(prev?: ViewObject) {
        if (prev) {
            this.prev = prev;
            this.prev.__close();
        }
        this.main.viewManage.popView1(this.node);
        if (this.main && this.main.gameHttp) {
            this.main.gameHttp.pushEvent(this);
        }
    }

    getWishData() {
        let msg = {};
        this.main.gameHttp.sendJson(`hdpay/v1/hdData`, msg, (state, reve: ReveData) => {
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    console.log("==reve=getWishData===", reve)
                    this.wishData = reve.data;
                    this.initItem();
                    this.show();
                } else {
                    this.main.showTips(reve.message);
                }
            } else {
                this.main.showTips('网络异常');
            }
        });
    }

    playVideo(callback: (result: number) => void) {
        let eventId1 = UM_EVENT_ID.ad_wish_0;
        let eventId2 = UM_EVENT_ID.ad_wish_1;
        let fqPay: FqPay = new FqPay(this.main);
        fqPay.adVideo(callback, eventId1, eventId2);
    }

    videoFree(id: number) {
        let msg = {
            hdId: id
        };
        this.main.gameHttp.sendJson(`hdpay/v1/freeHd`, msg, (state, reve: ReveData) => {
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    this.refresh();
                    this.main.showReward(reve);
                } else {
                    this.main.showTips(reve.message);
                }
            } else {
                this.main.showTips('网络异常');
            }
        });
    }

    initItem() {
        this.wishData.hdPayData.forEach((data, index) => {
            let item = this.itemList[index];
            let parent = item.getChildByName("goodList");
            let lbtimes = item.getChildByName("lbtimes");
            let btnPay = item.getChildByName("btnPay");
            let btnGeted = item.getChildByName("btnGeted");
            let lbpay = btnPay.getChildByName("lbpay");
            let times = !this.wishData.playerPay[data.id] ? 0 : this.wishData.playerPay[data.id];
            if (lbpay) {
                let payData = this.getPayDataById(this.wishData.hdPayData[index].payId);
                lbpay.getComponent(cc.Label).string = `$ ${payData.usd}`;
            }
            lbtimes.getComponent(cc.Label).string = `限购:${times}/${data.maxCount}`;
            if (times == data.maxCount) {
                btnGeted.active = true;
                btnPay.active = false;
            }
            JSON.parse(data.reward).forEach(rd => {
                this.addGood(parent, rd);
            });
        })
    }

    addGood(parent: cc.Node, reward: __FirstPayRewardData) {
        let good = cc.instantiate(this.goodItem);
        parent.addChild(good);
        this.initGoodItem(good, reward);
    }

    initGoodItem(item: cc.Node, reward: __FirstPayRewardData) {
        let node = item.getChildByName("infoNode");
        let icon = node.getChildByName("icon").getComponent(cc.Sprite);
        let frame = item.getChildByName("frame").getComponent(cc.Sprite);
        this.initIcon(icon, reward.icon);
        this.initFrameIcon(frame, reward.frame);
        node.getChildByName("countNode").getChildByName("count").getComponent(cc.Label).string = reward.count + "";
    }

    public initIcon(icon: cc.Sprite, path: string) {
        cc.resources.load(`icon/${path}`, cc.SpriteFrame, (err, spriteFrame: cc.SpriteFrame) => {
            if (err) {
                cc.error(err);
            } else {
                icon.spriteFrame = spriteFrame;
            }
        });
    }

    public initFrameIcon(icon: cc.Sprite, path: string | number) {
        cc.resources.load(`icon/frame/${path}`, cc.SpriteFrame, (err, spriteFrame: cc.SpriteFrame) => {
            if (err) {
                cc.error(err);
            } else {
                icon.spriteFrame = spriteFrame;
            }
        });
    }

    onClick(eventTouch: cc.Event.EventTouch, data: string) {
        this.target = eventTouch.target;
        this.curHdPayData = this.wishData.hdPayData[data];
        if (data == "0") {
            this.playVideo((result) => {
                if (result == 1) {
                    this.videoFree(this.curHdPayData.id);
                } else {
                    this.main.showTips("广告还未准备好");
                }
            });
        } else if (data == "1") {
            this.pay(this.curHdPayData.payId);
        } else if (data == "2") {
            this.pay(this.curHdPayData.payId);
        }
    }

    pay(payId: string) {
        let fqPay: FqPay = new FqPay(this.main);
        let payData = this.getPayDataById(payId);
        if (payData == null) {
            console.log("===payData=null===", payId)
            return
        }
        fqPay.pay(payData, () => {
            this.refresh();
        })
    }

    getPayDataById(payId: string) {
        let payData = null;
        this.main.sManage.payDatas.forEach(data => {
            if (data.id == Number(payId)) {
                payData = data;
            }
        })
        return payData;
    }

    refresh() {
        let item = this.target.parent;
        let lbtimes = item.getChildByName("lbtimes");
        let btnPay = item.getChildByName("btnPay");
        let btnGeted = item.getChildByName("btnGeted");
        let times = !this.wishData.playerPay[this.curHdPayData.id] ? 0 : this.wishData.playerPay[this.curHdPayData.id];
        times++;
        lbtimes.getComponent(cc.Label).string = `限购:${times}/${this.curHdPayData.maxCount}`;
        if (times == this.curHdPayData.maxCount) {
            btnPay.active = false;
            btnGeted.active = true;
        }
    }
}