/**
 * create by robot
 * date Thu Sep 12 16:16:36 CST 2019
 */



var table, form;

var pageIndex=1;
$(document).ready(function(){
	//调用查询
	pageIndex=StringUtil.getQueryString('pageIndex');
	if(pageIndex==undefined||pageIndex==null){
		pageIndex=1;
	}

	//绑定hover操作
	$(document).on('mouseenter','.listOperaters',function(){
		$(this).children(".ops_itemDiv").show();
		var width=15;
		$(this).children('div').find('li').each(function(){
			//获取li宽度
			width+=$(this).width();
		});
		$(this).children('div').width(width);
	})
	$(document).on('mouseleave','.listOperaters',function(){
		$(this).children(".ops_itemDiv").hide();
	});

	//日历控件
	layui.use(['layer', 'form', 'laydate', 'table'], function() {
		var layer = layui.layer;
		var laydate = layui.laydate;
		form = layui.form;
		table = layui.table;
		laydate.render({
			elem: '#date1', //指定元素
			format:'yyyy-MM-dd 00:00:00'
		});
		laydate.render({
			elem: '#date2', //指定元素
			format:'yyyy-MM-dd 23:59:59'
		});

		form.render();

		//执行一个 table 实例
		table.render({
			elem: '#demo'
			, id: 'idTest'
			, url: ctx + '/cash/page' //数据接口
			, autoSort: false
			, where: {
				column: 'createDt'
				, asc: false
			}
			, response: {
				statusName: 'code' //数据状态的字段名称，默认：code
				, countName: 'count' //数据总数的字段名称，默认：count
				, dataName: 'data' //默数据列表的字段名称，认：data
				, statusCode: 200
			}
			, parseData: function (res) { //res 即为原始返回的数据
				return {
					"code": res.code, //解析接口状态
					"msg": res.message, //解析提示文本
					"count": res.data.total, //解析数据长度
					"data": res.data.records //解析数据列表
				};
			}
			, request: {
				pageName: 'current' //页码的参数名称，默认：page
				, limitName: 'size' //每页数据量的参数名，默认：limit
			}
			, title: 'app首页菜单表'
			, page: true //开启分页
			, toolbar: '#toolBar' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
			, defaultToolbar: ['filter']
			, cols: [[ //表头
				{type: 'checkbox'}
				, {field: '', title: '序号', type: 'numbers'}
				, {field: 'userId', title: '用户ID', minWidth: 86, align: "center"}
				, {field: 'userName', title: '用户名', minWidth: 86, align: "center"}
				, {field: 'logo', title: '头像', minWidth: 80, templet: '#imgTemp', align: "center", hide: true}
				// , {field: 'alias', title: '商户简称', width: 150, align: "center"}
				, {field: 'phone', title: '手机号', minWidth: 120, align: "center"}
				, {field: 'cashTotalAmt', title: '已提现总额', minWidth: 100, align: "right"}
				, {field: 'totalProfit', title: '总分润', minWidth: 86, align: "right", templet: function(d) {

						return (null2Zero(d.totalProfit) + null2Zero(d.totalShareMoney)).toFixed(2);
					}}
				, {field: 'totalProfit', title: '剩余可提现(实时)', width: 140, align: "right", templet: function(d) {

						return (null2Zero(d.totalProfit) + null2Zero(d.totalShareMoney) - null2Zero(d.cashTotalAmt)).toFixed(2);
					}}
				, {field: 'cashAmt', title: '申请提现金额', minWidth: 120, align: "right"}
				, {field: 'virRealCashAmt', title: '实际到账', minWidth: 100, align: "right"}
				, {field: 'baseServiceCharge', title: '基本手续费', minWidth: 100, align: "right"}
				, {field: 'rate', title: '税率(%)', minWidth: 86, align: "right"}
				, {field: 'ratioCharge', title: '税费', minWidth: 100, align: "right"}
				, {field: 'virTotalCharge', title: '总手续费', minWidth: 100, align: "right"}
				, {field: 'remark', title: '备注', width: 150, align: "center"}
				, {field: 'status', title: '状态', width: 100, align: "center", templet: function (d) {
						if(d.status == '0'){
							return '<span style="color: #FF0000">审核中</span>';
						}else if(d.status == '1'){
							return '<span style="color: #00B83F">提现成功</span>';
						}else if(d.status == '2'){
							return '<span style="color: #2f3e44">提现失败</span>';
						}

						return '';
					}}
				, {field: 'cashNumber', title: '提现单号', width: 150, align: "center", hide: true}
				, {field: 'accountName', title: '支付宝账户名', width: 100, align: "center"}
				, {field: 'accountNo', title: '支付宝账号', width: 150, align: "center"}
				, {field: 'updator', title: '审核人', width: 150, align: "center", hide: true}
				, {field: 'type', title: '提现类型', width: 100, templet: function (d) {
						if(d.type == '0'){
							return '粉丝分润';
						}else if(d.type == '1'){
							return '推广分润';
						}else if(d.type == '2'){
							return '银行卡提现';
						}

						return '其他';
					}}
				, {
					field: 'createDt',
					title: '创建时间',
					width: 160,
					sort: true,
					hide: false,
					templet: "<div>{{layui.util.toDateString(d.createDt, 'yyyy-MM-dd HH:mm:ss')}}</div>"
				}
				, {
					field: 'updateDt',
					title: '审核时间',
					width: 165,
					sort: true,
					hide: false,
					templet: "<div>{{layui.util.toDateString(d.updateDt, 'yyyy-MM-dd HH:mm:ss')}}</div>"
				}
				, {fixed: 'right', title: '操作', width: 260, align: 'left', toolbar: '#barDemo'}
			]]
		});

		table.on('tool(test)', function(obj) {
			var that = this, data = obj.data;
			switch (obj.event) {
				case 'auditPass':
					auditPass(data);
					break;
				case 'auditSuccess':
					auditSuccess(data);
					break;
				case 'auditRefuse':
					auditRefuse(data.id);
					break;
			}
		})

		table.on('toolbar(test)', function(obj) {
			var checkStatus = table.checkStatus(obj.config.id);
			switch(obj.event){
				case 'search':
					queryCash2()
					break;
				case 'batchPass':
					var idArr = [];
					checkStatus.data.forEach(function(item) {
						idArr.push(item.id);
					});

					batchPass(idArr);
					break;
			}
		})
	});
	//行选中事件
	$("#allCheck").find("span").click(function() {
		$(this).toggleClass('checked');
		if($(this).hasClass('checked')){
			//所有列选中
		  $(".checker").find("span").each(function () {
		         $(this).addClass("checked");
		    })
		}else{
			//所有列取消选中
			$(".checker").find("span").each(function () {
				 $(this).removeClass("checked");
		    })
		}
	});

	//单个选中
	$(document).on('click','.checkeBox span',function() {
		$(this).toggleClass('checked');
		//设置头部事件
		var length=$('.checkeBox span').length;
		var count=0;
		$(".checkeBox").find("span").each(function () {
	        if($(this).hasClass("checked")){
	        	count++;
	        }
	   })
		//全选
	   if(count==length){
		   $("#allCheck").find("span").addClass('checked');
	   }else{
		   $("#allCheck").find("span").removeClass('checked');
	   }
	})
	//左右div高度相等
	var left_content_height = $(".right-content").height();
	$(".left-content").height(left_content_height+35);
	var sub_left_height=$(".res-menu").height(left_content_height-60);

	let data = {"userId":$("#userId").val(),"beginTime":$("#date1").val(),"endTime":$("#date2").val()};
	loadOrderData(data);
});

function loadOrderData(data){
	$.ajax({
		url : ctx + '/cash/otherData',
		type : "get",
		data : data,
		dataType : "json",
		success : function(res) {
			if(res.code == 200){
				// $("#transAmountCount").text(res.data.transAmountCount || "0.00");
				$("#shareAmountCount").text(res.data.shareAmountCount || "0.00");
				$("#fansAmountCount").text(res.data.fansAmountCount || "0.00");
				$("#useCashAmtCount").text(res.data.useCashAmtCount || "0.00");
				$("#inCashAmtCount").text(res.data.inCashAmtCount || "0.00");
				$("#profitAmountCount").text(res.data.profitAmountCount || "0.00");
			}
		},
		error : function(err) {

		}
	});
}


function batchPass(idArr) {
	if (idArr == null || idArr.length === 0) {
		layer.msg("至少选择一条记录");
		return;
	}

	layer.open({
		type: 1,
		closeBtn: 1,
		title: '批量通过',
		offset: 'm', //具体配置参考：offset参数项
		area: ['300px', '180px'],
		content: '<div style="padding:10px;" class="textc mt20">批量通过确认？</div>',
		btn: ['确认','取消'],
		btnAlign: 'r', //按钮居中
		shade: 0.3, //不显示遮罩
		yes: function() {
			var index = layer.load(1, {shade: [0.1, '#000']});
			$.ajax({
				url: ctx + "/cash/batchPass"
				, type: 'post'
				, data: {
					'ids': idArr
				}
				, success: function (d) {
					layer.close(index);
					if (d.code == 200) {
						queryCash2()
					} else {
						layer.closeAll();
						layer.msg(d.message)
					}
				}
				, error: function (req, textStatus, errorThrown) {
					layer.msg(textStatus)
				}
			})
		}
	});
}

function queryCash2() {
	table.reload("idTest", {
		where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
			userName:$('#userName').val()
			, status:$('#status').val()
			, type:$('#type').val()
			, userId:$("#userId").val()
			, phone:$("#phone").val()
			, beginTime:$("#date1").val()
			, endTime:$("#date2").val()
		}
	}, true);
	let data = {"userId":$("#userId").val(),"beginTime":$("#date1").val(),"endTime":$("#date2").val()};
	loadOrderData(data);
}

//初始化新增
function initAddCash(){
	window.location=ctx+'/cash/queryCashDetails?pageIndex='+pageIndex;
}

//初始化修改
function showCashDetails(id){
	window.location=ctx+'/cash/queryCashDetails?id='+id+'&pageIndex='+pageIndex;
}

//头部编辑
function initEditCash(){
	var count=0;
	var id=0;
	$(".checkeBox").find("span").each(function () {
         if($(this).hasClass("checked")){
        	 count++;
        	 id=$(this).data('id');
         }
    })
    if(count>1){
    	layer.msg('只能选中一行记录进行操作!');
    	return ;
    }
	 if(count==0){
    	layer.msg('请选中一行记录!');
    	return ;
	  }
	 if(id>0){
	  showCashDetails(id);
	 }
}
//头部删除
function initBatchDeleteCash(){
	var count=0;
	$(".checkeBox").find("span").each(function () {
         if($(this).hasClass("checked")){
        	 count++;
         }
    })

	 if(count == 0){
    	layer.msg('请选中一行记录!');
    	return ;
	  }


	layer.open({
		type: 1,
		closeBtn: 1,
		title: '提示',
		offset: 'm', //具体配置参考：offset参数项
		area: ['300px', '180px'],
		content: '<div style="padding:10px;" class="textc mt20">确认删除吗？</div>',
		btn: ['确认','取消'],
		btnAlign: 'r', //按钮居中
		shade: 0.3, //不显示遮罩
		yes: function() {
			layer.closeAll();
			deleteBatchCash();
		}
	});

}
//批量删除
function deleteBatchCash(){

	$(".checkeBox").find("span").each(function () {
        if($(this).hasClass("checked")){
        	var id=$(this).data('id');
        	deleteCash(id,false);
        	layer.msg('删除成功!');
        }
   })
}

//审核通过
function auditPass(data){
	layer.open({
		type: 2,
		area: ['400px', '300px'],
		content: ctx + "/cash/pass/" + data.id,
		shade: 0.3, //不显示遮罩
	});
}

function realAuditPass(id){
	$.ajax({
		url:ctx+'/cash/realAuditPass',
		data:{
			'id':id,
			'remark': $('textarea[id="remark"]').val()
		},
		dataType:'json',
		type:'post',
		success:function(res){
			layer.msg('提现申请已通过');
			queryCash2(pageIndex);
		},
		error:function(res){
			layer.msg('通过失败，系统繁忙请稍后再试');
			queryCash2(pageIndex);
		}
	})

}
//审核拒绝
function auditRefuse(id){
	layer.open({
		type: 1,
		closeBtn: 1,
		title: '提示',
		offset: 'm', //具体配置参考：offset参数项
		area: ['300px', '180px'],
		content: '<div style="padding:10px;" class="textc mt20">拒绝原因：<input style="border:0.5px solid #C0C0C0; height:25px;"  type="text" id="reason"></div>',
		btn: ['确认','取消'],
		btnAlign: 'r', //按钮居中
		shade: 0.3, //不显示遮罩
		yes: function() {
			realauditRefuse(id,$('#reason').val());
		}
	});
}
//审核通过
function auditSuccess(obj){
	var index = layer.confirm('确定审核通过?', {icon: 3, title:'提示'}, function(index){
		realAuditSuccess(obj.id);
	});
}
function realAuditSuccess(id){
	var index = layer.load(1, {shade: [0.1, '#000']});
	$.ajax({
		url:ctx+'/cash/auditSuccess',
		data:{
			'id':id,
			"status":"1",
		},
		dataType:'json',
		type:'post',
		success:function(res){
			layer.closeAll();
			if(res.code == 200){
				layer.msg(res.message,{icon:1})
				queryCash2();
			}else{
				layer.msg("操作失败",{icon:2})
			}
		},
		error:function(res){
			layer.msg('通过失败，系统繁忙请稍后再试');
		}
	})
}

function realauditRefuse(id,reason){
	if(StringUtil.isBlank(reason)){
		layer.msg('请输入拒绝原因');
		return;
	}
	$.ajax({
		url:ctx+'/cash/realauditRefuse',
		data:{
			'id':id,
			"reason":reason,
		},
		dataType:'json',
		type:'post',
		success:function(res){
			layer.closeAll();
			layer.msg('提现申请已拒绝');
			queryCash2(pageIndex);
		},
		error:function(res){
			layer.closeAll();
			layer.msg('通过失败，系统繁忙请稍后再试');
			queryCash2(pageIndex);
		}
	})
}

//时间格式化处理
function dateFtt(fmt,date)
{ //author: meizz
  var o = {
    "M+" : date.getMonth()+1,                 //月份
    "d+" : date.getDate(),                    //日
    "h+" : date.getHours(),                   //小时
    "m+" : date.getMinutes(),                 //分
    "s+" : date.getSeconds(),                 //秒
    "q+" : Math.floor((date.getMonth()+3)/3), //季度
    "S"  : date.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}
