var select = 0;//0代表选择table，1代表选择柱状图
var isfirst = 0;// isfirst=0代表初始化调用
var alluin = "";
var m_strRedPacket = [];//当前查询数据缓存
var alluserid = "";
var m_RedPacageType = "";//红包类型
var m_RevoiceIssue = "";//收入支出类型
var m_Rednum = ""; //红包数量
var m_Zhuannum = ""; //转账数量
var m_Strsendsourceissuenum = "";//收到数量
var m_Strsendsourcerevoicenum = "";//支出数量
var m_IssAlljine = "";//发出金额总计
var m_RevoiceAlljine = "";//收到金额总计
$(function () {
    $("#myPageAlert").hide();
    listcss();
    //获取部门
    var paraJson = $.toJSON({
        type: "data"
    });
    
    dataObj.getdeptbyauth(paraJson);
});

function AsyncGetDeptByAuthResult(jsonResult) {
    if (jsonResult.success) {
        var deptlist = jsonResult.deptlist;
        $("#selDept").append("<option value='" + jsonResult.myself.userid + "' tag='user' name='" + jsonResult.myself.username + "'>本人</option>");
        if (jsonResult.deptlist.length > 0) {
            for (var index in deptlist) {
                var item = deptlist[index];
                $("#selDept").append("<option value='" + item.dgid + "'>" + item.dgname + "</option>");
            }
        } else {
            $("#selDept").hide();
        }
        BindCompanyUsers();
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
    $(".loadingcover").hide();
    $(".loading").hide();
}

function BindCompanyUsers() {
	var paraJson;
	$("#selUser").empty();
	alluserid = "";
	var selectDom = $("#selDept").find("option:selected");
	if (selectDom.attr("tag") == "user") {
		$("#selUser").append("<option value='" + selectDom.val() + "' tag='user' selected='true'>" + selectDom.attr("name") + "</option>");
		alluserid = selectDom.val();
		BindChat();
	} else {
		$("#selUser").append("<option value=''>客服</option>");
		paraJson = $.toJSON({
			deptid: $("#selDept").val()
		});
		dataObj.getpersonbydeptid(paraJson);
	}
}

//绑定人员回调
function AsyncGetPersonByDeptidResult(jsonResult) {
	var selUser = $("#selUser");
	if (jsonResult.success) {
		var jsonObj = jsonResult.user;
		var jsonList = jsonObj.list;
		var currentId = jsonObj.loginuid;
		alluserid = "";
		for (var i = 0; i < jsonList.length; i++) {
			var item = jsonList[i];
			alluserid += item.userid + ",";
			selUser.append("<option value='" + item.userid + "'>" + item.name + "</option>");
		}
		alluserid = alluserid.substr(0, alluserid.length - 1);
		BindChat();
	} else {
		ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
	}
}


//绑定微信下拉框
function BindChat() {
    uid = $("#selUser").val();
    if ("" == uid) {
        $("#selChat").empty();
        $("#selChat").append("<option value=''>微信号</option>");
        if (isfirst == 0) {
            isfirst = 1;
            BindData();
        }
    } else {
        $(".loading").show();
        $(".loadingcover").show();
        var strParaJson = $.toJSON({
            uid: uid
        });
        dataObj.getwechatsallbyuid(strParaJson);
    }
}

//微信下拉框回调
function AsyncGetWeChatsAllByUidReportResult(jsonResult) {
    $("#selChat").empty();
    $("#selChat").append("<option value=''>微信号</option>");
    alluin = "";
    for (index in jsonResult.result.list) {
        var obj = jsonResult.result.list[index];
        if (obj.wremark == null || obj.wremark.trim() == "") {
            $("#selChat").append("<option value='" + obj.uin + "' >" + obj.nickname + "</option>");
        } else {
            $("#selChat").append("<option value='" + obj.uin + "' >" + obj.nickname + "(" + obj.wremark + ")" + "</option>");
        }

        alluin += obj.uin + ",";
    }
    alluin = alluin.substr(0, alluin.length - 1);

    if (isfirst == 0) {
        isfirst = 1;
        BindData();
    } else {
        $(".loading").hide();
        $(".loadingcover").hide();
    }
}

// 绑定微信号列表
function BindData() {
    //验证
    var myDate = new Date();//当前日期
    var taday = myDate.getTime();
	var time1 = Date.parse(new Date("20" + $("#txtTimeFrom").val()));
	var time2 = Date.parse(new Date("20" + $("#txtTimeTo").val()));
	var diff = parseInt((time2 - time1) / 1000 / 3600 / 24);
	if (diff > 30) {
		ShowError("myPageAlert", "最多只能统计30天的结果");
		return;
	} else if (diff < 0) {
		ShowError("myPageAlert", "起始时间不能大于终止时间");
		return;
	} else if (time1 > taday || time2 > taday) {
	    ShowError("myPageAlert", "选择的时间不能大于今天!");
	    return;
	}
	$(".loading").show();
	$(".loadingcover").show();
	$("#tableParent").show();
	$("#main").empty();
	var uid = $("#selUser").val();
	if ("" == uid) {
		uid = alluserid;
	}
	var uin = $("#selChat").val();

	if (uid != "") {
    	var paraJson = $.toJSON({
    		cususerid: uid,
    		uin: uin,
    		redpackagetype: $("#selChat1").val(),
    		sendtype: $("#selChat2").val(),//   0 收到 ，1 发出,
    		dtstart: $("#txtTimeFrom").val(), //开始时间,
    		dtend: $("#txtTimeTo").val()//结束时间
    	});
    	dataObj.getredpackage(paraJson);
    } else {
        $(".loading").hide();
        $(".loadingcover").hide();

        $("#liExport").hide();
        $("#redpacagetable").hide();
        $("#tips").show();
        $("#tableParent").hide();
        $("#friendcount").html(0);
        $("#todaynewfriend").html(0);
        m_strRedPacket.list = [];
    }
   
}

//红包统计回调
function AsyncGetRedPackageResult(jsonResult) {
    m_strRedPacket = {};
    if (jsonResult.success == true) {
        $("#mytbody").empty();
        $("#main").empty();
        m_strRedPacket = jsonResult.result;
        //if (1 == select) {
        //    HistorgramShow();
        //}
        if (jsonResult.result.list.length > 0) {
            SetFansShow(m_strRedPacket.list)
            $("#liExport").show();
            $("#tips").hide();
            $("#tableParent").show();
            $("#redpacagetable").show();
        } else {
            //m_strRedPacket = {};
            $("#liExport").hide();
            $("#tips").show();
            $("#tableParent").hide();
            $("#friendcount").html(0);
            $("#todaynewfriend").html(0);
            $("#redpacagetable").hide();
        }
    }else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
        $("#tips").show();
        $("#tableParent").hide();
        $("#friendcount").html(0);
        $("#todaynewfriend").html(0);
    }
    $(".loading").hide();
    $(".historyzhezhao").hide();
    $(".loadingcover").hide();
    $(".loading").hide();
}

// 统计页面
function SetFansShow(json) {
	var rednum = 0;//红包数量
	var zhuannum = 0;//转账数量
	var revoiceAlljine = 0;//收到金额总计
	var issAlljine = 0;//发出金额总计
	var strtype = "";//红包类型
	var strsendsourcerevoicenum = 0;//支出数量
	var strsendsourceissuenum = 0;//收到数量
	var strConrent = "";
	var TransferMoney;//转账金额 用于存储替换掉￥符号后的转账金额
    //表头
	strConrent += "<tr>";
	strConrent += "<th style=\"width: 50px\">序号</th>";
	strConrent += "<th style=\"width: 90px\">客服微信</th>";
	strConrent += "<th style=\"width: 90px\">红包类型</th>";
	strConrent += "<th style=\"width: 90px\">金额</th>";
	strConrent += "<th style=\"width: 90px\">收入/支出</th>";
	strConrent += "<th style=\"width: 90px\">发送人</th>";
	strConrent += "<th style=\"width: 90px\">接收人</th>";
	strConrent += "<th style=\"width: 90px\">时间</th>";
	strConrent += "</tr>"
		for (var i = 0; i < json.length; i++) {
			var strsource = "";
			TransferMoney = json[i].jine.indexOf("￥") >= 0 ? json[i].jine.replace("￥", "") : json[i].jine;
			if (json[i].sendsource == 1) {
				strsource = "发出";
				strsendsourcerevoicenum++;
				issAlljine = (Number(issAlljine) + Number(TransferMoney)).toFixed(2);
			} else {
				strsource = "收到";
				strsendsourceissuenum++;
				revoiceAlljine = (Number(revoiceAlljine) + Number(TransferMoney)).toFixed(2);
			}

			if (json[i].type == "0") {
				strtype = "红包";
				rednum++;
			} else {
				strtype = "转账";
				zhuannum++;
			}

			var strwechatremark = json[i].wremarkname.trim().length > 0 ? "(" + json[i].wremarkname + ")" : "";//微信备注
			var strremarkname = json[i].remarkname.trim().length > 0 ? "(" + json[i].remarkname + ")" : "";//好友备注
			strConrent += "<tr>";
			strConrent += "<td>" + (i + 1) + "</td>";
			strConrent += "<td>" + json[i].wnickname + strwechatremark + "</td>";
			var strjine = Number(TransferMoney) > 0 ? TransferMoney : "-";
			strConrent += "<td>" + strtype + "</td>";
			strConrent += "<td>" + strjine + "</td>";
			strConrent += "<td>" + strsource + "</td>";
			if (json[i].sendsource == 1) {
			    strConrent += "<td>" + json[i].wnickname + strwechatremark + "</td>";
			    strConrent += "<td>" + json[i].nickname + strremarkname + "</td>";
			} else {
			    strConrent += "<td>" + json[i].nickname + strremarkname + "</td>";
			    strConrent += "<td>" + json[i].wnickname + strwechatremark + "</td>";
			}
			strConrent += "<td>" + json[i].createtime + "</td>";
			strConrent += "</tr>";

		}
		strConrent += "<tr>";
		strConrent += "<td colspan=\"1\">合计：</td>";
		strConrent += "<td colspan=\"2\" id=\"pacagetype\"></td>";
		strConrent += "<td colspan=\"2\" id=\"sourcetype\"></td>";
		strConrent += "<td colspan=\"3\" id=\"jine\"></td>";
		strConrent += "</tr>";
		$("#mytbody").append(strConrent);

		if (m_RedPacageType == "1") {
			strredpacagetype = "转账数：" + zhuannum;
		} else if (m_RedPacageType == "0") {
			strredpacagetype = "红包数：" + rednum;
		} else {
			var strredpacagetype = "红包数：" + rednum + "&nbsp;&nbsp;转账数：" + zhuannum;
		}
		var strsourcetype = "";
		if (m_RevoiceIssue == "1") {
			strsourcetype = "共发出：" + strsendsourcerevoicenum;
		} else if (m_RevoiceIssue == "0") {
			strsourcetype = "&nbsp;&nbsp;收到：" + strsendsourceissuenum;
		} else {
			strsourcetype = "共发出：" + strsendsourcerevoicenum + "&nbsp;&nbsp;共收到：" + strsendsourceissuenum;
		}
		var strtoal = "共发出：" + issAlljine + "  共收到：" + revoiceAlljine;
		$("#pacagetype").html(strredpacagetype);
		$("#jine").html(strtoal);
		$("#sourcetype").html(strsourcetype);
		$("#redpacagetable").css("display", "block");
		m_Rednum = rednum;
		m_Zhuannum=zhuannum;
		m_Strsendsourceissuenum = strsendsourceissuenum;
		m_Strsendsourcerevoicenum = strsendsourcerevoicenum;
		m_IssAlljine = issAlljine;
		m_RevoiceAlljine = revoiceAlljine;
		tableSlip();//表头拖拽
}
//选择红包类型
function selRedPacageType() {
	m_RedPacageType = $("#selChat1").val();
}
//选择收入支出类型
function selRevoiceIssue() {
	m_RevoiceIssue = $("#selChat2").val();
}

function tableclick() {
    select = 0;
    BindData();
}

//导出excle
function ErportExcle() {
    var paraJson = $.toJSON({
        jsonpara: m_strRedPacket,
        rednum: m_Rednum,
        zhuannum:m_Zhuannum,
        strsendsourceissuenum: m_Strsendsourceissuenum,
        strsendsourcerevoicenum: m_Strsendsourcerevoicenum,
        issAlljine: m_IssAlljine,
        revoiceAlljine: m_RevoiceAlljine,
        sendtype: m_RedPacageType,
        redpackettype: m_RevoiceIssue
    });
    dataObj.redpackettoexcel(paraJson);
}
//导出excle回调
function AsyncRedPacketToExcelResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "报表导出成功！");
    } else {
        ShowError("myPageAlert", "报表导出异常" + jsonResult.error);
    }
}

//样式操作
function listcss() {
    $("#right").css({
        height: $(window).height()
    });
    $("#left").css({
        height: $(window).height()
    });
    $(".left-list-l").css({
        height: $(window).height()
    });
    $(".friends-table").css({
        height: $(window).height() - 180
    });
}
$(window).resize(function () {
    listcss();
});
//初始化控件
$(document).ready(function () {
    $('#txtTimeFrom').datetimepicker({
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        minView: "month",
        format: "yy-m-d"
    });
    $('#txtTimeTo').datetimepicker({
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        minView: "month",
        format: "yy-m-d"
    });

    //获取今天日期
    var myDate = new Date();
    //myDate.setDate(myDate.getDate() - 1);
    $('#txtTimeTo').val((myDate.getYear() - 100) + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate());
    $('#txtTimeTo').datetimepicker('update');
    //设置日期，当前日期的前七天
    myDate.setDate(myDate.getDate() - 7);
    $('#txtTimeFrom').val((myDate.getYear() - 100) + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate());
    $('#txtTimeFrom').datetimepicker('update');
});

