
$(function(){
	//获取团队信息
	var request = getRequest(),
	    teamCode = request.id,
	    docInfo = JSON.parse(window.localStorage.getItem('docInfo')),
	    isLeader = isTeamLeader() && (teamCode == docInfo.adminTeamCode),
	    prescriptionCode = request.code,
	    from = request.from, // 判断是否是tab页加载进来
	    fromTabIdx = request.fromTabIdx; 
    
    var $main = $('#main');
    
    var jwHospital = '',
    	jwDoctorCode = '';

    // 认证专用
    var strOriginalData;
    
    template.helper('idcardWidthStar',function(idcard) {
    	if(idcard) {
    		if(idcard.length == 18) {
    			return idcard.substring(0,8) +'********'+idcard.substring(16,18)
    		} else {
    			idcard.substring(0,5) +'********'+idcard.substring(16,18)
    		} 
    	}
    	return "";
    })
    
    template.config("escape", false);
    
    template.helper('getStatusName',function(status) {
    	return getStatusName(status)
    })
    
    template.helper('getReviewResultName',function(status) {
    	return getReviewResultName(status)
    })
    template.helper('setStatus',function(o){
		if(o == -3){ return '<span style="color:#999">续方取消（24小时未支付）</span>' }
		if(o == -2){ return '<span style="color:#999">续方取消（居民主动取消）</span>' }
		if(o == -1){ return '<span style="color:#ff4c4c">审核未通过</span>' }
		if(o == 0 || o == 10){ return '<span style="color:#ffa54b">审核中</span>' }
		if(o == 2){ return '<span style="color:#ffa54b">调整中</span>' }
		if(o == 3){ return '<span style="color:#ffa54b">调整成功/待ca认证</span>' }
		if(o == 4){ return '<span style="color:#ffa54b">调整失败</span>' }
		if(o == 20){ return '<span style="color:#ffa54b">药师审核中</span>' }
		if(o == 21){ return '<span style="color:#ff4c4c">药师审核失败</span>' }
		if(o == 30){ return '<span style="color:#ffa54b">开方中</span>' }
		if(o == 31){ return '<span style="color:#ff4c4c">开方失败</span>' }
		if(o == 40 || o == 41){ return '<span style="color:#db6bbd">待支付</span>' }
		if(o == 50){ return '<span style="color:#ffa54b">配药中</span>' }
		if(o == 60){ return '<span style="color:#db6bbd">等待领药</span>' }
		if(o == 61 || o == 62 || o == 65 || o == 69){ return '<span style="color:#06bf04">配送中</span>' }
		if(o == 100){ return '<span style="color:#17b3ec">已完成</span>' }
	})
   	template.helper('setRestTime',function(minDate,sDate){
   		
   		if(!minDate || !sDate) {
		   	return ""
		}
   		
		var now = getNowDate();
		var createDate = sDate.split(' ');
		var diff = getDays(createDate[0],now);
		if(diff<minDate){
			return '<span style="color:#17b3ec">'+(minDate-diff)+'天</span>'
		}else{
			return '<span style="color:#ff4c4c">已用完</span>'
		}
	})
	//相隔几天
	function getDays(sDate,eDate){
	   var oDate1;
	   var oDate2;
	   var iDays;
	   oDate1= sDate.split("-");
	   oDate2= eDate.split("-");
	   var strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
	   var strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
	   iDays = parseInt(Math.abs(strDateE - strDateS ) / 1000 / 60 / 60 /24)
	   return iDays ;
	}
	//现在时间
	function getNowDate() {
		var date = new Date();
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var day = date.getDate();
		var hour = date.getHours();
		var minute = date.getMinutes();
		var second = date.getSeconds();
		return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
	}
	
	
    prescriptionDetailApis.getContinuedPrescriptionAsDoctor({
    	data: {
    		code: prescriptionCode, // 续方CODE
    		type: isLeader?1:2 // 是否为团队长，1：是，2:否
    	}
    }).then(function(res) {
    	if(res.status == 200) {
    		var detailData = res.data;
			var prescription = detailData.prescription;
	    	var diagnosis = detailData.diagnosis;
	    	var patient = detailData.patient;
	    	strOriginalData = detailData;
	    	jwHospital = prescription.jwHospital;
	    	jwDoctorCode = prescription.jwDoctorCode;
	    	var diagnosisNames = _.pluck(diagnosis,'name').join('、')
    		prescriptionDetailApis.getPrescription({
    			data: {
    				code: prescriptionCode, 
    				patient: patient.code
    			}
    		}).then(function(res) {
				
				if(res.status == 200) {
					
					if(isLeader) {
			    		getDataPromises().then(function(responses) {
				    		var deptRes = responses[0],
				    			feeRes = responses[1],
				    			authRes = responses[2],
				    			reasonRes = responses[3];
				    			
				    		$main.html(template('detailTmpl',$.extend({}, detailData , {
				    			primary: res.data,
				    			diagnosisNames: diagnosisNames,
				    			depts: deptRes.data,
				    			feeRes: feeRes.data,
				    			isAuthentication: authRes.data.type == 4,
				    			isLeader: isLeader,
				    			reasonTypes: reasonRes.data
				    		})))
				    		
				    		bindEvents()
				    	}).catch(function(e) {
				    		showErrorMsg('初始化失败')
				    	})
			    	} else {
			    		$main.html(template('detailTmpl',$.extend({}, detailData , {
			    			primary: res.data,
			    			diagnosisNames: diagnosisNames,
			    			isLeader: isLeader
			    		})))
		
			    		bindEvents()
			    	}
				}else {
		    		showErrorMsg(res.msg)
		    	}
		    	
    		}).catch(function(e){
    			console && console.error(e)
    		})
    		
	    	
    	} else {
    		showErrorMsg(res.msg)
    	}
    	
    }).catch(function(e){
		console && console.error(e)
	})
    
    function bindEvents() {
    	$('#auditResultSel').on('change',function() {
			var value = $(this).val();
			if(value == 1) {
				$('#disagreeAudit').hide();
				$('#agreeAudit').show();
			} else if(value == 2) {
				$('#agreeAudit').hide();
				$('#disagreeAudit').show();
			} else {
				$('#agreeAudit').hide();
				$('#disagreeAudit').hide();
			}
		})
    	
    	$('#reviewBtn').on('click',function() {
    		var result = $('#auditResultSel').val();
    		var data = {
    				code: prescriptionCode, // 续方CODE
    				reason: '', // 不同意原因
    				reasonCode: '', // 不同意原因CODE
    				state: '', // 1同意,2不同意
    				dept: '', // 科室
    				registerFee: '', // 诊金
    				rateTypeCode: '' // 诊金类型
    			}
    		if(result == 1) { // 审核通过
    			if(!checkAgreeInputs()) {
    				return ;
    			}
    			$('#reviewBtn').attr('disabled','disabled')
    			var params ={
	    			strRealNameSoftCertCalledPasswd: $('#reviewPassword').val(),
	    			strOriginalData:JSON.stringify(getStrOriginalData()),
	    			prescriptionCode:prescriptionCode
	    		}
    			prescriptionDetailApis.requestRealNameSoftCertAndSign({
    				data: params
    			}).then(function(res) {
    				if(res.status==200 && res.data){
    					var feesel = $('#feeSel').val().split(' ');
    					prescriptionDetailApis.reviewPrescription({
			    			data: {
			    				code: prescriptionCode, // 续方CODE
			    				state: 1, // 1同意,2不同意
			    				dept: $('#deptSel').val(), // 科室
			    				registerFee: feesel[1], // 诊金
			    				rateTypeCode: feesel[0] // 诊金类型
			    			}
			    		}).then(function(res) {
			    			if(res.status == 200 && res.data){
			    				showSuccessMsg('提交成功')
			    				setTimeout(function() {
			    					location.reload(true)
			    				}, 2000)
			    			} else {
			    				showErrorMsg(res.msg)
			    				$('#reviewBtn').removeAttr('disabled')
			    			}
			    		})
    				} else {
    					showErrorMsg(res.msg)
    					$('#reviewBtn').removeAttr('disabled')
    				}
    			}).catch(function(e) {
    				showErrorMsg(e)
    			})
    		} else if(result == 2){ // 审核不通过
    			if(!checkDisAgreeInputs()) {
    				return ;
    			}
    			var reason = $('#disagreeReason').val();
				var reasonType = _.map($('#adjustReason li.active'),function(el) {
    				return $(el).attr('data-code')
    			}).join(',');
    			prescriptionDetailApis.reviewPrescription({
	    			data: {
	    				code: prescriptionCode, // 续方CODE
	    				state: 2, // 1同意,2不同意
	    				reason: reason || "-", // 不同意原因
    					reasonCode: reasonType // 不同意原因CODE
	    			}
	    		}).then(function(res) {
	    			if(res.status == 200 && res.data){
	    				showSuccessMsg('提交成功')
	    				setTimeout(function() {
	    					location.reload(true)
	    				}, 2000)
	    			} else {
	    				$('#reviewBtn').removeAttr('disabled')
	    			}
	    		}).catch(function(e) {
    				showErrorMsg(e)
    			})
    		} else {
    			showErrorMsg("请选择审核结果")
    		}
    		
    	})
    	
    	$('#editBtn').on('click',function() {
    		location.href = 'prescription-adjustment.html?code='+prescriptionCode
    	})
    	
    	$('#backBtn').on('click',function() {
    		if(from == 'tab') {
    			top.toPrePrescriptionTab && top.toPrePrescriptionTab()
    		} else {
    			history.go(-1);
    		}
    	})
    	
    	$('#adjustReason').on('click','li',function() {
    		if($(this).hasClass('active')) {
    			$(this).removeClass('active')
    		} else {
    			$(this).addClass('active')
    		}
    		setDisagreeReason()
    	})
    	
    	calcWorldWithTextarea()
    }
	
	function setDisagreeReason() {
		var reasons = _.map($('#adjustReason li.active'),function(el) {
			return $.trim($(el).text())
		});
		if(reasons && reasons.length) {
			$('#disagreeReason').val(reasons.join(','))
			$('#disagreeReason').focus()
		}
	}
	
	function getStrOriginalData() {
		var imporMsg = {
				prescription: {}
		};
    	imporMsg.prescription.jwCode = strOriginalData.prescription.jwCode;
    	imporMsg.prescription.patientName = strOriginalData.prescription.patientName;
    	imporMsg.prescription.doctorName = strOriginalData.prescription.doctorName;
    	imporMsg.prescription.diagnosis = strOriginalData.diagnosis;
    	var arr = _.map(strOriginalData.prescriptionInfo,function(item){
    	 	return _.pick(item, 'drugCode','drugName','jwSubCode','physicAmount','physicAmountUnit','physicAmountUnitName');
    	})
    	imporMsg.prescription.prescriptionInfo = arr;
    	
    	return imporMsg;
	}
	
	function checkAgreeInputs() {
		var fee = $('#feeSel').val();
		var dept = $('#deptSel').val();
		var pwd = $('#reviewPassword').val();
		if(!fee) {
			showErrorMsg("请选择诊查费用")
			return false;
		} else if(!dept) {
			showErrorMsg("请选择开方科室")
			return false;
		} else if(!pwd) {
			showErrorMsg("请输入审方密码")
			return false;
		} 
		return true;
	}
	
	function checkDisAgreeInputs() {
		var reason = $('#disagreeReason').val();
		if(!reason) {
			showErrorMsg("请输入不通过原因")
			return false;
		} 
		return true;
	}
	
	function getDataPromises() {
		return Promise.all([
		    prescriptionDetailApis.getDeptList({
		    	data: {
		    		jwHospital: jwHospital,
		    		jwDoctorCode: jwDoctorCode
		    	}
		    }),
		    prescriptionDetailApis.getRegisterRee({
		    	data: {
		    		jwHospital: jwHospital,
		    		jwDoctorCode: jwDoctorCode
		    	}
		    }),
		    prescriptionDetailApis.isAuthentication({}),
		    prescriptionDetailApis.getReasonByType({
		    	data: {
		    		type: '0'
		    	}
		    })
		])
	}
})