define(['zepto', 'medtap'], function($, medtap) {
	var main = {
		orderSn: medtap.getRequest('orderSn'),
		userId: '',
		relationId: '',
		doctorId: '',
		doctorName: '',
		doctorProfile: '',
		helperName: '',
		helperProfile: '',
		userName: '',
		userProfile: '',
		hasMore: false,
		limit: 50,
		offset: 1,
		minId: 0,
		maxId: 0,
		init: function() {
			main.getOrderDetail();
			main.bindEve();

				var getTalk = setInterval(function() {
					main.getTalkRecord();
					if(document.documentElement.scrollHeight > document.documentElement.clientHeight){
						setTimeout(function(){
							document.documentElement.scrollTop = document.documentElement.scrollHeight;
						})
					}
				}, 5000)
				$('input').on('focus',function(){
					clearInterval(getTalk);
				});
				$('input').on('blur',function(){
					var getTalk = setInterval(function() {
						main.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.winPop('消息不能为空')
				} else {
					main.sendMsg();
				}
			});

			//接受订单

			$('.accept_btn').unbind().bind('click', function() {
				main.acceptOrder();
			})

			//取消订单
			$('.refer_btn').unbind().bind('click', function() {
				main.rejectOrder();
			});
			
			
		},
		getOrderDetail: function() {
			$.ajax({
				url: 'https://testdevgw.medtap.cn/trade/order/getOrderByOrderSn',
				type: 'get',
				headers: medtap.getHeaders(),
				data: {
					orderSn: main.orderSn
				},
				success: function(res) {
					if (res.success == true) {
						var detail = res.content.order;
						$('.user_age').html(detail.imageConsultOrder.age + '岁' + ' ' + detail.imageConsultOrder.diseaseDiagnosisDesc)
						main.talkRelation(detail.clientId);
						var imgConsultDetail = detail.imageConsultOrder; //图文咨询详情
						main.userId = imgConsultDetail.clientId;
						$('.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);
						$('.content_item_imgList img').unbind().bind('click', function() {
							var imgObject = {};
							var imgSelect = $(this).index();
							var imgIndex = 0;
							var urls = [],
								picUrl = "";
							[].forEach.call($('.content_item_imgList img'),function(item,index){
								if($(item).index() == imgSelect){
									imgIndex = index;
								}
								urls.push($(item).attr('src'));
							})
							imgObject.imgList = urls;
							imgObject.imgIndex = imgIndex;
							try {
								if (!WebAPI) {
							
								}
								try {
									WebAPI.showImages(imgObject);
								} catch (e) {
							
								}
							} catch (e) {
							
							}
						})
						$('.help_area').val(imgConsultDetail.expectationHelp || '');

						//订单状态判断
						/* if (detail.status == 0) {

						} else if (detail.status.key == 1) {
							
						} else if (detail.status.key == 3) {
							$('.footer_btn').hide();
							$('.footer').hide();
						} */
						if (imgConsultDetail.serviceStatus.key == 2) {
							$('.footer_btn').show();
							$('.footer').hide();
						} else if (imgConsultDetail.serviceStatus.key == 10) {
							$('.footer_btn').hide();
							$('.footer').hide();
							main.getTalkRecord(imgConsultDetail.clientId);
							main.getPmdOrderInfo(imgConsultDetail.clientId);
						} else {
							$('.footer_btn').hide();
							$('.footer').show();
							main.getTalkRecord(imgConsultDetail.clientId);
							main.getPmdOrderInfo(imgConsultDetail.clientId);
						}
						var userId = res.content.order.clientId;
						$('.go_emr').unbind().bind('click', function() {
							medtap.pushNewWindow('../patientInfoByOrder/myEMR.html?userId=' + userId)
						})
					}
				}
			})
		},
		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(main.userId),
					clientType: 'USER'
				}),
				success: function(res) {
					medtap.jzz(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 + '）次')
							}
							//$('.pmd')
						}
					}
				}
			})
		},
		//初始化聊天
		talkRelation: function(userId) {
			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: userId,
					orderSn: main.orderSn
				}),
				success: function(res) {
					medtap.jzz(0);
					if (res.success == true) {
						main.relationId = res.content.talkRealtion.id;
						main.doctorId = res.content.talkRealtion.doctorId;
						main.doctorName = res.content.talkRealtion.doctorName;
						main.doctorProfile = res.content.talkRealtion.doctorProfile;
						main.userName = res.content.talkRealtion.username;
						main.userProfile = res.content.talkRealtion.userProfile;
						main.helperName = res.content.talkRealtion.helperName;
						main.helperProfile = res.content.talkRealtion.helperProfile;
						$('.user_profile').attr('src', res.content.talkRealtion.userProfile);
						$('.user_name').html(res.content.talkRealtion.username);
						document.title = res.content.talkRealtion.username;
						main.relationId = res.content.talkRealtion.id;
					}
				}
			})
		},
		//获取消息列表
		getTalkRecord: function() {
			medtap.jzz(1);
			$.ajax({
				url: 'https://testdevgw.medtap.cn/operation/talk/talkRecord',
				type: 'get',
				async: false,
				headers: medtap.getHeaders(),
				data: {
					offset: main.offset,
					limit: 50,
					relationId: main.relationId,
					orderSn: main.orderSn,
				},
				success: function(res) {
					medtap.jzz(0);
					var record = res.content.list;
					var html = '';
					if (record.length == 0) {
						main.hasMore = false;
						//medtap.winPop('没有更多了')
					} else {
						main.hasMore = true;
						main.minId = record[0].id;
						main.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 == main.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="' + main.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 == main.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="' + main.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 if (record[i].contentType == 3) {
								var content = record[i].content;
								content.replace(/\n/g, "<br>");
								html += '<p class="system_msg">' + content.replace(/\n/g, "<br>") + '</p>'
							}
						}
					}
					if (main.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;
							})
						};
					}
				}
			})
		},
		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: main.orderSn,
					relationId: main.relationId
				}),
				success: function(res) {
					medtap.jzz(0);
					if (res.success == true) {
						//window.location.reload();
						main.getTalkRecord();
						window.scrollTo(0, document.documentElement.clientHeight);
						$('#sendMsg').val('')
					} else {
						medtap.winPop(res.resultDesc)
					}
				}
			})
		},
		//接受订单
		acceptOrder: function() {
			medtap.jzz(1);
			$.ajax({
				url: 'https://testdevgw.medtap.cn/trade/imageConsultOrder/affirmOrder/ACCEPT',
				type: 'post',
				async: false,
				headers: medtap.getHeaders(),
				contentType: 'application/json',
				data: JSON.stringify({
					orderSn: main.orderSn
				}),
				success: function(res) {
					medtap.jzz(0);
					if (res.success == true) {
						medtap.winPop('已接受订单');
						setTimeout(function() {
							window.location.reload();
						}, 2000);
					}
				}
			})
		},
		rejectOrder: function() {
			medtap.jzz(1);
			$.ajax({
				url: 'https://testdevgw.medtap.cn/trade/imageConsultOrder/affirmOrder/REJECT',
				type: 'post',
				async: false,
				headers: medtap.getHeaders(),
				contentType: 'application/json',
				data: JSON.stringify({
					orderSn: main.orderSn
				}),
				success: function(res) {
					medtap.jzz(0);
					if (res.success == true) {
						medtap.winPop('已取消订单');
						setTimeout(function() {
							window.location.reload();
						}, 2000);
					}
				}
			})
		}
	}
	main.init();
})
