define(['zepto', 'medtap'], function($, medtap) {
	var newCard = {
		cardId:medtap.getRequest('id'),
		localIds: [],
		serverId: "",
		imgList: [],
		init: function() {
			newCard.getWechatTicket();
			newCard.bindEve();
			if(!newCard.cardId){
				
			}else{
				newCard.getEditById();
			}
		},
		bindEve: function() {
			/* 新加文本输入框字数限制与动态字数 */  
			$("#area").on("input propertychange", function() {  
        var $this = $(this),  
            _val = $this.val(),  
            count = "";  
        if (_val.length > 300) {  
						$this.val(_val.substring(0, 300)); 	
        }  
        count = $this.val().length;  
        $("#text-count").text(count);  
    });  
			$('.footer_btn').on('click', function() {
				if(!newCard.cardId){
					newCard.postPubbbs();
				}else{
					newCard.updatePubbs(newCard.cardId);
				}
			})
		},
		getWechatTicket: function() {
			medtap.submitAjax({
				url: 'https://gateway.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做处理的代码
								newCard.upLoadImg(serverId, localId);
								if (localIds.length > 0) {
									syncUpload(localIds);
								}
							}
						});
					};
					wx.chooseImage({
						count: 9,
						sizeType: ['original', 'compressed'],
						sourceType: ['album', 'camera'],
						success: function(res) {
							newCard.localIds = res.localIds;
							//所有需要上传到图片预览
							syncUpload(newCard.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://gateway.medtap.cn/common/uploadWechatFile',
				type: 'POST',
				async: false,
				data: {
					bizType: "3",
					folder: 'bbs',
					mediaId: serverId,
					ext: 'jpg'
				},
				headers:{
					'apptype':'wechat_lung',
					'user-os':'wechat'
				},
				success: function(data) {
					if (data.success == true) {
						var res = data.content;
						var imgKey = res.ossKey;
						newCard.imgList.push(imgKey);
						console.log('上传后图片的imgKey',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);
					}
				}

			})
		},
		postPubbbs: function() {
			var strLength =  $.trim($('.card_content').val())
			if(strLength.length<20){
				medtap.toast({
					message: '字数不能少于20字',
					time: 2000
				})
				return
			}
			var urls = [],
				picUrl = "";
			[].forEach.call($('#ImgUp .image_files_img'), function(item) {
				urls.push($(item).attr('imgkey'));
			});
			var picUrl = urls.join(',');
			// console.log('新建的图片数据',picUrl)
			medtap.loading(1);
			medtap.submitAjax({
				url: 'https://gateway.medtap.cn/operation/pubbbs/publish',
				type: "POST",
				asynv: false,
				contentType: 'application/json',
				data: {
					groupId:parseInt(medtap.getRequest('groupId')),
					content: $('.card_content').val(),
					picUrls: picUrl
				},
				success: function(res) {
					medtap.loading(0);
					if (res.success == true) {
						setTimeout(function() {
							medtap.toast({
								message: '发布成功！请等待审核',
								time: 2000
							})
							setTimeout(function(){
								//medtap.pushWindow('myCardList.html');
								if(!newCard.cardId){
									medtap.pushWindow('myCardList.html');
								}else{
									window.history.go(-1)
								}
							},1000)
						}, 1000)
					}
				}
			})
		},
		updatePubbs:function(id){
			var strLength =  $.trim($('.card_content').val())
			if(strLength.length<20){
				medtap.toast({
					message: '字数不能少于20字',
					time: 2000
				})
				return
			}
			var urls = [],
				picUrl = "";
			[].forEach.call($('#ImgUp .image_files_img'), function(item) {
				urls.push($(item).attr('imgkey'));
			});
			var picUrl = urls.join(',');
			// console.log('更新的图片数据',picUrl)
			medtap.loading(1);
			medtap.submitAjax({
				url: 'https://gateway.medtap.cn/operation/pubbbs/publish/mineUpdate',
				type: "POST",
				asynv: false,
				contentType: 'application/json',
				data: {
					id:parseInt(id),
					content: $('.card_content').val(),
					picUrls: picUrl
				},
				success: function(res) {
					// console.log(res)
					medtap.loading(0);
					if (res.success == true) {
						setTimeout(function() {
							medtap.toast({
								message: '发布成功！请等待审核',
								time: 2000
							})
							setTimeout(function(){
								// medtap.pushWindow('myCardList.html');
								// window.history.go(-1)
								window.location.replace('myCardList.html')
							},1000)
						}, 1000)
					}
				}
			})
		},
		getEditById:function(){
			medtap.loading(1);
			medtap.submitAjax({
				url:'https://gateway.medtap.cn/operation/pubbbs/publish/' + newCard.cardId,
				type:'GET',
				async: false,
				data:{
					
				},
				success:function(res){
					medtap.loading(0);
					if(res.success == true){
						var detailInfo = res.content.publish;
						$('.card_content').val(detailInfo.content);
						if(detailInfo.hasOwnProperty('picUrls')){
							var imgHtml = ''
							for(var i = 0;i < detailInfo.picUrls.length;i++){
								imgHtml += /* '<img src="'+detailInfo.picUrls[i]+'" >'; */
								'<div class="image_files_item">' +
									'<img src="'+detailInfo.picUrls[i]+'" class="image_files_img" imgkey="'+detailInfo.picUrls[i]+'">' +
									'<img src="../images/post_delete_btn@2x.png" class="image_del" >' +
									'</div>';
							}
							$('#ImgUp').html(imgHtml);
						}
					}
				}
			})
		}
	}
	newCard.init();
	newCard.choseImage();
	newCard.previewImage();
})
