define(['zepto', 'medtap', 'mui', 'mui.picker'], function($, medtap, mui) {　

  var furtherConsultation = {
		wechatId: medtap.getRequest('wechatId'),
		// 获取问卷id
		followUpId: medtap.getRequest('followUpId')||'',
		// 修改人员id
		adminId: medtap.getRequest('adminId')||'',
		// 获取本题序号
		questionNo: medtap.getRequest('questionNo')||'',
		//  获取本题id
		questionId: medtap.getRequest('questionId')||'',
			//  获取parentId
		parentId: medtap.getRequest('parentId')||'',	
		// 判断选项
		judge: '',
    judgePicker: '',
		movePicker: '',
		// 选择有或者无
		flag: '',
		// 图片集合
		imgList: [],
		// 
		serverId: "",
		localIds: '',
		// 图片https://地址
		imgKey: '',
    init:function(){
			console.log(furtherConsultation.flag)
			// 点击删除图片
			$('#ImgUp').on('click', '.image_del', function() {
				var src = $(this).siblings('img').attr('src')
				var index	= furtherConsultation.imgList.findIndex(function(item){
					return item = src
			 })
			 console.log(index)
				if (confirm('确定要删除图片吗？')) {
					furtherConsultation.imgList.splice(index,1)
					$(this).parent().remove();	
				}
			});
		// 用户点击了无
			$('.noHas').on('tap',function(){
				furtherConsultation.flag=false
				console.log(furtherConsultation.flag)
			})
			// 用户点击了有
			$('.has').on('tap',function(){
				furtherConsultation.flag=true
				console.log(furtherConsultation.flag)
			})
      // tab切换（有无）
      $(".tabbox li").click(function (){
  　　　　//获取点击的元素给其添加样式，讲其兄弟元素的样式移除
  　　　　$(this).addClass("active").siblings().removeClass("active");
  　　　　//获取选中元素的下标
  　　　　var index = $(this).index();
  　　　　$(this).parent().siblings().children().eq(index).addClass("active")
  　　　　.siblings().removeClass("active");
			});
      // 点击下一题
      $('.next').on('tap',function(){
				if(furtherConsultation.flag){
					furtherConsultation.judgeVal = $.trim($('.input_item_judge').val())
					furtherConsultation.movePositionVal = $.trim($('.input_item_move').val())

					if(furtherConsultation.judgeVal==''){
						medtap.winPop('请选择医生对疗效的判断选项或者选无')
						return
					}
					switch(furtherConsultation.judgeVal){
						case '出现新发病灶或其他部位转移':
						// 如果没选突变位置
						if(furtherConsultation.movePositionVal==''){
						medtap.winPop('请选择转移部位')
						return
						}
						break;
					}
					// 选择有时候的数据
				var datahas =	{
					  "parentId":furtherConsultation.parentId,
						"questionId":furtherConsultation.questionId,
						"answer":{
							"judge":furtherConsultation.judgeVal,
							"movePositionVal":furtherConsultation.movePositionVal,
							"imgKey":furtherConsultation.imgList,
							"status":1
						},
						"questionNo": Number(furtherConsultation.questionId),
						"followUpId": furtherConsultation.followUpId
					}
					furtherConsultation.getNextQuestion(datahas)
				}else {
					// 选择无时候的数据
				var datano =	{
					  "parentId":furtherConsultation.parentId,
						"questionId":furtherConsultation.questionId,
						"answer":{"judge":'',"movePositionVal":'',"imgKey":[],"status":0},
						"questionNo": Number(furtherConsultation.questionId),
						"followUpId": furtherConsultation.followUpId
					}
					furtherConsultation.getNextQuestion(datano)	
				}
			
			})
			 // 点击上一题
			 $('.pre').on('tap',function(){
				furtherConsultation.getPreQuestion()
      })
      furtherConsultation.getWechatTicket();
      furtherConsultation.inintJudge();
      furtherConsultation.inintMove();
      furtherConsultation.selectItems();
    },
    // 初始化 题3.有没有复诊picker数据
    inintJudge:function(){
      furtherConsultation.judgePicker = new mui.PopPicker();
      furtherConsultation.judgePicker.setData([
        {value:'1',text:'肿瘤明显缩小'},
        {value:'2',text:'肿瘤稳定，无明显变化'},
        {value:'3',text:'肿瘤明显增大'},
        {value:'4',text:'出现新发病灶或其他部位转移'},
        {value:'5',text:'不清楚'},
      ]);
    },
    // 初始化转移部位picker数据
    inintMove:function(){
      furtherConsultation.movePicker = new mui.PopPicker();
      furtherConsultation.movePicker.setData([
        {value:'4-1',text:'无转移'},
        {value:'4-2',text:'脑转移'},
        {value:'4-3',text:'骨转移'},
        {value:'4-4',text:'肝转移'},
        {value:'4-5',text:'淋巴转移'},
        {value:'4-6',text:'肾及肾上腺转移'},
        {value:'4-7',text:'其他部位转移'},
      ]);
    },
    // 点击picker后的事件注册
    selectItems:function(){
          // 点击医生对疗效的判断
      $('.input_item_judge').click(function(){
        furtherConsultation.judgePicker.show(function (Items) {
          console.log(Items[0].text);
          console.log(Items[0].value);
          $('.input_item_judge').val(Items[0].text)
          if(Items[0].value=='4'){
            $('.content_body_height_box').show()
          }else{
            $('.content_body_height_box').hide()
            $('.input_item_move').val('')
          }
        })
      })
      // 点击转移部位
      $('.input_item_move').click(function(){
        furtherConsultation.movePicker.show(function (Items) {
          console.log(Items[0].text);
          console.log(Items[0].value);
          $('.input_item_move').val(Items[0].text)
        })
      })
    },
    getWechatTicket: function() {
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/wechat/lung/fetchWechatTicket',
				type: 'GET',
				async: false,
				data: {
					url: window.location.href
				},
				success: function(res) {
					console.log(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_img').on('click',function() {
        console.log('点击了选择图片')
				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做处理的代码
								furtherConsultation.upLoadImg(serverId, localId);
								if (localIds.length > 0) {
									syncUpload(localIds);
								}
							}
						});
					};
					wx.chooseImage({
						count: 9,
						sizeType: ['original', 'compressed'],
						sourceType: ['album', 'camera'],
						success: function(res) {
							console.log('选择图片的结果',res)
							furtherConsultation.localIds = res.localIds;
							//所有需要上传到图片预览
							syncUpload(furtherConsultation.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,
				data: {
					bizType: "3",
					folder: 'bbs',
					mediaId: serverId,
					ext: 'jpg'
				},
				headers:{
					'apptype':'wechat_lung',
					'user-os':'wechat'
				},
				success: function(data) {
					console.log('上传的data',data)
					if (data.success == true) {
						var res = data.content;
						var imgKey = res.url;
						furtherConsultation.imgList.push(imgKey);
						console.log('上传后图片的imgKey',imgKey)
						console.log(localId)
						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);
					}
				}

			})
		},
		 // 获取问题答案
		getQuestionAnswer: function(){
			var crm = furtherConsultation.adminId==''? '':'/crm'
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/operation/followUp'+crm+'/getAnswer',
				type: 'post',
				async: false,
				contentType: 'application/json',
				data: {
					"followUpId": furtherConsultation.followUpId,
					"questionId": furtherConsultation.questionId,
				},
				success: function(res) {
					console.log(res)  
					if(!res.success) return medtap.winPop('获取数据失败')
					// 如果没做过题那么answer没有
					if(!res.content.followAnswer.answer) {
            furtherConsultation.flag=true
            return
          }
					if(res.content.followAnswer.answer.status=='0'){
						$('.noHas').addClass('active').siblings('.has').removeClass('active')
						$('.content_select_no').addClass('active').siblings('.content_select').removeClass('active')
						furtherConsultation.flag=false
						return
					}
					if(res.content.followAnswer.answer.judge=="出现新发病灶或其他部位转移"){
						$('.content_body_height_box').show()
				 }
				 if(res.content.followAnswer.answer.status=='1'){
					furtherConsultation.flag=true
					$('.input_item_move').val(res.content.followAnswer.answer.movePositionVal||'')
					$('.input_item_judge').val(res.content.followAnswer.answer.judge||'')
					// 图片相关操作。。
					var imgList = res.content.followAnswer.answer.imgKey
					furtherConsultation.imgList = res.content.followAnswer.answer.imgKey
					var html =''
					if(imgList.length>0){
						for(var i = 0;i<imgList.length;i++){
						html+='<div class="image_files_item">' +
							'<img src="' + imgList[i] + '" class="image_files_img">' +
							'<img src="../images/post_delete_btn@2x.png" class="image_del" >' +
							'</div>';
						}
						$('#ImgUp').append(html)
					}
				 }
				}
			})
		},
		// 上一题
		getPreQuestion:function(){
			var crm = furtherConsultation.adminId==''? '':'/crm'
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/operation/followUp'+crm+'/previousQuestion',
				type: 'post',
				async: false,
				contentType: 'application/json',
				data: {
					"questionId":furtherConsultation.questionId,
					"questionNo":furtherConsultation.questionNo,
					"followUpId":furtherConsultation.followUpId,
				},
				success: function(res) {
					console.log(res)
					if(!res.success) return medtap.winPop('获取数据失败')
					var parentId = res.content.previousQuestion.parentId||''
					var questionId = res.content.previousQuestion.questionId||''
					var questionNo = res.content.previousQuestion.questionNo||''
					medtap.pushWindow('questionnaireWeight.html?followUpId='+furtherConsultation.followUpId+'&questionId='+questionId+'&questionNo='+questionNo+'&parentId='+parentId+'&adminId='+furtherConsultation.adminId);
				}
			})
		},
		 // 下一题
		getNextQuestion:function(data){
			var crm = furtherConsultation.adminId==''? '':'/crm'
			medtap.submitAjax({
				url: 'https://testdevgw.medtap.cn/operation/followUp'+crm+'/nextQuestion',
				type: 'post',
				async: false,
				contentType: 'application/json',
				data: data,
				success: function(res) {
					console.log(res)
					if(!res.success) return medtap.winPop('获取数据失败')
					// 获取下一题的id和序号通过url传递
					var parentId = res.content.nextQuestion.parentId||''
					var questionId = res.content.nextQuestion.questionId||''
					var questionNo = res.content.nextQuestion.questionNo||''
						medtap.pushWindow('targetedTherapy.html?followUpId='+furtherConsultation.followUpId+'&questionId='+questionId+'&questionNo='+questionNo
						+'&parentId='+parentId+'&adminId='+furtherConsultation.adminId);
				}
			})
		}
  }
  furtherConsultation.init();
  furtherConsultation.getQuestionAnswer();
  furtherConsultation.choseImage();
	furtherConsultation.previewImage();
})