
$(function(){
	//获取团队信息
	var request = getRequest(),
	    teamCode = request.id,
	    isLeader = isTeamLeader(),
	    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.helper('getStatusName',function(status) {
    	return getStatusName(status)
    })
    
    template.helper('getReviewResultName',function(status) {
    	return getReviewResultName(status)
    })
    
    prescriptionDetailApis.getContinuedPrescriptionAsDoctor({
    	data: {
    		code: prescriptionCode, // 续方CODE
    		type: isLeader?1:2 // 是否为团队长，1：是，2:否
    	}
    }).then(function(res) {
    	if(res.status == 200) {
    		var data = res.data;
	    	var prescription = data.prescription;
	    	var diagnosis = data.diagnosis;
	    	strOriginalData = data;
	    	jwHospital = prescription.jwHospital;
	    	jwDoctorCode = prescription.jwDoctorCode;
	    	var diagnosisNames = _.pluck(diagnosis,'name').join('、')
	    	
	    	if(isLeader) {
	    		getDataPromises().then(function(responses) {
		    		var deptRes = responses[0],
		    			feeRes = responses[1],
		    			authRes = responses[2],
		    			reasonRes = responses[3];
		    			
		    		$main.html(template('detailTmpl',$.extend({}, 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({}, data , {
	    			diagnosisNames: diagnosisNames,
	    			isLeader: isLeader
	    		})))

	    		bindEvents()
	    	}
	    	
    	} else {
    		showErrorMsg(res.msg)
    	}
    	
    })
    
    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(res.msg || '操作成功')
			    				setTimeout(function() {
			    					location.reload(true)
			    				}, 2000)
			    			} else {
			    				$('#reviewBtn').removeAttr('disabled')
			    			}
			    		})
    				} else {
    					showErrorMsg(res.msg)
    					$('#reviewBtn').removeAttr('disabled')
    				}
    			}).catch(function(e) {
    				showErrorMsg(e)
    			})
    		} else if(result == 2){ // 审核不通过
    			if(!checkDisAgreeInputs()) {
    				return ;
    			}
    			var reasonType = $('#adjustReason li.active').text();
				var reason = $('#disagreeReason').val();
    			prescriptionDetailApis.reviewPrescription({
	    			data: {
	    				code: prescriptionCode, // 续方CODE
	    				state: 2, // 1同意,2不同意
	    				reason: reasonType, // 不同意原因
    					reasonCode: reason, // 不同意原因CODE
	    			}
	    		}).then(function(res) {
	    			if(res.status == 200 && res.data){
	    				showSuccessMsg(res.msg || '操作成功')
	    				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'
    	})
    	
    	$('#backBtn').on('click',function() {
    		if(from == 'tab') {
    			top.toPrePrescriptionTab && top.toPrePrescriptionTab()
    		} else {
    			history.go(-1);
    		}
    	})
    	
    	$('#adjustReason').on('click','li',function() {
    		$(this).siblings().removeClass('active');
    		$(this).addClass('active')
    	})
    	
    	calcWorldWithTextarea()
    }
	
	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 reasonType = $('#adjustReason li.active').text();
		var reason = $('#disagreeReason').val();
		if(!reasonType) {
			showErrorMsg("请选择不通过原因")
			return false;
		} else 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'
		    	}
		    })
		])
	}
})