define([ 'zepto', 'medtap' ], function($, medtap) {
	var chat = {
		doctorId: medtap.getRequest('doctorId'),
		relationId: '',
		userId: '',
		doctorName: '',
		doctorProfile: '',
		helperName: '',
		helperProfile: '',
		userName: '',
		userProfile: '',
		hasMore: false,
		limit: 10,
		offset: 1,
		minId: 0,
		maxId: 0,
		data: null,
		localId: '',
		localIds: [],
		serverId: '',
		imgList: [],
		// 发送是传递的类型编号 0 文字 1 图片 2 ...
		num: 0,
		// 图片的ossKey
		imgKey: '',
		// 上传图片后的url地址
		imgUrl: '',
		// 中划线类名
		throwClass:'',
		init: function() {
			chat.bindEve();
			chat.talkRelation();
			chat.getWechatTicket();
			chat.getPmdOrderInfo();
			chat.getOrderDetail();
			/* $(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();
				if (document.documentElement.scrollHeight > document.documentElement.clientHeight) {
					setTimeout(function() {
						document.documentElement.scrollTop = document.documentElement.scrollHeight;
					});
				}
			}, 5000);
			$('input').on('focus', function() {
				$('body').scrollTop(0);
				clearInterval(getTalk);
			});
			$('input').on('blur', function() {
				$('body').scrollTop(0);
				var getTalk = setInterval(function() {
					chat.getTalkRecord();
					if (document.documentElement.scrollHeight > document.documentElement.clientHeight) {
						setTimeout(function() {
							document.documentElement.scrollTop = document.documentElement.scrollHeight;
						});
					}
				}, 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.toast({
						message: '请输入留言内容',
						time: 1500
					});
				} else {
					chat.sendMsg(chat.num);
				}
			});
		},
		// 获取门票
		getWechatTicket: function() {
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/wechat/lung/fetchWechatTicket',
				type: 'GET',
				async: false,
				data: {
					url: window.location.href
				},
				success: function(res) {
					var data = res.content;
					wx.config({
						debug: false,
						appId: data.appId, // 必填，公众号的唯一标识
						timestamp: data.timestamp, // 必填，生成签名的时间戳
						nonceStr: data.nonceStr, // 必填，生成签名的随机串
						signature: data.signature, // 必填，签名，见附录1
						jsApiList: [ 'chooseImage', 'previewImage', 'uploadImage' ]
					});
				}
			});
		},
		//选择图片
		choseImage: function() {
			$('.footer_addPic').on('click', function() {
				// console.log('1')
				var html = '';
				wx.ready(function() {
					var syncUpload = function(localIds) {
						localId = localIds[0];
						localIds = localIds.length > 1 ? localIds.slice(1) : localIds[0];
						wx.uploadImage({
							localId: localId,
							isShowProgressTips: 1,
							success: function(res) {
								var serverId = res.serverId; // 返回图片的服务器端ID
								//其他对serverId做处理的代码
								chat.upLoadImg(serverId, localId);
								if (localIds.length > 0) {
									syncUpload(localIds);
								}
							}
						});
					};
					wx.chooseImage({
						count: 1,
						sizeType: [ 'original', 'compressed' ],
						sourceType: [ 'album', 'camera' ],
						success: function(res) {
							chat.localIds = res.localIds;
							//所有需要上传到图片预览
							syncUpload(chat.localIds);
						}
					});
				});
			});
		},
		// 点击图片信息预览图片
		previewImg: function() {
			$('.chat_list').on('click', '.chat_nopadding img', function(e) {
				var curImageSrc = e.target.src;
				var imgURls = [];
				if (curImageSrc) {
					imgURls.push(curImageSrc);
					wx.previewImage({
						current: curImageSrc, // 当前显示图片的http链接
						urls: imgURls // 需要预览的图片http链接列表
					});
				}
			});
		},
		//上传图片
		upLoadImg: function(serverId, localId) {
			// console.log('执行上传图片')
			$.ajax({
				url: 'https://testdevgw.medtap.cn/common/uploadWechatFile',
				type: 'POST',
				async: true,
				data: {
					bizType: '3',
					folder: 'bbs',
					mediaId: serverId,
					ext: 'jpg'
				},
				headers: {
					'apptype': 'wechat_lung',
					'user-os': 'wechat'
				},
				success: function(data) {
					// console.log('上传图片success',data)
					if (data.success == true) {
						var res = data.content;
						var imgKey = res.ossKey;
						var imgUrl = res.url;
						chat.sendMsg(1, imgUrl);
						// newCard.imgList.push(imgKey);
						// var html = '<div class="image_files_item">' +
						// 	'<img src="' + localId + '" class="image_files_img" imgkey="' + imgKey + '">' +
						// 	'<img src="../images/post_delete_btn@2x.png" class="image_del" >' +
						// 	'</div>';
						// $('#ImgUp').append(html);
					}
				}
			});
		},
		//获取私人医生订单详情
		getPmdOrderInfo: function() {
			medtap.loading(1);
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/trade/pmdConsultOrder/listValidOrder',
				type: 'post',
				contentType: 'application/json',
				async: false,
				data: {
					doctorId: chat.doctorId
				},
				success: function(res) {
					medtap.loading(0);
					if (res.success == true) {
						var pmdOrderList = res.content.list;
						if (pmdOrderList.length == 0) {
							$('.service_btn').addClass('service_none');
						} else {
							if (pmdOrderList[0].serviceStatus == 3) {
								$('.pmd').html('私人医生（服务中）');
								$('.img_consult').html('图文咨询（不限次）');
								$('.consult').html('电话咨询（' + pmdOrderList[0].consultCount + '）次');
							}
						}
					}
				}
			});
		},
		//获取订单详情
		getOrderDetail: function() {
			medtap.loading(1);
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/trade/order/getOrderByOrderSn',
				type: 'get',
				data: {
					orderSn: medtap.getRequest('orderSn')
				},
				success: function(res) {
					if (res.success == true) {
						var detail = res.content.order;
						$('.user_age').html(
							detail.imageConsultOrder.age + '岁' + ' ' + detail.imageConsultOrder.diseaseDiagnosisDesc
						);
						var imgConsultDetail = detail.imageConsultOrder; //图文咨询详情
						$('.patient_name').html(
							imgConsultDetail.patientName +
								' (' +
								(imgConsultDetail.sex == 'M' ? '男 ' : '女 ') +
								imgConsultDetail.age +
								'岁' +
								' ' +
								(imgConsultDetail.hasOwnProperty('areaItem')
									? imgConsultDetail.areaItem.fullName
									: '') +
								')'
						);
						$('.user_age').html(
							(imgConsultDetail.sex == 'M' ? '男 ' : '女 ') +
								imgConsultDetail.age +
								'岁' +
								' ' +
								(imgConsultDetail.hasOwnProperty('areaItem') ? imgConsultDetail.areaItem.fullName : '')
						);
						$('.patient_disease').html(imgConsultDetail.diseaseDiagnosisDesc);
						$('.patient_disease_type').html(imgConsultDetail.pathologyTypeDesc);
						$('.disease_area').val(imgConsultDetail.describe);
						var str = '';
						if (imgConsultDetail.hasOwnProperty('describePic')) {
							for (var i = 0; i < imgConsultDetail.describePic.length; i++) {
								str += '<img src="' + imgConsultDetail.describePic[i] + '" >';
							}
						} else {
							str = '';
						}
						$('.content_item_imgList').html(str);
						$('.help_area').val(imgConsultDetail.expectationHelp || '');

						//订单状态判断
						/* if (detail.status == 0) {
				
						} else if (detail.status.key == 1) {
							
						} */
						if (imgConsultDetail.serviceStatus.key == 2) {
							$('.footer_btn').show();
							$('.footer').hide();
						} else if (imgConsultDetail.serviceStatus.key == 10) {
							$('.footer_btn').hide();
							$('.footer').hide();
						} else {
							$('.footer_btn').hide();
							$('.footer').show();
						}
						//病历id
						var emrId = imgConsultDetail.emrId;
						$('.go_emr').unbind().bind('click', function() {
							medtap.pushWindow('../../wechat_lung_myHome/pages/myEMR.html');
						});
					}
				}
			});
		},
		talkRelation: function() {
			medtap.loading(1);
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/operation/talk/talkRelation',
				type: 'post',
				async: false,
				contentType: 'application/json',
				data: {
					doctorId: parseInt(chat.doctorId),
					orderSn: medtap.getRequest('orderSn')
				},
				success: function(res) {
					medtap.loading(0);
					if (res.success == true) {
						chat.relationId = res.content.talkRealtion.id;
						chat.userId = res.content.talkRealtion.userId;
						chat.doctorName = res.content.talkRealtion.doctorName;
						chat.doctorProfile = res.content.talkRealtion.doctorProfile;
						chat.userName = res.content.talkRealtion.username;
						chat.userProfile = res.content.talkRealtion.userProfile;
						$('.doctor_profile').attr('src', chat.doctorProfile);
						$('.doctor_name').html(chat.doctorName);
						$('.doctor_title').html(res.content.talkRealtion.technologyProfessional.value);
						chat.getTalkRecord();
					} else {
						chat.getToken();
					}
				}
			});
		},
		sendMsg: function(num, content) {
			medtap.loading(1);
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/operation/talk/talk',
				type: 'post',
				async: false,
				contentType: 'application/json',
				data: {
					contentType: num,
					content: content ? content : $('#sendMsg').val(),
					orderSn: medtap.getRequest('orderSn'),
					relationId: chat.relationId
				},
				success: function(res) {
					medtap.loading(0);
					if (res.success == true) {
						//window.location.reload();
						chat.getTalkRecord();
						window.scrollTo(0, document.documentElement.clientHeight);
						$('#sendMsg').val('');
					} else {
						medtap.toast({
							message: res.resultDesc
						});
					}
				}
			});
		},
		//获取消息列表
		getTalkRecord: function() {
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/operation/talk/talkRecord',
				type: 'get',
				async: false,
				data: {
					offset: chat.offset,
					limit: 50,
					relationId: chat.relationId,
					orderSn: medtap.getRequest('orderSn')
				},
				success: function(res) {
					var record = res.content.list;
					var html = '';
					if (record.length == 0) {
						chat.hasMore = false;
					} 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.userId) {
									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.userProfile +
										'" 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.doctorId) {
									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.doctorProfile +
										'" 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 if (type == 10) {
								var content = JSON.parse(record[i].content);
								html +=
									'<div class="service_message img_consult clearfix" style="margin-bottom:0.2rem;">' +
									'<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 (type == 3) {
								var content = record[i].content;
								content.replace(/\n/g, '<br>');
								html += '<p class="system_msg">' + content.replace(/\n/g, '<br>') + '</p>';
							} else if (type == 1) {
								if (record[i].senderId == chat.userId) {
									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.userProfile +
										'" class="chat_profile send_profile">' +
										'<div class="chat_message_warp">' +
										'<div class="chat_message chat_message_send chat_nopadding">' +
										// 图片消息
										'<img src="' +
										record[i].contentPic[0] +
										'" />' +
										'</div>' +
										'</div>' +
										'</div>' +
										'</div>';
								} else if (record[i].senderId == chat.doctorId) {
									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.doctorProfile +
										'" 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 chat_nopadding">' +
										// 图片消息
										'<img src="' +
										record[i].contentPic[0] +
										'" />' +
										'</div>' +
										'</div>' +
										'</div>' +
										'</div>';
								}
							}
						}
					}
					//$('.chat_list').html(html);

					if (chat.offset == 1) {
						$('.chat_list').html(html);
						if (document.documentElement.scrollHeight > document.documentElement.clientHeight) {
							setTimeout(function() {
								document.documentElement.scrollTop = document.documentElement.scrollHeight;
							});
						}
					} else {
						$('.chat_list').prepend(html);
						if (document.documentElement.scrollHeight > document.documentElement.clientHeight) {
							setTimeout(function() {
								document.documentElement.scrollTop = document.documentElement.scrollHeight;
							});
						}
					}
					//window.scrollTo(0, document.documentElement.clientHeight);
				}
			});
		},
		//刷新消息列表
		refreshRecord: function(operateType) {
			var id = 0;
			if (operateType == 0) {
				id = chat.maxId;
			} else {
				id = chat.minId;
			}
			medtap.loading(1);
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/operation/talk/talkRecord/refresh',
				type: 'get',
				async: false,
				data: {
					offset: chat.offset,
					limit: 10,
					relationId: chat.relationId,
					orderSn: '',
					operateType: operateType,
					startId: id
				},
				success: function(res) {
					medtap.loading(0);
					chat.offset += 1;
					var record = res.content.list;
					var html = '';
					if (record.length == 0) {
						chat.hasMore = false;
						/* medtap.toast({
							message: '没有更多了'
						}) */
					} 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.userId) {
										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.userProfile +
											'" 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.doctorId) {
										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.doctorProfile +
											'" 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.userId) {
										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.userProfile +
											'" 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.doctorId) {
										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.doctorProfile +
											'" 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);
						}
					}
				}
			});
		},
		getToken: function() {
			localStorage.wxLungToken = '';
			medtap.loading(1);
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/user/auth/token',
				type: 'POST',
				async: false,
				contentType: 'application/json',
				data: {
					wechatId: medtap.getRequest('wechatId')
				},
				success: function(res) {
					medtap.loading(0);
					if (res.success == true) {
						var token = res.content.token;
						localStorage.setItem('wxLungToken', token);
						//main.checkUser();
						window.location.reload();
					} else {
					}
				},
				error: function(res) {
					console.log(res.resultDesc);
				}
			});
		}
	};
	chat.init();
	chat.choseImage();
	chat.previewImg()
});
