/**
 * 租赁
 */
import gameToast from "../Network/gameToast"
import date from "../Unit/date";
cc.Class({
    extends: cc.Component,

    properties: {

        inputInviteValue: {
            default: 1,
            visible: false
        },

        //1 对应3个月，2对应1年，3对应5年
        toggleInputValue: {
            default: '2',
            visible: false
        },
        totalPriceLabel: {
            default: null,
            type: cc.Label,
            serializable: true
        },
        totalPriceValue: {
            default: 0,
            visible: false
        },

        ToastParent: {
            default: null,
            type: cc.Node,
            serializable: true
        },
        //输入节点
        inputContainer: {
            default: null,
            type: cc.Node,
            serializable: true
        },

        toggle1: {
            default: null,
            type: cc.Toggle,
            serializable: true
        },

        toggle2: {
            default: null,
            type: cc.Toggle,
            serializable: true
        },

        toggle3: {
            default: null,
            type: cc.Toggle,
            serializable: true
        },

        //这个显示的时候，拦截输入
        blockInput: {
            default: null,
            type: cc.Node,
            serializable: true
        },
        leaseFarmlandInfoNode: {
            default: null,
            type: cc.Node,
            serializable: true,
            visible: false,
            toolTip: "操作的土地对象,初始化时候传入"
        },
        //轮询土地状态
        AutoGetLandData: null,
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    // start() {

    // },

    onOpenInfo() {
        this.node.active = true;

    },

    //初始化时候需要初始化一次默认值
    onToggleInput(value, evnentData) {
        // console.log(value.isChecked, evnentData);
        this.toggleInputValue = evnentData;
        this._updatePrice();
    },

    inputLeaseValue(value, e) {

        var numberTemp = new RegExp("^[A-Za-z0-9]+$");
        let limitValue = 100;
        if (GlobalD.GameSetting && GlobalD.GameSetting.maxLeaseMulti) {
            limitValue = GlobalD.GameSetting.maxLeaseMulti;
            console.log("配置的数据limitValue:",limitValue);
        }
        if (numberTemp.test(value)) {
            if (Number(value) >= 1 && Number(value) <= limitValue) {
                this.inputInviteValue = Number(value);
            } else if (Number(value) > limitValue) {
                //限制只能输入100
                this.inputInviteValue = limitValue;
                this.inputContainer.getComponent(cc.EditBox).string = this.inputInviteValue;
            } else {
                this.inputInviteValue = 1;
                this.inputContainer.getComponent(cc.EditBox).string = this.inputInviteValue;
            }
        } else {
            this.inputInviteValue = 1;
            this.inputContainer.getComponent(cc.EditBox).string = this.inputInviteValue;
            console.log("请输入整数的倍数", this.inputInviteValue);
        }
        this._updatePrice();
    },

    _updatePrice() {
        //this.inputInviteValue 默认是1倍
        // console.log( this.inputInviteValue);
        let _configLandInfo = this.leaseFarmlandInfoNode.getComponent("LeaseFarmlandInfo").configLandInfo

        switch (this.toggleInputValue) {
            case "1": //700
                this.totalPriceValue = _configLandInfo.rental1 * this.inputInviteValue;
                this.totalPriceLabel.string = this.totalPriceValue ;
                break;
            case "2": //2500
                this.totalPriceValue = _configLandInfo.rental2 * this.inputInviteValue;
                this.totalPriceLabel.string = this.totalPriceValue ;
                break;
            case "3": //5000
                this.totalPriceValue = _configLandInfo.rental3 * this.inputInviteValue;
                this.totalPriceLabel.string = this.totalPriceValue ;
                break;
            default:
                console.error("this.toggleInputValue 不是1 2 3！", this.toggleInputValue);
                break;
        }

    },

    /**
     * 显示面板时候，设置一下初始化数据
     */
    onInitLeaseInfo(multiple) {
        //这里处理倍数
        this.inputInviteValue = multiple;
        this.inputContainer.getComponent(cc.EditBox).string = this.inputInviteValue;
        this._updatePrice();
    },

    //租赁支付
    onLeaseInfo() {
        console.log('支付总额：' + this.totalPriceValue);
        if (!GlobalD.dapp) {
            console.error("onBindInviteInfo warn,dapp未初始化！");
            return;
        }
        let _self = this;
        //cntAmount,payType,itemType,callback
        let _configLandInfo = this.leaseFarmlandInfoNode.getComponent("LeaseFarmlandInfo").configLandInfo

        //租赁的itemType 要处理一下
        let _itemType = this.toggleInputValue + "or" + _configLandInfo.id;

        GlobalD.GameData.payCNT(this.totalPriceValue, 1, _itemType, (data) => {
            console.log("土地支付:", this.totalPriceValue, "== playType=", 1, ",item_type==", _itemType);
            console.log("支付data:", data);
            const [err, tx] = data;

            if (err === null) {
                // TODO 成功, 支付为链上操作，需要提供回调接口给这边服务端确认交易成功后修改购买订单结果
                console.log(tx) // 交易hash，唯一标识符
                let _leaseFarmlandInfo = this.leaseFarmlandInfoNode.getComponent("LeaseFarmlandInfo");
                //todo 如果是土地租赁，轮询土地状态 
                if (this.AutoGetLandData) {
                    this.unschedule(this.AutoGetLandData);
                    this.AutoGetLandData = null;
                }
                this.AutoGetLandData = () => {
                    GlobalD.GameData.getLandState({
                        landId: _configLandInfo.id,
                        callback: (value) => {
                            console.log("轮询土地数据:" + JSON.stringify(value.msg));
                            if (0 === value.code) {
                                let _landData = value.data;
                                let _leaseLandInfo = _leaseFarmlandInfo.leaseLandInfo
                                //如果是空的，说明没有创建过土地
                                if (_leaseLandInfo == null) {
                                    this.unschedule(this.AutoGetLandData);
                                    // console.log("轮询到土地购买成功！");
                                    GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "土地购买成功！", 2);
                                    //解锁土地操作
                                    _leaseFarmlandInfo.setLeaseLandInfo(_landData, true);
                                    this.onClose();
                                } else {
                                    //根据update时间判断
                                    if (!date.datesIsEqual(_leaseLandInfo.updateTime, _landData.updateTime)) {
                                        //如果不是空，判断为续租
                                        GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "续租土地成功！", 2);
                                        //续租土地时候， 只更新 租赁相关参照
                                        let _oldLeaseLandInfo = Object.assign({}, _leaseLandInfo, {
                                            isLease: _landData.isLease,
                                            isPlant: _landData.isPlant,
                                            leaseDays: _landData.leaseDays,
                                            leaseDaysMill: _landData.leaseDaysMill,
                                            leaseDaysRemaining: _landData.leaseDaysRemaining,
                                            leaseTime: _landData.leaseTime,
                                            rentalExpenses: _landData.rentalExpenses,
                                            updateTime: _landData.updateTime
                                        });
                                        // console.log("续租之后的信息：", _landData, _leaseLandInfo, _oldLeaseLandInfo);
                                        _leaseFarmlandInfo.setLeaseLandInfo(_oldLeaseLandInfo, true);
                                        this.onClose();
                                    }
                                }

                            }
                        }
                    });
                };
                this.schedule(this.AutoGetLandData, 5);
            } else {
                console.log(err)
            }
        });
        // GlobalD.dapp.bindParent(_self.inputInviteValue).then((data) => {
        //     if (data.err === null) {
        //         // 返回成功，见下面消息体
        //         console.log(data.res)
        //         //绑定成功时候，隐藏输入框，设置父节点
        //         GlobalD.Dapp.UserInfo.parent = data.res;
        //         _self.parentInviteValue.string = GlobalD.Dapp.UserInfo.parent.invite_code;
        //         //如果存在父节点，隐藏输入框
        //         _self.inputContainer.active = false;


        //     } else {
        //         //TODO 服务错误
        //         console.log(data.err)
        //     }
        // })
    },

    onClose() {
        // if (this.AutoGetLandData) {
        //     this.unschedule(this.AutoGetLandData);
        //     this.AutoGetLandData = null;
        // }
        this.node.destroy();
    },
    onDestroy() {
        if (this.AutoGetLandData) {
            this.unschedule(this.AutoGetLandData);
            this.AutoGetLandData = null;
        }
    }

});
