/* define(['zepto','medtap'],function($,medtap){
	var main = {
		userId:medtap.getRequest('userId'),
		init:function(){
			$('#content').append(main.userId);
			main.bindEve()
		},
		bindEve:function(){
			$('#content img').unbind().bind('click',function(){
				var imgObeject = {};//webApi对象参数
				var imgSelect = $(this).index();//选中图片
				var imgIndex = 0;
				var urls = [],
					picUrl = "";
				[].forEach.call($('#content img'), function(item,index) {
					if($(item).index() == imgSelect){
						imgIndex = index;
					}
					urls.push($(item).attr('src'));
				});
				imgObeject.imgList = urls;
				imgObeject.imgIndex = imgIndex;
				console.log(imgObeject);
				//调用webApi展示大图
				try {
					if (!WebAPI) {
				
					}
					try {
						WebAPI.showImages(imgObeject);
					} catch (e) {
				
					}
				} catch (e) {
				
				}
			})
		}
	}
	main.init();
}) */
define(['zepto', 'medtap'], function($, medtap) {
	var chat = {
		userId: medtap.getRequest('userId'),
		relationId: '',
		doctorId: '',
		doctorName: '',
		doctorProfile: '',
		helperName: '',
		helperProfile: '',
		userName: '',
		userProfile: '',
		hasMore: false,
		limit: 50,
		offset: 1,
		minId: 0,
		maxId: 0,
		init: function() {
			chat.bindEve();
			chat.getPmdOrderInfo();
			chat.talkRelation();
			/* $(window).scroll(function() {
				var scrollTop = $(this).scrollTop(); //滚动条距离顶部的高度
				var scrollHeight = $(document).height(); //当前页面的总高度
				var clientHeight = $(this).height(); //当前可视的页面高度
				if (scrollTop + clientHeight >= scrollHeight) { //距离顶部+当前高度 >=文档总高度 即代表滑动到底部 
					//滚动条到达底部
					chat.offset = 1;
					chat.refreshRecord(0);
				} else if (scrollTop <= 0) {
					//滚动条到达顶部
					chat.offset = 1;
					chat.refreshRecord(1);
				}
			}); */
			var getTalk = setInterval(function() {
				chat.getTalkRecord();
				window.scrollTo(0, document.documentElement.clientHeight);
			}, 10000)
			$('input').on('focus',function(){
				//$('body').scrollTop(0);
				clearInterval(getTalk);
			});
			$('input').on('blur',function(){
				//$('body').scrollTop(0);
				var getTalk = setInterval(function() {
					chat.getTalkRecord();
					window.scrollTo(0, document.documentElement.clientHeight);
				}, 5000)
			});
		},
		bindEve: function() {
			$('.close_info_btn').unbind().bind('click', function() {
				$('.chat_info').hide();
				$(this).hide();
				$('.open_info_btn').show();
			});

			$('.open_info_btn').unbind().bind('click', function() {
				$('.chat_info').show();
				$(this).hide();
				$('.close_info_btn').show();
			});

			$('.send').unbind().bind('click', function() {
				if (!$('#sendMsg').val()) {
					medtap.winPop('消息不能为空')
				} else {
					chat.sendMsg();
				}
			})
		},
		//获取私人医生订单相关信息
		getPmdOrderInfo: function() {
			medtap.jzz(1);
			$.ajax({
				url: 'https://testdevgw.medtap.cn/trade/pmdConsultOrder/listValidOrder',
				type: 'post',
				contentType: "application/json",
				async: false,
				headers: medtap.getHeaders(),
				data: JSON.stringify({
					clientId: parseInt(chat.userId),
					clientType: 'USER'
				}),
				success: function(res) {
					medtap.jzz(0);
					if (res.success == true) {
						var pmdOrderList = res.content.list;
						if (pmdOrderList.length == 0) {
							//console.log(1)
							$('.service_btn').addClass('service_none');
						} else {
							//console.log(2)
						}
					}
				}
			})
		},
		//绑定，获取聊天关系
		talkRelation: function() {
			medtap.jzz(1);
			$.ajax({
				url: 'https://testdevgw.medtap.cn/operation/talk/talkRelation',
				type: 'post',
				async: false,
				contentType: 'application/json',
				headers: medtap.getHeaders(),
				data: JSON.stringify({
					userId: parseInt(chat.userId)
				}),
				success: function(res) {
					medtap.jzz(0);
					if (res.success == true) {
						chat.relationId = res.content.talkRealtion.id;
						chat.doctorId = res.content.talkRealtion.doctorId;
						chat.doctorName = res.content.talkRealtion.doctorName;
						chat.doctorProfile = res.content.talkRealtion.doctorProfile;
						chat.userName = res.content.talkRealtion.username;
						chat.userProfile = res.content.talkRealtion.userProfile;
						chat.helperName = res.content.talkRealtion.helperName;
						chat.helperProfile = res.content.talkRealtion.helperProfile;
						$('.user_profile').attr('src', chat.userProfile);
						$('.user_name').html(chat.userName);
						$('.assistant_name').html(chat.helperName);
						document.title = chat.userName;
						$('.assistant_profile').attr('src', chat.helperProfile);
						chat.getTalkRecord();
					}
				}
			})
		},
		sendMsg: function() {
			medtap.jzz(1);
			$.ajax({
				url: 'https://testdevgw.medtap.cn/operation/talk/talk',
				type: 'post',
				async: false,
				headers: medtap.getHeaders(),
				contentType: 'application/json',
				data: JSON.stringify({
					contentType: 0,
					content: $('#sendMsg').val(),
					orderSn: '',
					relationId: chat.relationId
				}),
				success: function(res) {
					medtap.jzz(0);
					if (res.success == true) {
						//window.location.reload();
						chat.getTalkRecord();
						window.scrollTo(0, document.documentElement.clientHeight);
						$('#sendMsg').val('')
					}
				}
			})
		},
		//获取消息列表
		getTalkRecord: function() {
			medtap.jzz(1);
			$.ajax({
				url: 'https://testdevgw.medtap.cn/operation/talk/talkRecord',
				type: 'get',
				async: false,
				headers: medtap.getHeaders(),
				data: {
					offset: chat.offset,
					limit: 50,
					relationId: chat.relationId,
					orderSn: '',
				},
				success: function(res) {
					medtap.jzz(0);
					var record = res.content.list;
					var html = '';
					if (record.length == 0) {
						chat.hasMore = false;
						//medtap.winPop('没有更多了')
					} else {
						chat.hasMore = true;
						chat.minId = record[0].id;
						chat.maxId = record[record.length - 1].id;
						//console.log(chat.minId + ':' + chat.maxId)
						for (var i = 0; i < record.length; i++) {
							var type = record[i].contentType;
							if (type == 0) {
								if (record[i].senderId == chat.doctorId) {
									html += '<div class="chat_item chat_item_right">' +
										'<p class="message_time">' + record[i].createTime.substring(5, 16) + '</p>' +
										'<div class="chat_info_warp clearfix">' +
										'<img src="' + chat.doctorProfile + '" class="chat_profile send_profile">' +
										'<div class="chat_message_warp">' +
										'<div class="chat_message chat_message_send">' +
										record[i].content +
										'</div>' +
										'</div>' +
										'</div>' +
										'</div>';
								} else if (record[i].senderId == chat.userId) {
									html += '<div class="chat_item chat_item_left">' +
										'<p class="message_time">' + record[i].createTime.substring(5, 16) + '</p>' +
										'<div class="chat_info_warp clearfix">' +
										'<img src="' + chat.userProfile + '" class="chat_profile from_profile">' +
										'<div class="chat_message_warp">' +
										/* '<p class="chat_from_name">' + chat.doctorName + '医生</p>' + */
										'<div class="chat_message chat_message_from">' +
										record[i].content +
										'</div>' +
										'</div>' +
										'</div>' +
										'</div>';
								} else{
									html += '<div class="chat_item chat_item_left">' +
										'<p class="message_time">' + record[i].createTime.substring(5, 16) + '</p>' +
										'<div class="chat_info_warp clearfix">' +
										'<img src="' + chat.helperProfile + '" class="chat_profile from_profile">' +
										'<div class="chat_message_warp">' +
										'<p class="chat_from_name">' + chat.helperName + '</p>' +
										'<div class="chat_message chat_message_from">' +
										record[i].content +
										'</div>' +
										'</div>' +
										'</div>' +
										'</div>';
								}
							}else if (record[i].contentType == 10) {
									var content = JSON.parse(record[i].content);
									html += '<div class="service_message img_consult clearfix" style="margin-bottom:0.2rem;" data-id="'+content.orderSn+'">' +
										'<div class="service_left_box sevice_img_consult">' +
										'<img src="images/consult_order_twzx_png@2x.png" >' +
										'<p class="service_title">图文咨询</p>' +
										'<p class="service_price">' + content.payFee + '</p>' +
										'</div>' +
										'<div class="service_right_box service_message_detail">' +
										'<p class="detail_patient_name">' + content.texts[0] + '</p>' +
										'</div>' +
										'</div>';
							}else if(record[i].contentType == 11){
								var content = JSON.parse(record[i].content);
								html += '<div class="service_message consult_box clearfix" data-id="'+content.orderSn+'">'+
											'<div class="service_left_box sevice_consult">'+
												'<img src="images/consult_order_twzx_png@2x.png" >'+
												'<p class="service_title">私人医生</p>'+
												'<p class="service_price">' + content.payFee + '</p>'+
											'</div>'+
											'<div class="service_right_box service_message_detail">'+
												/* '<p class="detail_patient_name">患者：张天问</p>'+ */
												'<p class="detail_question">' + content.texts[1] + '</p>'+
											'</div>'+
										'</div>';
							}else if(type == 3){
								var content = record[i].content;
								content.replace(/\n/g,"<br>");
								html += '<p class="system_msg">'+content.replace(/\n/g,"<br>")+'</p>';
							}
						}
					}
					if (chat.offset == 1) {
						$('.chat_list').html(html);
						window.scrollTo(0, document.documentElement.clientHeight);
					} else {
						$('.chat_list').prepend(html);
						window.scrollTo(0, document.documentElement.clientHeight);
					}
					$('.consult_box').unbind().bind('click',function(){
						var id = $(this).attr('data-id');
						//medtap.pushWindow('../../wechat_lung_prvivateDoctor/pages/pmdDetail.html?id=' + id + '&wechatId=' + medtap.getRequest('wechatId'));
						window.location.href = 'medtapdoc://medtap.cn/order/detail?orderSn=' + id;
					});
					
					$('.img_consult').unbind().bind('click',function(){
						var id = $(this).attr('data-id');
						//medtap.pushWindow('../../wechat_lung_imgConsult/pages/imgConsultDetail.html?id=' + id + '&wechatId=' + medtap.getRequest('wechatId'));
						window.location.href = 'medtapdoc://medtap.cn/order/detail?orderSn='+ id;
					})
				}
			})
		},
		//刷新消息列表
		refreshRecord: function(operateType) {
			var id = 0;
			if (operateType == 0) {
				id = chat.maxId;
			} else {
				id = chat.minId;
			}
			medtap.jzz(1);
			$.ajax({
				url: 'https://testdevgw.medtap.cn/operation/talk/talkRecord/refresh',
				type: 'get',
				async: false,
				headers: medtap.getHeaders(),
				data: {
					offset: chat.offset,
					limit: 10,
					relationId: chat.relationId,
					orderSn: '',
					operateType: operateType,
					startId: id
				},
				success: function(res) {
					medtap.jzz(0);
					chat.offset += 1;
					var record = res.content.list;
					var html = '';
					if (record.length == 0) {
						chat.hasMore = false;
						//medtap.winPop('没有更多了');
					} else {
						chat.hasMore = true;
						if (operateType == 0) {
							chat.maxId = record[record.length - 1].id;
							for (var i = 0; i < record.length; i++) {
								var type = record[i].contentType;
								if (type == 0) {
									if (record[i].senderId == chat.doctorId) {
										html += '<div class="chat_item chat_item_right">' +
											'<p class="message_time">' + record[i].createTime.substring(5, 16) + '</p>' +
											'<div class="chat_info_warp clearfix">' +
											'<img src="' + chat.doctorProfile + '" class="chat_profile send_profile">' +
											'<div class="chat_message_warp">' +
											'<div class="chat_message chat_message_send">' +
											record[i].content +
											'</div>' +
											'</div>' +
											'</div>' +
											'</div>';
									} else if (record[i].senderId == chat.userId) {
										html += '<div class="chat_item chat_item_left">' +
											'<p class="message_time">' + record[i].createTime.substring(5, 16) + '</p>' +
											'<div class="chat_info_warp clearfix">' +
											'<img src="' + chat.userProfile + '" class="chat_profile from_profile">' +
											'<div class="chat_message_warp">' +
											/* '<p class="chat_from_name">' + chat.doctorName + '医生</p>' + */
											'<div class="chat_message chat_message_from">' +
											record[i].content +
											'</div>' +
											'</div>' +
											'</div>' +
											'</div>';
									}
								}
								$('.chat_list').append(html);
							}
						} else {
							chat.minId = record[0].id;
							for (var i = 0; i < record.length; i++) {
								var type = record[i].contentType;
								if (type == 0) {
									if (record[i].senderId == chat.doctorId) {
										html += '<div class="chat_item chat_item_right">' +
											'<p class="message_time">' + record[i].createTime.substring(5, 16) + '</p>' +
											'<div class="chat_info_warp clearfix">' +
											'<img src="' + chat.doctorProfile + '" class="chat_profile send_profile">' +
											'<div class="chat_message_warp">' +
											'<div class="chat_message chat_message_send">' +
											record[i].content +
											'</div>' +
											'</div>' +
											'</div>' +
											'</div>';
									} else if (record[i].senderId == chat.userId) {
										html += '<div class="chat_item chat_item_left">' +
											'<p class="message_time">' + record[i].createTime.substring(5, 16) + '</p>' +
											'<div class="chat_info_warp clearfix">' +
											'<img src="' + chat.userProfile + '" class="chat_profile from_profile">' +
											'<div class="chat_message_warp">' +
											/* '<p class="chat_from_name">' + chat.doctorName + '医生</p>' + */
											'<div class="chat_message chat_message_from">' +
											record[i].content +
											'</div>' +
											'</div>' +
											'</div>' +
											'</div>';
									}
								}
							}
							$('.chat_list').prepend(html);
						}
					}

				}
			})
		}
	}
	chat.init();
})
