//用户id
var userid = $.cookie("userid");

//getConsultData参数
var pageSize = 5;
var pageNo, isbind, status, timeType, sortType;

getConsultData(pageSize, 1, true, 0, 1, 0);
consultPullDownMenu();

function getConsultData(pageSize, pageNo, isbind, status, timeType, sortType) {
	var params = {
		"professorId": userid, //专家ID
		"status": status, //查询状态 0-全部，1-进行中，2-未感谢，3-未评价，4-已完成， 可以不传，默认为0
		"timeType": timeType, //排序目的 0-按发起时间，1-按最后回复时间，2-按完成时间 默认为0
		"sortType": sortType, //排序目的 0-倒序，1-正序 默认为0
		"pageSize": pageSize, //每页记录数 默认为5
		"pageNo": pageNo //当前页码 默认为1
	};
	//	console.log(params);
	$.ajax({
		url: "/ajax/consult/pqPro",
		type: "get",
		//传值：登陆人id:咨询id
		data: params,
		async: false,
		dataType: "json",
		contentType: "application/x-www-form-urlencoded",
		success: function(response) {
			//			console.log(response);
			//数据为空时
			if(response.success) {
				if(response["data"]["data"] == null || response["data"]["data"] == undefined || response["data"]["data"] == "") {
					return;
				} else {
					var consultStr;
					var allData = response.data;
					var myData = allData["data"];
					//					console.log(myData);
					//拿到收到咨询数据
					$("#workContainer").html(""); //清空数据

					if(myData.length != 0 && myData.length != null) {
						consultStr = handleData(myData, "professorId", "lookBtn");
						//						console.log(consultStr)
						$("#workContainer").append(consultStr);

					} else {
						return;
					}
					//分页
					if(isbind == true) {
						$(".getConsultPage").createPage({
							pageCount: Math.ceil(allData.total / pageSize),
							current: allData.pageNo,
							backFn: function(p) {
								getConsultData(pageSize, p, false, status, timeType, sortType);
							}
						});
					}
				}
			}

		},
		error: function(response) {
			$.MsgBox.Alert('提示', "收到咨询数据请求失败");
		},
		complete: function() {

		}
	});
};

//data:需要处理的数据，htmlStr:页面中需要的html字符串拼接，
//attrParams:数据中不同的参数比如:收到咨询是professorId，收到答复：consultantId
function handleData(data, attrParams, btnCls) {
	var htmlStr = '';
	var title,
		office,
		orgName,
		department,
		address;

	for(var i = 0; i < data.length; i++) {
		//text:回复/查看，state:进行中/已完成/未评价，photoUrl：头像地址，proModify：专家认证
		var text, state, stateStyle, photoUrl, proModify;
		var modifyclass = '';
		if(data[i]["professor"]) { //过滤没有专家对象的数据

			if(data[i]["consultStatus"] == 0) {
				state = "进行中";
				stateStyle = 'status-1';
				text = '回复';
			} else if(data[i]["consultStatus"] == 1) {
				text = "查看";
				state = "已完成";
				stateStyle = 'status-3';
				if(attrParams == 'consultId') {
					if(data[i]["assessStatus"] == 0) {
						state = "待评价";
						stateStyle = 'status-2';
					}
				}
			} else if(data[i]["consultStatus"] == 2) {
				text = "查看";
				state = "新咨询";
				stateStyle = 'status-2';
			} else if(data[i]["consultStatus"] == 3) {
				text = "查看";
				state = "已谢绝";
				stateStyle = 'status-5';
			} else if(data[i]["consultStatus"] == undefined) {
				text = "";
				state = "";
			}

			//专家头像
			if(data[i]["professor"]["hasHeadImage"] == 0) {
				photoUrl = "images/default-photo.jpg"

			} else {
				photoUrl = "images/head/" + data[i]["professor"]["id"] + "_l.jpg"

			};
			//认证
			//			if(data[i]["professor"]["authentication"] == true){
			//				proModify = "display:inline-block;"
			//			}else{
			//				proModify = "display:none;"
			//			}

			if(data[i]["professor"].authType) { //专家
				modifyclass = 'authicon authicon-cu';
			} else { //普通用户
				if(data[i]["professor"].authStatus == 3) { 
					if(data[i]["professor"].authentication == 1) { //科研工作者
						modifyclass = "authicon2 authicon-mana";
					} else if(data[i]["professor"].authentication == 2) { //企业专家
						modifyclass = "authicon2 authicon-staff";
					} else { //学生
						modifyclass = "authicon2 authicon-stu";
					}
				}
			};

			//未读消息
			var unread = unreadConsultFn(userid, data[i]["consultId"], i);

			htmlStr += "<div class='workselectitem' id='" + data[i]["consultId"] + "' >" +
				"<table width='100%'><tbody><tr><td width='14%' class='messagebox'>" +
				"<a class='workhead workitimg headRadius'>" +
				"<img class='headPhoto' src='" + photoUrl + "'  width='100%' height='100%'>" +
				"</a>" +
				"<span class='msgprompt showUnreadMsg' style='" + unread.style + "' id='" + data[i]["consultId"] + "'>" + unread.unreadCount + "</span>" +
				"</td>" +
				"<td style='position:relative;top:20px;' width='86%'>" +
				"<div class='workinfor worksitcon'><h4><a class='named' id='nameS'> " + data[i]["professor"]["name"] + " </a>" +
				"<a class='modifyicon " + modifyclass + "'></a><input type='text' class='assessStar' value='" + data[i]["assessStar"] + "' style='display: none;'></h4><h6 class='h3Font'>";

			if(data[i]["professor"]["title"]) {
				htmlStr += "<span>" + data[i]["professor"]["title"] + "</span>, ";
			};
			if(data[i]["professor"]["office"]) {
				if(data[i]["professor"]["orgName"] || data[i]["professor"]["department"]) {
					htmlStr += "<span>" + data[i]["professor"]["office"] + "</span>, ";
				} else {
					htmlStr += "<span>" + data[i]["professor"]["office"] + "</span>";
				}

			};
			if(data[i]["professor"]["orgName"]) {
				if(data[i]["professor"]["department"]) {
					htmlStr += "<span>" + data[i]["professor"]["orgName"] + "</span>, ";
				} else {
					htmlStr += "<span>" + data[i]["professor"]["orgName"] + "</span>";
				}

			};
			if(data[i]["professor"]["department"]) {
				htmlStr += "<span>" + data[i]["professor"]["department"] + "</span>";
			};
			if(data[i]["professor"]["address"]) {
				htmlStr += ' | ' + "<span>" + data[i]["professor"]["address"] + "</span>";
			};
			htmlStr += "</h6><h6 style='position:relative;'>" +
				"<div class='titList'>咨询主题：<em class='h4Font'> " + data[i]["consultTitle"] + "  </em></div>" +
				"<span class='lasttime rightTime'>" + lastReplyFn(userid, data[i]["consultId"])["lastReplyTime"] + "</span>" +

				"<p class='rebackcon lastReplyCon' >" + lastReplyFn(userid, data[i]["consultId"])["lastReplyCon"] + "</p>" +
				"</h6></div>" +
				"<div class='workhandle'>" +
				"<div class='rightopert floatR'>" +
				"<span   attrP='" + attrParams + "' class='replybtn " + btnCls + "' id='" + data[i]["consultId"] + "' consultStatus='" + data[i]["consultStatus"] + "' assess='" + data[i]["assessStatus"] + "' thanks='" + data[i]["thanksStatus"] +
				"' onclick='clickLookBtn2(\"" + userid + "\",\"" + attrParams + "\",\"" + data[i]["consultId"] + "\"," + data[i]["consultStatus"] + "," + data[i]["assessStatus"] + "," + data[i]["thanksStatus"] + ");'>" +
				text +
				"</span>" +
				"<span class='moreopert complain'>...</span>" +
				"<ul class='moreopertbtn'>" +
				"<li>投诉</li>" +
				"</ul>" +
				"</div>" +
				"<div class='leftstate floatR'>" +
				"<span class='coultstate  " + stateStyle + "'><i>" + state + "</i></span>" +
				"</div>" +
				"<div class='leftstate floatR'>" +
				"<span class='coultstate coulstAim status-4'><i>" + data[i]["consultType"] + "</i></span>" +
				"</div>" +
				"</div>" +
				"</td>" +
				"</tr></tbody></table>" +
				"</div>";

		}

	};

	return htmlStr;
};

//未读信息接口
function unreadConsultFn(senderId, consultId, i) {
	var unreadCount, style;
	var params = {
		"senderId": senderId, //发送者ID
		"consultId": consultId //咨询ID
	};
	$.ajax({
		url: "/ajax/tidings/qaNotReadTidings",
		type: "get",
		async: false,
		data: params,
		success: function(response) {
			unreadCount = response["data"];
			console.log()
			if(unreadCount == 0) {
				style = "display:none;"
			} else {
				style = "display:block;"

			}
		},
		error: function(error) {
			$.MsgBox.Alert('提示', "未读消息请求失败");
		}

	});
	return {
		"unreadCount": unreadCount,
		"style": style
	}

};

//列表最后回复
function lastReplyFn(sendId, consultId) {

	var lastReplyTimeData, lastReplyTime, lastReplyCon;
	$.ajax({
		url: "/ajax/tidings/qaLastRevovery",
		async: false,
		data: {
			"consultId": consultId, //咨询ID
			"senderId": sendId //登录者ID
		},
		success: function(response) {
			//			console.log(response)
			if(response["data"] == null || response["data"] == "" || response["data"] == undefined) {
				lastReplyTimeData = '';
				lastReplyTime = '';
				lastReplyCon = '';
			} else {
				lastReplyTimeData = response["data"]["createTime"];
				lastReplyTime = lastReplyTimeData.substr(0, 4) + "-" + lastReplyTimeData.substr(4, 2) + "-" + lastReplyTimeData.substr(6, 2) + " " + lastReplyTimeData.substr(8, 2) + ":" + lastReplyTimeData.substr(10, 2)
				lastReplyCon = response["data"]["tidingsContant"];
			}

		},
		error: function(error) {
			$.MsgBox.Alert('提示', "最后回复数据失败");
		}

	});

	return {
		"lastReplyTime": lastReplyTime,
		"lastReplyCon": lastReplyCon

	};
};

//咨询下拉菜单顺序处理函数
function consultPullDownMenu() { //点击下拉菜单
	$(".consultOption ul").find("li").click(function() {
		status = $(this).attr("tip");
		timeType = $("#showTimeSort").attr("tim");
		sortType = $("#timeSortId").val();

		$("#workContainer").remove();
		$("#shoudao").append('<div id="workContainer"></div>')
		$(".getConsultPage").remove();
		$("#shoudao").append('<div class="tcdPageCode getConsultPage"></div>');

		console.log(status + timeType + sortType);

		getConsultData(pageSize, 1, true, status, timeType, sortType);

	});
	$(".timeOption ul").find("li").click(function() {
		status = $("#showStatus").attr("tip");
		timeType = $(this).attr("tim");
		sortType = $("#timeSortId").val();

		$("#workContainer").remove();
		$("#shoudao").append('<div id="workContainer"></div>')
		$(".getConsultPage").remove();
		$("#shoudao").append('<div class="tcdPageCode getConsultPage"></div>');

		console.log(status + timeType + sortType);

		getConsultData(pageSize, 1, true, status, timeType, sortType);
	});
	var sortFlag = true;
	$("#consultArrow").click(function() {

		if(sortFlag == true) {
			$(this).find("div").css("background-position", "-20px 1px");
			$("#timeSortId").val("1");
			sortFlag = false;
		} else {
			$(this).find("div").css("background-position", "0px 1px");
			$("#timeSortId").val("0");
			sortFlag = true;
		}

		status = $("#showStatus").attr("tip");
		timeType = $("#showTimeSort").attr("tim");
		sortType = $("#timeSortId").val();

		$("#workContainer").remove();
		$("#shoudao").append('<div id="workContainer"></div>')
		$(".getConsultPage").remove();
		$("#shoudao").append('<div class="tcdPageCode getConsultPage"></div>');

		console.log(status + timeType + sortType);

		getConsultData(pageSize, 1, true, status, timeType, sortType);
	});
};

//咨询和回复中点击查看或者回复
function clickLookBtn2(sendId, attrParams, consultId, consultStatus, assessStatus, thanksStatus) {
	if(consultStatus == 2) {
		window.location.href = "consultSure.html?consultId=" + consultId
	} else {
		window.location.href = "diloags.html?sendId=" + sendId + "&attrParams=" + attrParams + "&consultId=" + consultId + "&consultStatus=" + consultStatus + "&assessStatus=" + assessStatus + "&thanksStatus=" + thanksStatus;
	}
}