$(function(){
	getWithDrawType();
    /*var withDrawTypeVal = $.trim($("#withDrawType").val());
    selectWithDrawType(withDrawTypeVal);*/
    

    //全部提现
    $("#withdrawAllMoney").on("click", function(){
        $("#errorTip").html("");
        var useableMoney = $.trim($("#useableMoney").val());
        if( parseFloat(useableMoney) > 0 ) {
            $("#curWithdrawMoney").val(useableMoney);
        } else {
            moneyNotEnough("您当前无可提现余额，无法申请提现");
        }

    });

    //表单验证
    $("#submitWithdrawFormBtn").on("click", function(){
        verifyCurrentForm();
    });

});

/**
 * 提款限额设置:
 * 1:微信的2w限额，其他的5w;
 */
setWithdrawLimit();
function setWithdrawLimit(withDrawType){
    var poundage = $("#withDrawType").find("option:selected").attr("poundage");
    var poundageTip = "";
    if(parseFloat(poundage) > 0){
        poundageTip += '，每笔收'+ poundage +'元手续费';
    }
    if(withDrawType == "1"){//微信钱包
        $("#limitMoneyTip").html("备注：单笔提款限额<span id='maxLimit'>"+wxxian+"</span>元" + poundageTip);
    }else if(withDrawType == "2"){//银行卡提现
        $("#limitMoneyTip").html("备注：单笔提款限额<span id='maxLimit'>"+bankxian+"</span>元" + poundageTip);
    }else if(withDrawType == "3"){//快速银行卡提现
        $("#limitMoneyTip").html("备注：单笔提款限额<span id='maxLimit'>"+bankxian+"</span>元" + poundageTip);
    }else{
        $("#limitMoneyTip").html("备注：单笔提款限额<span id='maxLimit'>"+alixian+"</span>元" + poundageTip);
    }
}

//提现方式切换
function selectWithDrawType(val) {
  $("#errorTip").html("");
  $("#accountSelectId").show();
  
  if(val == "1"){
	  $("#alipayAccountSelect").css("display","none");
	  $("#bankCardSelect").css("display","none");
//      var isBindWx = $("#isBindWx").val();
      $("#weChatAccountSelect").css("display","block");
      
      var weChatAccountSelect=$("#weChatAccountSelect").val();
      if(weChatAccountSelect=="-1"){
    	  noWXAccountTip("您当前未添加微信账号，添加后才可使用微信提现");
      }
      /*if(isBindWx=="" || isBindWx == "2" ||isBindWx == "3"){//没有绑定微信
          showBindWxTip("您当前未绑定微信账号，绑定后才可以微信提现");
      }*/
  }else{

	  $("#weChatAccountSelect").hide();
	  
      if(val=="2" || val=="3"){
          $("#bankCardSelect").css("display","block");
          $("#alipayAccountSelect").css("display","none");
          
          var bankCardSelect=$("#bankCardSelect").val();
          if(bankCardSelect=="-1"){
              noBankCardTip("您当前未添加银行卡，添加后才可使用银行卡提现");
          }
      }else if(val=="4"){
          $("#bankCardSelect").css("display","none");
          $("#alipayAccountSelect").css("display","block");
          //没有支付宝帐号的情况
          var alipayAccountSelect=$("#alipayAccountSelect").val();
          if(alipayAccountSelect=="-1"){
              noAlipayAccountTip("您当前未添加支付宝帐号，添加后才可使用支付宝提现");
          }
      }
  }
  setWithdrawLimit(val);
}

/**
 * 切换银行卡
 * @param val
 */
function selectBankCard(val){
    if(val==="-1"){
        noBankCardTip("您当前未添加银行卡，添加后才可使用银行卡提现");
    }
}
/**
 * 切换支付宝帐号
 * @param val
 */
function selectAlipayAccount(val){
    if(val==="-1"){
        noAlipayAccountTip("您当前未添加支付宝帐号，添加后才可使用支付宝提现");
    }
}
/**
 * 切换微信账号
 * @param val
 */
function selectWeChatAccount(val){
    if(val==="-1"){
        noWeChatTip("您当前未添加微信账号，添加后才可使用微信账号提现");
    }
}

function moneyNotEnough(tipTxt) {
    layer.alert('<span style="color:#f39c13;">'+ tipTxt +'</span>', {
        title: "提示",
        icon: 0,
        skin: 'layer-ext-moon',
        btn: '我知道了',
        yes: function(index, layero){
            //按钮的回调
            layer.close(index);
        }
    });
}
//微信
function noWXAccountTip(tipTxt) {
    layer.alert('<span style="color:#f39c13;">'+ tipTxt +'</span>', {
        title: "提示",
        icon: 0,
        skin: 'layer-ext-moon',
        btn: '立即去添加',
        yes: function(index, layero){
            //按钮的回调
            layer.close(index);
            gotoWeixinAccount();
        }
    });
}

function noBankCardTip(tipTxt) {
    layer.alert('<span style="color:#f39c13;">'+ tipTxt +'</span>', {
        title: "提示",
        icon: 0,
        skin: 'layer-ext-moon',
        btn: '立即去添加',
        yes: function(index, layero){
            //按钮的回调
            layer.close(index);
            gotoBankAccount();
        }
    });
}

function noAlipayAccountTip(tipTxt) {
    layer.alert('<span style="color:#f39c13;">'+ tipTxt +'</span>', {
        title: "提示",
        icon: 0,
        skin: 'layer-ext-moon',
        btn: '立即去添加',
        yes: function(index, layero){
            //按钮的回调
            layer.close(index);
            gotoAlipayAccount();
        }
    });
}

/**
 * 提交方式和提现账号信息通过API应用用ajax去获取然后显示在页面上
 */
function getWithDrawType(){
	$.ajax({
        url: banklist,
        data:{
        	pf:1
        },
        dataType: "json",
        async: true,
        type: "POST",
        xhrFields: {
            withCredentials: true
        },
       	crossDomain: true,
        beforeSend: function() {},
        success: function(data) {
        	var typeHtml
    		$.each(data.drawTypeSettings, function(index, item){
//		        console.log("选择类型",item)
				if(item.type == '1' && item.enable =="on"){
					typeHtml += '<option value="'+1+'" poundage="'+item.poundage+'" >微信钱包</option>'
				}else if(item.type == '3' && item.enable =="on"){
					typeHtml += '<option value="'+3+'" poundage="'+item.poundage+'">银行卡</option>' 
				}else if(item.type == '4' && item.enable =="on"){
					typeHtml += '<option value="'+4+'" poundage="'+item.poundage+'">支付宝提现</option>'
				}
				 
			})
			$("#withDrawType").append(typeHtml)
			
			//提现账号设置
			var withDrawTypeVal = $.trim($("#withDrawType").val());
        	console.log("当前提现方式："+withDrawTypeVal);
    		selectWithDrawType(withDrawTypeVal);
    		
    		// 微信
        	var weixinHtml
        	if(data.weixinDrawAccountList != undefined && data.weixinDrawAccountList != ''){
        		$.each(data.weixinDrawAccountList, function(index, item){
    				weixinHtml= '<option value="'+item.id+'">'+item.bankCodeName+'</option>'
            		$("#weChatAccountSelect").append(weixinHtml)
            	})
        	}else{
            	weixinHtml= '<option value="-1">暂无微信账号</option>'
            	$("#weChatAccountSelect").append(weixinHtml)
            }
        	
        	// 支付宝
        	var aliPayHtml
        	if(data.aliPayAccountList != undefined && data.aliPayAccountList != ''){
        		$.each(data.aliPayAccountList, function(index, item){
            		aliPayHtml= '<option value="'+item.id+'">'+item.bankCodeName+'('+item.account+')</option>' 
            		$("#alipayAccountSelect").append(aliPayHtml)
        		})
        	}else{
    			aliPayHtml= '<option value="-1">暂无支付宝账号</option>'
    			$("#alipayAccountSelect").append(aliPayHtml)
    		}
        	
        	// 银行卡
        	var bankCardHtml
        	if(data.bankCardList != undefined && data.bankCardList != ''){
        		$.each(data.bankCardList, function(index, item){
            		bankCardHtml= '<option value="'+item.id+'">'+item.bankCodeName+'('+item.account+')</option>' 
            		$("#bankCardSelect").append(bankCardHtml)	
            	})
        	}else{
        		bankCardHtml= '<option value="-1">暂无银行卡</option>'
        		$("#bankCardSelect").append(bankCardHtml)
        	}
        },
        complete: function() {
        },
        error: function(e) {
            layer.msg("请求出错,请刷新后重试！", {icon : 2,shade : [ 0.4, '#000' ],time : 2000});
        }
    });
}


/**
 * 表单验证
 * 1、是否有余额
 * 2、是否实名认证：必须完成实名认证，才可以申请提现
 * 3、提现方式验证：如果是微信必须绑定微信账号；如果是银行卡必须有银行卡才行
 * 4、提现金额验证：最多允许输入小数点后二位；不可大于可提现余额；提现金额扣除手续费后要大于等于1元；不能大于提现的最大限额
 * 5、交易密码验证：是否开启；是否输入
 */
function verifyCurrentForm() {
    var icon = "<i class='fa fa-times-circle'></i>";
    $("#errorTip").html("");

    var useableMoney = $.trim($("#useableMoney").val());
    if( parseFloat(useableMoney) > 0 ) {
        var isRealNameAuthen = $.trim($("#isRealNameAuthen").val());
        if(isRealNameAuthen == "false"){
            $("#errorTip").html(icon+"必须实名认证成功后才可提现，请先实名认证");
        }else{
            var withdrawType = $("#withDrawType").val();
            
            if(withdrawType == "1"){
            	$("#bankCardSelect").val("");
            	$("#alipayAccountSelect").val("");
            	verifyRestElement();
            }else if(withdrawType == "3"){
            	$("#weChatAccountSelect").val("");
            	$("#alipayAccountSelect").val("");
                //没有银行卡的情况
                var bankCardSelect=$("#bankCardSelect").val();
                if(bankCardSelect=="-1"){
                    noBankCardTip("您当前未添加银行卡，添加后才可使用银行卡提现");
                }else{
                    verifyRestElement();
                }
            }else if(withdrawType == "4"){
                //没有支付宝帐号的情况
            	$("#weChatAccountSelect").val("");
            	$("#bankCardSelect").val("");
                var alipayAccountSelect=$("#alipayAccountSelect").val();
                if(alipayAccountSelect=="-1"){
                    noAlipayAccountTip("您当前未添加支付宝帐号，添加后才可使用支付宝提现");
                }else{
                    verifyRestElement();
                }
            }else{//withdrawType类型未知
                $("#errorTip").html(icon+"类型未知，请联系网站管理员");
            }
        }
    } else {
        moneyNotEnough("您当前无可提现余额，无法申请提现");
    }
}

function verifyRestElement() {
    var icon = "<i class='fa fa-times-circle'></i>";
    var useableMoney = parseFloat($.trim($("#useableMoney").val()));//可提现余额
    var curWithdrawMoney = $.trim($("#curWithdrawMoney").val());
    var moneyReg = /^[1-9]\d*(\.\d{1,2})?$|^0(\.\d{1,2})?$/;
   
    console.log($.trim($("#weChatAccountSelect").val()), $.trim($("#bankCardSelect").val()), $.trim($("#alipayAccountSelect").val()));
    if(curWithdrawMoney == ""){
        $("#errorTip").html(icon+"请输入提现金额");
    }else{
        if(curWithdrawMoney > useableMoney){
            $("#errorTip").html(icon+"可提现余额不足");
            return false;
        }else{
            if(moneyReg.test(curWithdrawMoney)){
                //可提现余额足够，提现金额扣除手续费后要大于等于1元且不能大于等于提现的最大限额
                var poundage = $("#withDrawType").find("option:selected").attr("poundage");
                
                var maxLimitTxt = $.trim($("#maxLimit").html());
                var maxLimit = parseFloat(maxLimitTxt)*10000;
//                console.log("手续费："+poundage+";最大限额："+maxLimit+";类型："+ typeof maxLimit);
                if( parseFloat(curWithdrawMoney) - parseFloat(poundage) < 1 ){
                    $("#errorTip").html(icon+"提现金额扣除手续费后不能小于1元~");
                    return false;
                }
                if(parseFloat(curWithdrawMoney) >= maxLimit){
                    $("#errorTip").html(icon+"提现金额不能大于等于提现的最大限额");
                    return false;
                }

                var isOpenTradePaaword = $.trim($("#isOpenTradePaaword").val());
                var tradePassword = $.trim($("#tradePassword").val());
                if(isOpenTradePaaword == ""){
                    $("#errorTip").html(icon+"请先开启交易密码，开启交易密码才可提现");
                }else{
                    if(tradePassword == ""){
                        $("#errorTip").html(icon+"请输入交易密码");
                    }else{
                    	var layerindex = '';
						$.post($("#withdrawCashForm").attr("action"),$("#withdrawCashForm").serialize(),function(data){
							 if(data.code==1){
                                   //成功样式
                                   parent.layer.alert('<span style="color:#27c5ab;">提现成功，提现进度可在提现记录查看！</span>', {
                                       title: "提现成功",
                                       icon: 1,
                                       skin: 'layer-ext-moon',
                                       btn: '查看提现记录',
                                       yes: function(index, layero){
                                           //按钮的回调
                                           window.location.reload();//刷新提现记录查询页面
                                           parent.layer.close(index);
                                           addFrame( txjl,"1133","提现记录");
                                       },
                                       cancel: function(index, layero){//右上角关闭按钮回调
                                           window.location.reload();//刷新结算记录查询页面
                                       }
                                   });
                               }else{
                                   //报错信息
									setTimeout(function(){
										parent.layer.close(layerindex);
									}, 2000);
                                   $("#errorTip").html(icon + data.msg);
                               }
						})
                    	
                    }
                }
            }else{
                $("#errorTip").html(icon+"提现金额请输入数字，最多保留两位小数");
            }
        }
    }
}