define(['zepto','medtap'],function($,medtap){
	var consult = {
		doctorId:medtap.getRequest('doctorId'),
		localIds: [],
		serverId: "",
		imgList: [],
		pmdOrderSn:medtap.getRequest('pmdOrderSn'),
		isPmd:false,
		consultCount:0,
		init:function(){
			$('.doctor_name').text(medtap.getRequest('doctorname') + ' 医生')
			consult.getWechatTicket();
			consult.confirmConsultOrder();
			consult.bindEve();
		},
		bindEve:function(){
			$('.submit').unbind().bind('click',function(){
				var result = consult.checkValue();
				if(result == true){
					if(consult.pmdOrderSn != '' || consult.pmdOrderSn != 'undefined'){
						if(consult.isPmd == true && consult.consultCount > 0){
							consult.freeOrder();
						}else{
							consult.createConsultOrder();
						}
					}else{
						consult.createConsultOrder();
					}
				}
			})
			$('.contact_helper').unbind().bind('click',function(){
				window.location.href = "tel:4000059900"
			})
		},
		confirmConsultOrder:function(){
			medtap.loading(1);
			medtap.submitAjax({
				url:'https://testdevgw.medtap.cn/trade/consult/confirmConsultOrder',
				type:'post',
				async:false,
				contentType: "application/json",
				data:{
					doctorId:consult.doctorId,
					pmdOrderSn:consult.pmdOrderSn
				},
				success:function(res){
					medtap.loading(0);
					if(res.success == true){
						var result = res.content.result;
						consult.isPmd = result.isPmd;
						consult.consultCount = result.consultCount;
						$('.free_price').html(result.totalFee + '/次');
						$('.pay_price').html(result.totalFee + '/次');
						if(consult.consultCount != 0 && consult.isPmd == true){
							$('.for_free').show();
							$('.need_pay').hide();
						}else{
							$('.for_free').hide();
							$('.need_pay').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做处理的代码
								consult.upLoadImg(serverId, localId);
								if (localIds.length > 0) {
									syncUpload(localIds);
								}
							}
						});
					};
					wx.chooseImage({
						count: 9,
						sizeType: ['original', 'compressed'],
						sourceType: ['album', 'camera'],
						success: function(res) {
							consult.localIds = res.localIds;
							//所有需要上传到图片预览
							syncUpload(consult.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: 'consult',
					mediaId: serverId,
					ext: 'jpg'
				},
				success: function(data) {
					if (data.success == true) {
						var res = data.content;
						var imgKey = res.ossKey;
						consult.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(!$('#tel_phone').val()){
				medtap.toast({
					message:'请输入联系电话',
					time:1500
				});
				flag = false;
			}else 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;
		},
		//创建免费订单
		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/consult/submitConsultOrderByPmd',
				type:'post',
				async: false,
				contentType: 'application/json',
				data:{
					doctorId:consult.doctorId,
					pmdOrderSn:medtap.getRequest('pmdOrderSn'),
					diseaseDescription:$('#disease_detail').val(),
					expectationHelp:$('#expectation_help_detail').val(),
					mobile:$('#tel_phone').val(),
					picUrl:picUrl
				},
				success:function(res){
					medtap.loading(0);
					if(res.success == true){
						var orderDetail = res.content.order;
						setTimeout(function(){
							medtap.pushWindow('pages/success.html?orderSn=' + orderDetail.orderSn + '&wechatId=' + medtap.getRequest('wechatId'));
						},1000);
					}
				}
			})
		},
		//创建付费订单
		createConsultOrder: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/consult/submitConsultOrder',
				type:'post',
				async: false,
				contentType: 'application/json',
				data:{
					doctorId:consult.doctorId,
					diseaseDescription:$('#disease_detail').val(),
					expectationHelp:$('#expectation_help_detail').val(),
					mobile:$('#tel_phone').val(),
					picUrl:picUrl
				},
				success:function(res){
					medtap.loading(0);
					if(res.success == true){
						var orderDetail = res.content.order;
						setTimeout(function(){
							medtap.pushWindow('pages/success.html?orderSn=' + orderDetail.orderSn + '&wechatId=' + medtap.getRequest('wechatId'));
						},1000);
					}
				}
			})
		}
	}
	consult.init();
	consult.choseImage();
	consult.previewImage();
})