// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import PlayerConst from "../data/PlayerConst";
import Util from "../util/Util";
import PoolMgr, { NODEPOOLPREFABTYPE } from "../mgr/PoolMgr";
import CashOutItem, { CASHOUTITEMSTATE } from "./uiItem/CashOutItem";
import GameConst from "../data/GameConst";
import EffectMgr from "../mgr/EffectMgr";
import HttpMgr from "../mgr/HttpMgr";
import GameMgr, { UI_NAME } from "../mgr/GameMgr";
import DataMgr from "../mgr/DataMgr";
import { EVENT_TYPE } from "../../game/data/GameData";

const { ccclass, property } = cc._decorator;

@ccclass
export default class CashOutUI extends cc.Component {

    @property(cc.Node)
    node_rectBg: cc.Node = null;

    @property(cc.Node)
    node_top: cc.Node = null;
    @property(cc.Node)
    node_content: cc.Node = null;

    @property(cc.Node)
    node_backBtn: cc.Node = null;
    @property(cc.Node)
    node_cashOutRecordBtn: cc.Node = null;

    @property(cc.Node)
    node_cashOutItemList: cc.Node = null;

    @property(cc.Label)
    label_cashNum: cc.Label = null;

    @property(cc.Node)
    node_wxIcon: cc.Node = null;
    @property(cc.Label)
    label_nickName: cc.Label = null;

    @property(cc.Node)
    node_cashOutBtn: cc.Node = null;
    @property(cc.Label)
    label_cashOutTip: cc.Label = null;

    @property(cc.Node)
    node_noCashOutBtn: cc.Node = null;
    @property(cc.Label)
    label_noCashOutTip: cc.Label = null;

    @property(cc.Node)
    node_taskCashOut: cc.Node = null;
    @property(cc.RichText)
    richText_taskCashOutBtn: cc.RichText = null;
    @property(cc.Node)
    node_goToTaskBtn: cc.Node = null;

    public curSelectCashOutItem: CashOutItem = null;

    public color_gray: cc.Color = new cc.Color(174, 174, 174);
    public color_green: cc.Color = new cc.Color(174, 174, 174);

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start() {
        this.adapt();
        this.initView();
        this.initEvent();
    }

    // update (dt) {}

    onDisable() {
        let node_playerInfoUI = mk.ui.getCurOnPanel("PlayerInfoUI");
        if (node_playerInfoUI) {
            // AdMgr.Inst.showNativeAd(4, true);
        }
       
        mk.event.remove(EVENT_TYPE.UPDATE_CashNum, this.initCashNum, this);
    }

    onEnable() {
        GameMgr.Inst.sendEvent(UI_NAME.CashOutUI, "进入提现界面");

        this.initCashNum();
        this.initCashOutItem();
        this.initNickName();
        this.initHead();
    }

    adapt() {

        let offset = 1334 * 0.5 - this.node_top.y;
        let gap = (cc.winSize.height - 1334) * 0.5
        // LogUtil.log("offset", offset);
        // this.node_top.y = cc.winSize.height * 0.5 - offset;

        this.node_top.y += gap;
        this.node_content.y += gap;

        this.node_rectBg.setContentSize(cc.winSize.width, cc.winSize.height);
    }

    initView() {
        this.initNickName();
    }

    initEvent() {
        this.node_backBtn.on(cc.Node.EventType.TOUCH_END, this.onClick, this);
        this.node_cashOutRecordBtn.on(cc.Node.EventType.TOUCH_END, this.onClick, this);
        this.node_cashOutBtn.on(cc.Node.EventType.TOUCH_END, this.onClick, this);
        if (!GameConst.isAuth) {
            mk.event.register(EVENT_TYPE.BACK_WxAuth, this.onWxAuthBack, this);
        }
        mk.event.register(EVENT_TYPE.UPDATE_CashNum, this.initCashNum, this);
    }

    onClick(event: cc.Event.EventTouch) {
        switch (event.currentTarget) {
            case this.node_backBtn:
                this.onClickBackBtn();
                break;
            case this.node_cashOutRecordBtn:
                this.onClickCashOutRecordBtn();
                break;
            case this.node_cashOutBtn:
                this.onClickCashOutBtn();
                break;
        }
    }

    /**初始化 */
    initCashNum() {
        // let num = Math.round((PlayerConst.cashNum * 100)) / 100;
        let num = Util.numberFixed(PlayerConst.cashNum, 2);
        this.label_cashNum.string = `¥ ${num}`;
    }

    /**初始化昵称 */
    initNickName() {
        this.label_nickName.string = Util.cutStr(PlayerConst.nickName, 12);
        this.label_nickName.node.active = true;
        this.node_wxIcon.x = this.label_nickName.node.x - this.label_nickName.node.width - 30;
    }

    /**初始化头像 */
    async initHead() {
        // let spr_wxIcon = this.node_wxIcon.getComponent(cc.Sprite);
        // LoaderUtil.loadHeadImg(this.node_wxIcon.getComponent(cc.Sprite), 42);
        // mk.loader.
    }

    /**初始化提现 */
    initCashOutItem() {
        if (this.node_cashOutItemList.childrenCount <= 0) {
            for (var i = 0; i < 5; i++) {
                let node_cashOutItem = PoolMgr.Inst.getPoolPrefab(NODEPOOLPREFABTYPE.CashOutItem);
                //LogUtil.log("node_cashOutItem", node_cashOutItem);
                let cashOutItem = node_cashOutItem.getComponent(CashOutItem);
                let cashOutItemState = this.getCashOutItemState(i);
                cashOutItem.init(i, cashOutItemState);
                this.node_cashOutItemList.addChild(node_cashOutItem);
            }
        }
        else {
            for (var i = 0; i < this.node_cashOutItemList.childrenCount; i++) {
                let node_cashOutItem = this.node_cashOutItemList.children[i];
                let cashOutItem = node_cashOutItem.getComponent(CashOutItem);
                let cashOutItemState = this.getCashOutItemState(i);
                cashOutItem.init(i, cashOutItemState);
            }
        }
    }

    /**获取提现状态
     * @param index 索引值
     */
    getCashOutItemState(index: number): CASHOUTITEMSTATE {
        let cashOutItemState = CASHOUTITEMSTATE.Normal;
        if (PlayerConst.clockInCashInfo) {
            let clockInCashInfo = PlayerConst.clockInCashInfo[index];

            if (clockInCashInfo) {
                if (clockInCashInfo.isWithdraw === 0) {
                    cashOutItemState = CASHOUTITEMSTATE.Normal;
                }
                else if (clockInCashInfo.isWithdraw === 1) {
                    cashOutItemState = CASHOUTITEMSTATE.CashOuted;
                }
                else {
                    cashOutItemState = CASHOUTITEMSTATE.CashOuting
                }
            }
        }
        return cashOutItemState;
    }

    /**点击返回按钮 */
    onClickBackBtn() {
        GameMgr.Inst.sendEvent(UI_NAME.CashOutUI, "点击返回按钮");

        // AudioMgr.Inst.playEffect(AUDIO_CLIP_NAME.buttonClick);
        mk.audio.playEffect("ef_button_click");
        
        mk.ui.closePanel("CashOutUI");
    }

    /**点击提现记录按钮 */
    onClickCashOutRecordBtn() {
        GameMgr.Inst.sendEvent(UI_NAME.CashOutUI, "点击提现记录按钮");
    }

    onClickCashOutBtn() {

        GameMgr.Inst.sendEvent(UI_NAME.CashOutUI, "点击提现按钮");

        if (!GameConst.isAuth) {
            mk.ui.openPanel("game/prefab/uiPanel/GuideAuthUI")
            return;
        }

        if (!this.curSelectCashOutItem) {
            EffectMgr.Inst.addTip("请选择提现档次");
            return;
        }

        let day = this.curSelectCashOutItem.day;
        let cashNum = this.curSelectCashOutItem.cashOutNum;

        if (PlayerConst.clockInDay < day) {
            EffectMgr.Inst.addTip(`还需打卡${day - PlayerConst.clockInDay}天，可以提现哦`)
        }
        else {
            if (PlayerConst.cashNum < cashNum) {
                let leftNum = Math.round((cashNum - PlayerConst.cashNum) * 10) / 10;
                EffectMgr.Inst.addTip(`还需${leftNum}元零钱，可以提现哦`)
            }
            else {
                HttpMgr.Inst.cash(cashNum, 1).then(() => {
                    HttpMgr.Inst.getClockInInfo();
                    DataMgr.Inst.updateMoneyNum(-cashNum);
                    EffectMgr.Inst.addTip("恭喜提现成功,等待到账");

                    GameMgr.Inst.sendEvent(UI_NAME.CashOutUI, `${PlayerConst.clockInDay}打卡提现成功`);
                    GameMgr.Inst.sendEventCp(UI_NAME.CashOutUI, `${PlayerConst.clockInDay}打卡提现成功`);

                    //提现操作
                }).catch((err) => {
                    // EffectMgr.Inst.addTip(`后台维护中,请稍后再试`)
                    EffectMgr.Inst.addTip(err.errmsg);
                });
            }
        }
    }

    setCurSelectItemBtn(cashOutItem: CashOutItem) {
        if (this.curSelectCashOutItem) {
            this.curSelectCashOutItem.cancelSelect();
        }
        this.curSelectCashOutItem = cashOutItem;
        this.curSelectCashOutItem.select();

        switch (this.curSelectCashOutItem.cashOutItemState) {
            case CASHOUTITEMSTATE.Normal:
                this.node_cashOutBtn.active = true;
                this.node_noCashOutBtn.active = false;
                this.node_taskCashOut.active = false;
                break;
            case CASHOUTITEMSTATE.CashOuting:
                this.node_cashOutBtn.active = false;
                this.node_noCashOutBtn.active = true;
                this.node_taskCashOut.active = false;
                break;
            case CASHOUTITEMSTATE.CashOuted:
                this.node_cashOutBtn.active = false;
                this.node_noCashOutBtn.active = true;
                this.node_taskCashOut.active = false;
                break;
        }
    }

    //自定义事件---------------------------------------------------------------------
    /**微信授权返回 */
    onWxAuthBack() {
        console.log("CashOutUI 微信授权返回");
        this.initHead();
        this.initNickName();
        mk.console.log("PlayerConst.headImgUrl", PlayerConst.headImgUrl);
        mk.console.log("PlayerConst.nickName111", PlayerConst.nickName);
        mk.event.remove(EVENT_TYPE.BACK_WxAuth, this.onWxAuthBack, this);
    }
}
