define(['zepto','medtap'],function($,medtap){
	var imgConsult = {
		doctorId:medtap.getRequest('doctorId'),
		doctorName:'',
		pmdOrderSn:medtap.getRequest('pmdOrderSn'),
		localIds: [],
		serverId: "",
		imgList: [],
		emrId:'',
		payFee:'',
		isPmd:false,
		wxLungToken:localStorage.wxLungToken,
		init:function(){
			imgConsult.getDoctorDetail();
			imgConsult.bindEve();
			imgConsult.getWechatTicket();
			imgConsult.getPatient();
			imgConsult.confirmImgConsult();
			$('textarea').on('blur',function(){
				window.scrollTo(0, document.documentElement.clientHeight);
			});
		},
		bindEve:function(){
			$('.btn_icon').unbind().bind('click',function(){
				$(this).toggleClass('btnSelect');
				if ($(this).hasClass('btnSelect')) {
					$(this).attr('select', 'yes');
				} else {
					$(this).attr('select', 'no');
				}
			});
			$('.consult_agreement').unbind().bind('click',function(){
				medtap.pushWindow('https://review-formal.iplusmed.com/App/dev/FF499211739FD801DOCTOR/AppHtml/DoctorServiceLicense.html')
			})
			
			$('.submit_order').unbind().bind('click',function(){
				var flag = $('.btn_icon').attr('select');
				var result = imgConsult.checkValue();
				if(result == true){
					if(flag == 'yes'){
						if(imgConsult.pmdOrderSn == '' || imgConsult.pmdOrderSn == 'undefined'){
							imgConsult.createImgConsult();
						}else{
							if(imgConsult.isPmd == true && imgConsult.payFee == '0'){
								imgConsult.freeOrder();
							}else{
								//imgConsult.createImgConsult();
							}
						}
					}else{
						medtap.toast({
							message:'<p style="text-align:center">请阅读并同意<br/>《医生咨询服务订单协议》</p>',
							time:1500
						})
					}
				}
			})
		},
		getDoctorDetail:function(){
			medtap.loading(1);
			medtap.submitAjax({
				url:'https://testdevgw.medtap.cn/doctor/getDoctorDetail',
				type:'get',
				async:false,
				data:{
					doctorId:imgConsult.doctorId
				},
				success:function(res){
					medtap.loading(0);
					if(res.success == true){
						var doctorInfo = res.content.doctorItem;
						var str = doctorInfo.hasOwnProperty('technologyProfessional') ? doctorInfo.technologyProfessional.value : '';
						$('.doctor_name').html(doctorInfo.doctorName + "(" + str + ")");
						imgConsult.doctorName = doctorInfo.doctorName;
						$('.img_consult_price').html(doctorInfo.hasOwnProperty('imageConsultPrice') ? doctorInfo.imageConsultPrice + ' / 次' : '');
					}
				}
			})
		},
		getPatient:function(){
			medtap.loading(1);
			medtap.submitAjax({
				url:'https://testdevgw.medtap.cn/user/patientEMR/listPatientEMR',
				type:'post',
				async:false,
				contentType: 'application/json',
				data:{
					pageNum:1,
					pageSize:10,
					condition:{
						
					}
				},
				success:function(res){
					medtap.loading(0);
					if(res.success == true){
						var patientList = res.content.list;
						var sex = '';
						var age = '';
						var city = '';
						for(var i = 0;i < patientList.length;i++){
							if(patientList[i].defaultFlg == true){
								$('.service_patient').html(patientList[i].patientName);
								imgConsult.emrId = patientList[i].emrId;
								$('.patient_name').text(patientList[i].patientName);
								if(patientList[i].sex == 'M'){
									sex = '男';
								}else if(patientList[i].sex == 'F'){
									sex = '女';
								}
								age = patientList[i].age;
								city = patientList[i].hasOwnProperty('areaItem') ? patientList[i].areaItem.fullName : '';
								$('.patient_sex_age_city').text('(' + sex +' ' + age +'岁 ' + city + ')');
								$('.diseaseDiagnosis').text('疾病诊断：' + patientList[i].diseaseDiagnosisName);
								$('.pathologyType').text('病理类型：' + patientList[i].pathologyTypeName)
							}
						}
					}
				}
			})
		},
		createImgConsult:function(){
			var urls = [],
				picUrl = "";
			[].forEach.call($('#ImgUp .image_files_img'), function(item) {
				urls.push($(item).attr('imgkey'));
			});
			var picUrl = urls.join(',');
			medtap.loading(1);
			medtap.submitAjax({
				url:'https://testdevgw.medtap.cn/trade/imageConsultOrder/submitOrder',
				type:'post',
				async: false,
				contentType: 'application/json',
				data:{
					emrId:imgConsult.emrId,
					doctorId:imgConsult.doctorId,
					describe:$('#disease_detail').val() || '',
					describePic:picUrl,
					expectationHelp:$('#expectation_help_detail').val() || ''
				},
				success:function(res){
					medtap.loading(0);
					if(res.success == true){
						var orderDetail = res.content.order;
						medtap.pushWindow('https://review-formal.iplusmed.com/wechatForLungCancer/dev/wechat_lung_wxPay/wxPay.html?orderType=imgConsult&orderId=' + orderDetail.orderSn + '&wxLungToken=' + imgConsult.wxLungToken + '&wechatId=' + medtap.getRequest('wechatId'));
					}
				}
			})
		},
		freeOrder:function(){
			var urls = [],
				picUrl = "";
			[].forEach.call($('#ImgUp .image_files_img'), function(item) {
				urls.push($(item).attr('imgkey'));
			});
			var picUrl = urls.join(',');
			medtap.loading(1);
			medtap.submitAjax({
				url:'https://testdevgw.medtap.cn/trade/imageConsultOrder/submitOrderByPmd',
				type:'post',
				async: false,
				contentType: 'application/json',
				data:{
					emrId:imgConsult.emrId,
					doctorId:imgConsult.doctorId,
					pmdOrderSn:medtap.getRequest('pmdOrderSn'),
					describe:$('#disease_detail').val() || '',
					describePic:picUrl,
					expectationHelp:$('#expectation_help_detail').val() || ''
				},
				success:function(res){
					medtap.loading(0);
					if(res.success == true){
						var orderDetail = res.content.order;
						setTimeout(function(){
							medtap.pushWindow('pages/success.html?id=' + orderDetail.orderSn + '&wechatId=' + medtap.getRequest('wechatId'));
						},1000);
					}
				}
			})
		},
		confirmImgConsult:function(){
			medtap.loading(1);
			medtap.submitAjax({
				url:'https://testdevgw.medtap.cn/trade/imageConsultOrder/confirmOrder',
				type:'post',
				async: false,
				contentType: 'application/json',
				data:{
					emrId:imgConsult.emrId,
					doctorId:imgConsult.doctorId,
					pmdOrderSn:medtap.getRequest('pmdOrderSn')
				},
				success:function(res){
					medtap.loading(0);
					if(res.success == true){
						var result = res.content.result;
						imgConsult.isPmd = result.isPmd;
						imgConsult.payFee = result.payFee;
						$('.img_consult_price').html(result.hasOwnProperty('totalFee') ? result.totalFee + '元 / 次' : '');
						if(result.isPmd == true && result.payFee == '0'){
							$('.free_tip').show();
							$('.needPay').hide();
						}else{
							$('.free_tip').hide();
							$('.needPay').show();
						}
					}
				}
			})
		},
		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() {
			$('#upload').on('click', function() {
				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做处理的代码
								imgConsult.upLoadImg(serverId, localId);
								if (localIds.length > 0) {
									syncUpload(localIds);
								}
							}
						});
					};
					wx.chooseImage({
						count: 9,
						sizeType: ['original', 'compressed'],
						sourceType: ['album', 'camera'],
						success: function(res) {
							imgConsult.localIds = res.localIds;
							//所有需要上传到图片预览
							syncUpload(imgConsult.localIds);
						}
					})
				})
			})
		},
		//图片预览
		previewImage: function() {
			$('#ImgUp').on('click', '.image_files_img', function() {
				var imgArray = [];
				var curImageSrc = $(this).attr('src');
				if (curImageSrc) {
					$('#ImgUp .image_files_img').each(function(index, el) {
						var itemSrc = $(this).attr('src');
						imgArray.push(itemSrc);
					});
					wx.previewImage({
						current: curImageSrc,
						urls: imgArray
					});
				}
			});
			$('#ImgUp').on('click', '.image_del', function() {
				if (confirm('确定要删除图片吗？')) {
					$(this).parent().remove();
				}
			});
		},
		//上传图片
		upLoadImg: function(serverId, localId) {
			$.ajax({
				url: 'https://testdevgw.medtap.cn/common/uploadWechatFile',
				type: 'POST',
				async: false,
				headers:{
					'apptype':'wechat_lung',
					'user-os':'wechat'
				},
				data: {
					bizType: "3",
					folder: 'imgConsult',
					mediaId: serverId,
					ext: 'jpg'
				},
				success: function(data) {
					if (data.success == true) {
						var res = data.content;
						var imgKey = res.ossKey;
						imgConsult.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);
					}
				}
		
			})
		},
		checkValue:function(){
			var flag = false;
			if(!$('#disease_detail').val()){
				medtap.toast({
					message:'请输入疾病描述',
					time:1500
				})
				flag = false;
			}else if($('#disease_detail').val().length < 10){
				medtap.toast({
					message:'疾病描述不可少于10个字',
					time:1500
				})
				flag = false;
			}else if(!$('#expectation_help_detail').val()){
				medtap.toast({
					message:'请输入您想要咨询的内容',
					time:1500
				})
				flag = false;
			}else if($('#expectation_help_detail').val().length < 5 || $('#expectation_help_detail').val().length > 20){
				medtap.toast({
					message:'咨询内容只能输入5-20字',
					time:1500
				})
				flag = false;
			}else{
				flag = true;
			}
			
			return flag;
		}
	}
	imgConsult.init();
	imgConsult.choseImage();
	imgConsult.previewImage();
})