$(function(){
	var request = getRequest(),
	    teamCode = request.id,
	    isLeader = isTeamLeader(),
	    prescriptionCode = request.code;
    
    var medicineFreqData = [];
    var usageDict = [];
    var isChangeDiagnosis = 0; //判断是否改变疾病类型
    var $main = $('#main');
    
    template.helper('toJson',function(o) {
    	if(o) {
    		return JSON.stringify(o)
    	}
    	return "";
    })
    
    Promise.all([
    	prescriptionDetailApis.getContinuedPrescriptionAsDoctor({
	    	data: {
	    		code: prescriptionCode, // 续方CODE
	    		type: isLeader?1:2 // 是否为团队长，1：是，2:否
	    	}
	    }),
	    prescriptionDetailApis.getRateList({data:{}}),
	    prescriptionDetailApis.getUsageDict({data:{}}),
	    prescriptionDetailApis.getReasonByType({data: {type:1}})
    ]).then(function(responses) {
    	var prescriptionInfo = responses[0].data;
    	var reasonTypes = responses[3].data;
    	$main.html(template('detailTmpl', $.extend({},prescriptionInfo, {reasonTypes:reasonTypes})))
    	medicineFreqData = responses[1].data
    	usageDict = responses[2].data
    	
    	showDiagnosisBtn()
    	
		bindEvents()
		initDiagnosisSuggestInput()
		initDrugNameSuggestInput()
		initFreqSuggestInput()
		initDaySuggestInput()
		initUsageSuggestInput()
		calcWorldWithTextarea()
    }).catch(function(e) {
    	console && console.error(e)
    })
    
    function showDiagnosisBtn() {
    	if($('#diagnosis li').length >= 3) {
			$('#addDiagnosisBtn').hide()
		} else {
			$('#addDiagnosisBtn').show()
		}
    }
    
    function bindEvents() {
    	
    	$('#addDrugBtn').click(function() {
    		var html = template('drugTmpl',{})
    		$('#drugs').append(html)
    		initDrugNameSuggestInput()
    		initFreqSuggestInput()
			initDaySuggestInput()
			initUsageSuggestInput()
    	})
    	
    	$('#adjustReason').on('click','li',function() {
    		if($(this).hasClass('active')) {
    			$(this).removeClass('active')
    		} else {
    			$(this).addClass('active')
    		}
    		setAdjustReason()
    	})
    	
    	$('#drugs').on('click','.icon-shanchu',function() {
    		$(this).closest('.ibox-content').remove();
    	}).on('click','.icon-jianshao',function() {
    		var $input = $(this).closest('li').find('input').eq(0);
    		var amount = parseFloat($input.val()||'0')
    		if(amount > 0) {
    			if($input.hasClass('j-medi-single')) {
	    			$input.val(amount - 0.25)
	    		} else {
	    			$input.val(amount - 1)
	    		}
    		} else {
    			$input.val(0)
    		}
    		var $box = $(this).closest('.ibox-content')
	        countMediSum($box)
    	}).on('click','.icon-xinzeng',function() {
    		var $input = $(this).closest('li').find('input').eq(0);
    		var amount = parseFloat($input.val()||'0')
    		if($input.hasClass('j-medi-single')) {
    			$input.val(amount + 0.25)
    		} else {
    			$input.val(amount + 1)
    		}
    		
    		var $box = $(this).closest('.ibox-content')
	        countMediSum($box)
    	}).on('blur', 'input.j-medi-single, input.j-selDate, input.j-selFreq',function() {
    		var $box = $(this).closest('.ibox-content')
    		if(!$(this).val().trim()) {
    			$(this).attr('data-code','')
    			$sum = $box.find('.j-sumMedicine')
    			$sum.attr('data-num','')
    			$sum.text('')
    		}
	        countMediSum($box)
    	})
    	
    	$('.diagnosis-wrap').on('click',function() {
    		$('#placeholdText').hide()
    		$('#diagnosisInput').show()
    		$('#diagnosisInput').focus()
    	})
    	
    	$('#addDiagnosisBtn').on('click',function() {
    		$(this).hide();
    		$('.diagnosis-wrap').show();
    		setTimeout(function() {
    			$('#diagnosisInput').click()
    		},100)
    	})
    	
    	$('#diagnosisInput').on('blur keydown',function(e) {
    		if(e.type == 'keydown' && e.keyCode == 13) {
    			$('#diagnosisInput').blur()
    		} else {
    			if(e.type == 'blur') {
    				var name = $('#diagnosisInput').val()
	    			var code = $('#diagnosisInput').attr('data-code')
    				var isSelected = $('#diagnosis li[data-code="'+ code +'"]').length>0?true:false // 该诊断结果是否已选择
	    			$('#placeholdText').show()
	    			$('#diagnosisInput').hide()
	    			
	    			if(name && code && !isSelected) {
	    				isChangeDiagnosis = 1;
	    				var html = template('diagnosisTmpl', {data:{name: name,code:code}})
	    				$('#diagnosis').append(html)
	    			}
	    			$('#diagnosisInput').val('')
	    			$('#diagnosisInput').attr('data-code','')
	    			
	    			showDiagnosisBtn()
	    			
	    			$('.diagnosis-wrap').hide()
	    		}
    		}
    	})
    	
    	$('#diagnosis').on('click', '.fa-close' ,function() {
    		$(this).closest('li').remove()
    		isChangeDiagnosis = 1;
    		showDiagnosisBtn()
    	})
    	$('#backBtn').on('click',function() {
    		history.go(-1);
    	})
    	$('#confirmBtn').click(function(){
			var $sum = $(".j-sumMedicine");
			if($sum.length > 0){
				for(var i=0;i<$sum.length;i++){
					var $box = $sum.eq(i).closest('.ibox-content')
					var $method = $box.find('.j-method')
					if(! $sum.eq(i).attr('data-num') || !$method.val() || !$method.attr('data-id')){
						showErrorMsg('请完善药品信息')
						return 
					}
				}
			}else{
				showErrorMsg('请添加药品')
				return ;
			}
	
			var msgArr = [],
				$box = $('#drugs .ibox-content');
			for(var i=0;i<$box.length;i++){
				var data = {};
				var saveData = JSON.parse($box.eq(i).attr('data-json'));
				data.prescriptionCode = prescriptionCode;
				data.drugCode = saveData.drugCode;
				data.drugName = $box.eq(i).find('.j-drugName').val().replace(/\(/,'（').replace(/\)/,'）');
				data.drugRate = $box.eq(i).find('.j-selFreq').attr('data-code');
				data.drugRateName = $box.eq(i).find('.j-selFreq').val();
	   		    data.drugFormat=saveData.drugFormat.replace(/\(/,'（').replace(/\)/,'）'); 
	   		    data.subjectClass = $box.eq(i).attr('data-class');
	   		    data.isRefrigerate = $box.eq(i).attr('data-storage')==2?1:0;
		 		data.physicAmount = "";
		 		data.physicAmountUnit = saveData.physicAmountUnit;
		 		data.physicAmountUnitName = saveData.physicAmountUnitName;
		 		data.physicDose = $box.eq(i).find('.j-medi-single').val().trim();
		 		data.physicDoseUnit = $box.eq(i).find('.j-dose-unit').attr('data-unit');
		 		data.physicDoseUnitName = $box.eq(i).find('.j-dose-unit').text(); 
		 		data.drugNumUnit = $box.eq(i).find('.j-sumMedicine').attr('data-unit');//取当次用量单位
		 		data.drugNumUnitName = $box.eq(i).find('.j-sumMedicine').attr('data-name'); 
		 		data.drugUsage= $box.eq(i).find('.j-method').attr('data-code');
		 		data.usageName= $box.eq(i).find('.j-method').val();
		 		data.num= $box.eq(i).find(".j-sumMedicine").attr('data-num');//取总量
		 		data.dayCount=$box.eq(i).find('.j-selDate').val();
		     	msgArr.push(data);   
			}
			//调整CODE
			var reasonCode= _.map($('#adjustReason li.active'),function(el) {
    				return $(el).attr('data-code')
    			}).join(',')
			var params= {
				code:prescriptionCode,
				infos:JSON.stringify(msgArr),
				reason:$('#adjustReasonTextarea').val().trim()?$('#adjustReasonTextarea').val().trim():'-',
				reasonCode:reasonCode,
				diagnosis:(function(){
					// TODO
					var diagnosis = [];
					if(isChangeDiagnosis) {
						diagnosis = _.map($('#diagnosis li'),function(el) {
							var data = JSON.parse($(el).attr('data-json'))
							return {
								code: data.code,
								name: data.name
							}
						})
						return JSON.stringify(diagnosis)
					}
					return ""
				})()
			}
			
			if($('#diagnosis li').length == 0) {
				showErrorMsg('请添加诊断结果')
				return ;
			}
			
			
			prescriptionDetailApis.updatePresInfo({
				data: params
			}).then(function(res) {
				if(res.status == 200){
					showSuccessMsg("保存成功")
					setTimeout(function() {
						location.reload(true)
					}, 2000)
				} else {
					showErrorMsg(res.msg || "保存失败")
				}
			})
			
		})
    }
	function setAdjustReason() {
		var reasons = _.map($('#adjustReason li.active'),function(el) {
			return $.trim($(el).text())
		});
		if(reasons && reasons.length) {
			$('#adjustReasonTextarea').val(reasons.join(','))
			$('#adjustReasonTextarea').focus()
		}
	}
	function initDiagnosisSuggestInput() {
		$('#diagnosisInput').bsSuggest({
	      url: APIService.server+'doctor/prescriptionInfo/getIcd10Info?nameKey=',
	      getDataMethod:'url',
	      idField: "code",
          keyField: "name",
	      effectiveFields: ['name'],
	      ignorecase: true,
	      fnProcessData: function(res) {
	      	return {
	      		value: res.data
	      	}
	      }
	    }).on('onSetSelectValue', function (e, v) {
	        $(this).attr('data-code', v.id)
	    })
	}
	
	function initDrugNameSuggestInput() {
		$("input.j-drugName").bsSuggest({
	      url: APIService.server+'doctor/prescriptionInfo/findDictByName?name=',
	      getDataMethod:'url',
	      idField: "drugCode",
          keyField: "drugName",
	      effectiveFields: ['drugName','drugFormat'],
	      effectiveFieldsAlias:{drugName: "药品名称",drugFormat:"规格"},
	      ignorecase: true,
	      fnProcessData: function(res) {
	      	return {
	      		value: res.data
	      	}
	      }
	    }).on('onSetSelectValue', function (e, v) {
	        var $box = $(this).closest('.ibox-content'),
	        	$single = $box.find(".j-medi-single"),
	        	$doseUnit = $box.find('.j-dose-unit'),
				$freq = $box.find(".j-selFreq"),
				$date = $box.find(".j-selDate"),
				$sum = $box.find('.j-sumMedicine'),
				$method = $box.find('.j-method');
			var json = v.json;	
			$box.attr('data-json',JSON.stringify(json))
			$single.val(json.physicDose)
			$single.attr('data-code', json.physicDoseUnit)
			$doseUnit.text(json.physicDoseUnitName)
			$doseUnit.attr('data-unit', json.physicDoseUnit)
			$freq.val(json.drugRateName||"")
			$freq.attr('data-code', json.drugRate)
			$date.val(json.dayCount||"")
			$sum.text('')
			$method.val('')
			$method.attr('data-code','')
	    })
	}
	
	function initFreqSuggestInput() {
		$("input.j-selFreq").bsSuggest({
	      data: {value: medicineFreqData},
	      idField: "code",
          keyField: "name",
	      getDataMethod:'data',
	      effectiveFields: ['name'],
	      ignorecase: true
	    }).on('onSetSelectValue', function (e, v) {
	        $(this).attr('data-code', v.id)
	        var $box = $(this).closest('.ibox-content')
	        countMediSum($box)
	    })
	}
	
	function initDaySuggestInput() {
		$("input.j-selDate").bsSuggest({
	      data: {value: _.map(_.range(1, 31),function(v) {
	      	return {
	      		day: v
	      	}
	      })},
	      idField: "day",
          keyField: "day",
	      getDataMethod:'data',
	      effectiveFields: ['day'],
	      ignorecase: true
	    }).on('onSetSelectValue', function (e, v) {
	        var $box = $(this).closest('.ibox-content')
	        countMediSum($box)
	    })
	}
	
	function initUsageSuggestInput() {
		$("input.j-method").bsSuggest({
	      data: {value: usageDict},
	      idField: "code",
          keyField: "name",
	      getDataMethod:'data',
	      effectiveFields: ['name'],
	      ignorecase: true
	    }).on('onSetSelectValue', function (e, v) {
	        
	    })
	}
	
	//计算药品总量
	function countMediSum($box){
		var single = $box.find(".j-medi-single").val(),
			freq = $box.find(".j-selFreq").attr('data-code'),
			date = $box.find(".j-selDate").val(),
			$sum = $box.find('.j-sumMedicine'),
			$info = JSON.parse($box.attr('data-json'));
		if(!single || !freq || !date) {
			return ;
		} else {
			single = single.trim();
			freq = freq.trim();
			date = date.trim();
		}
		if(single && freq && date){
			prescriptionDetailApis.drugToRate({data:{code: freq}}).then(function(res){
				if(res.status == 200){
					var rate = res.data.rate
					var num = single*rate*date
					var sum="";
					if($info.pakeSpec){
						//新增药品
						sum = Math.ceil(num/$info.minDose)
						$sum.text(sum+$info.drugNumUnitName)
						$sum.attr('data-num',sum)
						$sum.attr('data-name',$info.drugNumUnitName);
						$sum.attr('data-unit',$info.drugNumUnit);
					}else{
						var drugNumUnit = $info.drugNumUnit,
							physicDoseUnit = $info.physicDoseUnit;			
						//请求药品信息
						var drugCode = $info.drugCode;
						
						prescriptionDetailApis.getPhysicInfo({data:{code: drugCode}}).then(function(res){
							if(res.status == 200){
								var msg = res.data[0]
								$box.attr('data-storage',msg.storageConditions);//冷藏
								$box.attr('data-class',msg.subjectClass);
								if(drugNumUnit == physicDoseUnit){
									sum = num
								}else{
									if(drugNumUnit == msg.pack_unit){
										sum = Math.ceil(num/msg.packSpec)
									}else{
										sum = Math.ceil(num/msg.minDose)
									}
								}
								$sum.text(sum+$info.drugNumUnitName)
								$sum.attr('data-num',sum)
								$sum.attr('data-name',$info.drugNumUnitName);
								$sum.attr('data-unit',$info.drugNumUnit);
							}
						})
					}
				}		
			})
		}
	}	
	
})