
var httpData=GetRequest(),
	doctorInfo = JSON.parse(window.localStorage.getItem('wlyyAgent'));

var refuseReason = null;

function showSuccessMessage(msg) {
	layer.msg(msg, {
		icon: 1
	})
}

function showErrorMessage(msg) {
	layer.msg(msg, {
		icon: 5
	})
}

function showWarningMessage(msg) {
	layer.msg(msg, {
		icon: 2
	})
}

function showInfoMessage(msg) {
	layer.msg(msg, {
		icon: 6
	})
}

function getReason(ele) {
	if(ele.hasClass("active")) {
		ele.removeClass("active")
		refuseReason = null
		return false;
	}
	ele.addClass("active").siblings().removeClass("active");
	refuseReason = ele.html();
}

top.changeTypeIndex=null;//修改居民标签的窗体

top.handleVue=new Vue({
    el: "#app",
    data: {
    	renewFlag: httpData.renewFlag, // 2 改签
    	applyDate: decodeURI(httpData.applyDate) || "",
    	justDoc: null,
    	justHDoc: null,
    	doctorType: doctorInfo.doctorType,
    	isShowList1: false,
    	isShowList2: false,
    	isShowList3: false,
    	isShowList4: false,
    	patientInfo: {jtSign: {}},
    	warnMsg: "",
    	signdictList: null,
    	teamList: null,
    	hisTeamName: null, // 历史团队
    	memberList: null, // 团队成员列表
    	doctorList: null, // 全科医生列表
    	dictList: null,
    	fileList: null,
    	serverName: null,
    	labelName: null,
    	patLabel: [],
    	signInfo: {
            signType: 1,
            signCode: httpData.signCode,
            majorDoctor: null,
            majorDoctorName: null,
            healthLabel: null,
            customLabel: null,
            disease: null,
            patientIDcard: null, // 必填
            adminTeamCode: null,
            teamCode: null,
            mesId: null, // 消息id（必填）
            msgid: null, // 消息id（必填）
            patient: httpData.patientCode,
            doctor: null,
            doctorName: null,
            healthDoctor: null,
            healthDoctorName: null,
            type: 1,
            state: 1,
            expenses: null,
            group: null,
            //添加服务类型数据
            sevId: null,
            // 拒绝参数
//		                adminTeamCode:0,
//		                type: 2,
       		refuseReason: null
        },
    },
    mounted: function() {
    	this.getSigndict();
    	this.getDictByDictName();
    	if(!httpData.msgid || httpData.msgid == "undefined" || httpData.msgid == "null") {
    		this.findMsgId()
    	} else {
    		this.signInfo.mesId = httpData.msgid
    		this.signInfo.msgid = httpData.msgid
    	}
    	this.teamLimit();
    	this.findPatientSignServerBySignCode();
    },
    methods: {
    	allLabels: function(selData) {
    		var vm =this,
    			param = {
    				teamCode: this.signInfo.adminTeamCode
    			},
    			loadding = layer.load(0, {shade: false});
			signAPI.allLabels(param).then(function(res) {
				layer.close(loadding)
				if(res.status == 200) {
					$.each(res.data, function(i, v) {
						if(v.labelType == 2) {
							$.each(selData.heath, function(j, u) {
								if(u == v.labelCode) {
									if(vm.labelName == "") {
			    						vm.labelName += v.labelName
			    					} else {
			    						vm.labelName += ',' + v.labelName
			    					}
			    				}
							});
						}
						if(v.labelType == 3) {
							$.each(selData.disease, function(j, u) {
								if(u == v.labelCode) {
									if(vm.labelName == "") {
			    						vm.labelName += v.labelName
			    					} else {
			    						vm.labelName += ',' + v.labelName
			    					}
			    				}
							});
						}
						if(v.labelType == 4) {
							$.each(selData.team, function(j, u) {
								if(u == v.labelCode) {
									if(vm.labelName == "") {
			    						vm.labelName += v.labelName
			    					} else {
			    						vm.labelName += ',' + v.labelName
			    					}
			    				}
							});
						}
					});
				} else {
					showErrorMessage(res.msg);
				}
			})
    	},
    	getTeamNameByTeamCode: function() {
    		var vm =this,
    			params = {
    				teamCode: vm.patientInfo.jtSign.adminTeamId
    			},
    			loadding = layer.load(0, {shade: false});
			signAPI.getTeamNameByTeamCode(params).then(function(res) {
				layer.close(loadding)
				if(res.status == 200) {
					vm.hisTeamName = res.data
				} else {
					showErrorMessage(res.msg);
				}
			})
    	},
    	patientLabel: function() {
    		var vm =this,
    			params = {
    				patient: httpData.patientCode,
    				labelType: ""
    			},
    			loadding = layer.load(0, {shade: false});
			signAPI.patientLabel(params).then(function(res) {
				layer.close(loadding)
				if(res.status == 200) {
					vm.patLabel = res.data
				} else {
					showErrorMessage(res.msg);
				}
			})
    	},
    	getSigndict: function() {
    		var vm =this,
    			loadding = layer.load(0, {shade: false});
			signAPI.getSigndict().then(function(res) {
				layer.close(loadding)
				if(res.status == 200) {
					vm.signdictList = res.data
				} else {
					showErrorMessage(res.msg);
				}
			})
    	},
    	findMsgId: function() {
    		var vm =this,
    			params = {
    				sender: httpData.patientCode,
    				signStatus: httpData.status == 0 ? 1 : (vm.renewFlag == 1 ? 8 : 9)
    			},
    			loadding = layer.load(0, {shade: false});
			signAPI.findMsgId(params).then(function(res) {
				layer.close(loadding)
				if(res.status == 200) {
					vm.signInfo.mesId = res.data.id
					vm.signInfo.msgid = res.data.id
				} else {
					showErrorMessage(res.msg);
				}
			})
    	},
    	signing: function() {
    		var vm = this,
    			loadding = layer.load(0, {shade: false}),
    			params = {
    				patient: httpData.patientCode
    			}
			signAPI.signing(params).then(function(res) {
				layer.close(loadding)
				if(res.status == 200) {
					vm.patientInfo = res.data
					vm.signInfo.patientIDcard = res.data.idCard
					if(vm.doctorType == 2) {
						vm.signInfo.doctorName = res.data.jtSign.doctorName
						vm.signInfo.doctor = res.data.jtSign.doctor
					}
					if(vm.doctorType == 3) {
						vm.signInfo.healthDoctorName = res.data.jtSign.doctorHealthName
						vm.signInfo.healthDoctor = res.data.jtSign.doctorHealth
					}
				} else {
					showErrorMessage(res.msg);
				}
			})
    	},
    	selectServer:function(){
    		var vm=this
    		if(!this.signInfo.adminTeamCode) {
    			showWarningMessage("请先选择签约团队");
    			return false;
    		}
    		if(top.changeTypeIndex && top.$('#layui-layer-shade'+top.changeTypeIndex).length){
    			top.xgLabel.initPage();
    			(top.$('#layui-layer-shade'+top.changeTypeIndex).show(),top.$('#layui-layer'+top.changeTypeIndex).show());
    		}else{
    			top.changeTypeIndex=top.layer.open({
	        		type: 2,
	        		area: ['500px', '405px'],
	        		title: "修改居民标签",
	        		shade: 0.5,
	        		shadeClose: false,
	        		closeBtn: 0,
	        		shift: 2,
	        		content: '../html/modify-the-label.html?patient=' + httpData.patientCode+'&teamCode='+vm.signInfo.adminTeamCode+"&signCode="+httpData.signCode
	        	});
    		}
    	},
    	handleStr: function(str) {
            if (!str || str === '') {
                return ''
            }
            return str.substr(0, 19)
       },
    	acceptanceRes:function(res){
    		var vm = this
    		this.serverName = "";
    		this.labelName = "";
    		if(res.server.length != 0) this.signInfo.sevId = res.server.join(",");
    		if(res.disease.length != 0) this.signInfo.disease = res.disease.join(",");
    		if(res.heath.length != 0) this.signInfo.healthLabel = res.heath.join(",");
    		if(res.team.length != 0) this.signInfo.customLabel = res.team.join(",");
    		$.each(res.server, function(i, v) {
    			$.each(vm.signdictList, function(j, u) {
    				if(v == u.code) {
    					if(vm.serverName == "") {
    						vm.serverName += u.name
    					} else {
    						vm.serverName += ',' + u.name
    					}
    				}
            	});
            });
            this.allLabels(res)
    	},
    	signOuttime: function() {
    		var vm = this,
    			loadding = layer.load(0, {shade: false}),
    			params = {
    				patient: httpData.patientCode
    			}
			signAPI.signOuttime(params).then(function(res) {
				layer.close(loadding)
				if(res.status == 200) {
					vm.patientInfo = res.data
					vm.signInfo.adminTeamCode = vm.patientInfo.jtSign.adminTeamId
					vm.signInfo.teamCode = vm.patientInfo.jtSign.adminTeamId
					vm.signInfo.healthDoctorName = vm.patientInfo.jtSign.doctorHealthName || ""
					vm.signInfo.healthDoctor = vm.patientInfo.jtSign.doctorHealth || ""
					vm.signInfo.doctor = vm.patientInfo.jtSign.doctor || ""
					vm.signInfo.doctorName = vm.patientInfo.jtSign.doctorName || ""
					if(vm.doctorType == 2) {
						vm.signInfo.doctorName = doctorInfo.name
						vm.signInfo.doctor = doctorInfo.uid
					}
					if(vm.doctorType == 3) {
						vm.signInfo.healthDoctorName = doctorInfo.name
						vm.signInfo.healthDoctor = doctorInfo.uid
					}
					vm.signInfo.expenses = vm.patientInfo.jtSign.expensesType
					vm.judgeTeamToDoc(vm.signInfo.adminTeamCode)
					// 查找之前签约的居民标签
			    	vm.patientLabel()
			    	if(vm.renewFlag == 2) { // 获取之前签约团队名字
			    		vm.getTeamNameByTeamCode()
			    	}
				} else {
					showErrorMessage(res.msg);
				}
			})
    	},
    	judgeTeamToDoc: function(teamCode) {
    		var judge = false
    		for(var i = 0, len = this.teamList.length; i < len; i++) {
    			if(this.teamList[i].id == teamCode) {
    				judge = true
    				this.teamMember()
    			}
    		}
    		if(!judge) {
    			this.signInfo.adminTeamCode = null
    			this.signInfo.teamCode = null
    			this.warnMsg = "您已不在原签约团队,请选择新的签约团队"
    			if(this.doctorType == 2) {
    				this.justHDoc = this.signInfo.healthDoctorName
					this.signInfo.healthDoctorName = null
					this.signInfo.healthDoctor = null
				} else {
					this.justDoc = this.signInfo.doctorName
					this.signInfo.doctor = null
					this.signInfo.doctorName = null
				}
    		}
    	},
    	getDictByDictName: function() {
    		var vm =this,
    			loadding = layer.load(0, {shade: false}),
    			params = {
    				name: "SIGN_EXPENSES"
    			}
			signAPI.getDictByDictName(params).then(function(res) {
				layer.close(loadding)
				if(res.status == 200) {
					vm.dictList = res.list
				} else {
					showErrorMessage(res.msg);
				}
			})
    	},
    	teamLimit: function() {
    		var vm = this,
    			loadding = layer.load(0, {shade: false}),
    			params = {
    				doctorId: doctorInfo.uid
    			}
			signAPI.teamLimit(params).then(function(res) {
				layer.close(loadding)
				if(res.status == 200) {
					vm.teamList = res.data
					if (httpData.status == 0) {
			    		vm.signing()
			    	} else {
			    		vm.signOuttime();
			    	}
				} else {
					showErrorMessage(res.msg);
				}
			})
    	},
    	findPatientSignServerBySignCode: function() {
    		var vm =this,
    			loadding = layer.load(0, {shade: false}),
    			params = {
					signCode: httpData.signCode
    			};
			signAPI.findPatientSignServerBySignCode(params).then(function(res) {
				layer.close(loadding)
				if(res.status == 200) {
					vm.fileList = [];
					var len = res.data.length;
					if(res.data.length > 0) {
						vm.serverName = "";
						vm.signInfo.sevId = "";
						for(var i = 0; i < len; i++) {
							if(i == 0) {
								vm.serverName += res.data[i].serverTypeName
								vm.signInfo.sevId += res.data[i].servetType
							} else {
								vm.serverName += + ', ' + res.data[i].serverTypeName
								vm.signInfo.sevId += +',' +  res.data[i].servetType
							}
						}
					}
					$.each(res.data, function(i, v) {
		                if(v.serverType == 8 || v.serverType == 9 || v.serverType == 11) {
		                    vm.fileList.push(v);
		                }
		            });
				} else {
					showErrorMessage(res.msg);
				}
			})
		},
    	teamMember: function() {
    		var vm = this,
    			loadding = layer.load(0, {shade: false}),
    			params = {
    				teamId: vm.signInfo.adminTeamCode
    			}
			signAPI.teamMember(params).then(function(res) {
				layer.close(loadding)
				vm.memberList = [];
				vm.doctorList = [];
				if(res.status == 200) {
					var judge = false
					$.each(res.data, function(i, v) {
						if(v.available) {
							if(v.code == vm.signInfo.doctor && vm.doctorType == 3) {
								judge = true
							}
							if(v.code == vm.signInfo.healthDoctor && vm.doctorType == 2) {
								judge = true
			            	}
						}
		                if(v.available && (v.level == 3 || v.level == 2)) {vm.memberList.push(v);}
		                if(v.available && v.level == 2) {vm.doctorList.push(v);}
		            });
		            if(!judge && httpData.status == 1) {
		            	if(vm.doctorType == 3) {
		            		if(!vm.justDoc && !vm.signInfo.doctorName) {
		            			vm.signInfo.doctorName = vm.signInfo.healthDoctorName
		            			vm.signInfo.doctor = vm.signInfo.healthDoctor
		            			return false
		            		}
		            		if(!vm.justDoc) {
		            			vm.justDoc = vm.signInfo.doctorName
		            		}
		            		vm.warnMsg = "去年签约的全科医生" + vm.justDoc + "已不在您的团队，请重新选择一位全科医生"
							vm.justDoc = null
							vm.signInfo.doctor = null
		            		vm.signInfo.doctorName = null
		            	}
						if(vm.doctorType == 2) {
							if(!vm.justHDoc && !vm.signInfo.healthDoctorName) {
		            			vm.signInfo.healthDoctorName = vm.signInfo.doctorName
		            			vm.signInfo.healthDoctor = vm.signInfo.doctor
		            			return false
		            		}
							if(!vm.justHDoc) {
		            			vm.justHDoc = vm.signInfo.healthDoctorName
		            		}
		            		vm.warnMsg = "去年签约的健管师" + vm.justHDoc + "已不在您的团队，请重新选择一位健管师"
		            		vm.justHDoc = null
		            		vm.signInfo.healthDoctor = null
		            		vm.signInfo.healthDoctorName = null
						}
						top.changeTypeIndex=null
		            }
				} else {
					showErrorMessage(res.msg);
				}
			})
   		},
    	selectStatus: function(num) {
    		if(num == 1) {
    			this.isShowList2 = false;
    			this.isShowList3 = false;
    			this.isShowList4 = false;
    			this.isShowList1 = !this.isShowList1;
    		} else if (num == 2) {
    			if(!this.signInfo.adminTeamCode) {
    				showWarningMessage("请先选择签约团队")
    				return false;
    			}
    			this.isShowList1 = false;
    			this.isShowList3 = false;
    			this.isShowList4 = false;
    			this.isShowList2 = !this.isShowList2;
    		} else if (num == 3) {
    			this.isShowList1 = false;
    			this.isShowList2 = false;
    			this.isShowList4 = false;
    			this.isShowList3 = !this.isShowList3;
    		} else {
    			if(!this.signInfo.adminTeamCode) {
    				showWarningMessage("请先选择签约团队")
    				return false;
    			}
    			this.isShowList1 = false;
    			this.isShowList2 = false;
    			this.isShowList3 = false;
    			this.isShowList4 = !this.isShowList4;
    		}
            
        },
        selectLi: function(num, data) {
        	if(num == 1) { // 选择签约团队
        		this.isShowList1 = false;
	            this.signInfo.adminTeamCode = data.id;
	            this.signInfo.teamCode = data.id;
	            if(this.doctorType == 2) {
	            	this.signInfo.healthDoctor = null
	            	this.signInfo.healthDoctorName = null
	            }
	            if(this.doctorType == 3) {
	            	this.signInfo.doctor = null
	            	this.signInfo.doctorName = null
	            }
							// 发现切换团队时无法更新健管师列表,将这个判断取消后就可以更新.
	            // if(!this.memberList || !this.doctorList) {
	            this.teamMember()
	            // }
        	}
        	if(num == 2) { // 选择健管师
        		this.isShowList2 = false;
	            this.signInfo.healthDoctorName = data.name
	            this.signInfo.healthDoctor = data.code
        	}
			if(num == 3) {
				this.isShowList3 = false;
				this.signInfo.expenses = data.code;
			}
			if(num == 4) { // 选择全科医生
				this.isShowList4 = false;
	            this.signInfo.doctorName = data.name
	            this.signInfo.doctor = data.code
			}
        },
        showTeamName: function(teamCode) {
        	var teamName;
        	if(!this.teamList) {
        		return "请选择签约团队";
        	}
        	for(var i = 0, len = this.teamList.length; i < len; i++) {
        		if(teamCode == this.teamList[i].id) {
        			teamName = this.teamList[i].name;
        		}
        	}
        	return teamName
        },
        showExpensesName: function(code) {
        	var expensesName;
        	if(!this.dictList) {
        		return "请选择补贴类型";
        	}
        	for(var i = 0, len = this.dictList.length; i < len; i++) {
        		if(code == this.dictList[i].code) {
        			expensesName = this.dictList[i].value;
        		}
        	}
        	return expensesName
        },
        setPatImg: function(str) {
        	var imgStr = httpRequest.getImgUrl(str);
        	if (imgStr == "") {
        		return '../../../images/p-female.png';
        	} else {
        		return imgStr;
        	}
        },
        lookPhoto: function(data) {
        	parent.photoLayerIndex = parent.layer.open({
        		type: 2,
        		area: ['70%', '600px'],
        		title: false,
        		shade: 0.5,
        		shadeClose: true,
        		shift: 2,
        		content: '../html/photo_show.html?serverType=' + data.serverType + '&patientCode=' + httpData.patientCode
        	})
        },
        refuse: function() {
        	var vm = this;
        	layer.open({
				type: 1,
				area: ['400px', '300px'],
				shade: 0.5,
				title: '拒绝签约原因',
				shift: 2,
				shadeClose: false, //点击遮罩关闭层
				content: '<div class="p20 pb0"><div class="reason_list clearfix"><span class="fl mr10 mb20" onclick="getReason($(this))">居民信息填写不详</span><span class="fl mr10 mb20" onclick="getReason($(this))">签约人数已满</span><span class="fl mb20" onclick="getReason($(this))">家庭医生变更</span></div><textarea id="reason" maxLength="200" placeholder="可选择填写其他拒签原因(限200字以内)"></textarea></div>',
				btn: ['提 交', '取 消'],
				yes:function(index, layero) {
					if(!refuseReason) {
						if(!$("#reason").val()) {
							showWarningMessage("请选择或输入拒绝理由！");
							layer.close(index);
							return false
						}
						vm.signInfo.refuseReason = $("#reason").val()
					} else {
						if($("#reason").val()) {
							vm.signInfo.refuseReason = refuseReason + "。" + $("#reason").val()
						} else {
							vm.signInfo.refuseReason = refuseReason
						}
					}
					vm.signInfo.adminTeamCode = 0;
					vm.signInfo.teamCode = 0;
					vm.signInfo.type = 2;
					vm.signInfo.state = 0;
					vm.sign();
					layer.close(index);
				},
				success: function(layero){
					layero.find('.layui-layer-btn').css('text-align', 'center')
				}
			});
        },
        sign: function() {// type:1签约 2拒签
        	if(this.signInfo.type == 1 && (!this.signInfo.expenses || (this.doctorType == 2 && !this.signInfo.healthDoctor) || (this.doctorType == 3 && !this.signInfo.doctor) || !this.signInfo.sevId || (!this.signInfo.disease && !this.signInfo.healthLabel && !this.signInfo.customLabel))) {
        		showWarningMessage("请将填写完整签约信息！");
        		return false;
        	}
        	var vm = this,
    			loadding = layer.load(0, {shade: false});
    		if (httpData.status == 0) {
    			var param = vm.signInfo
    			if(vm.doctorType == 2) {
    				param.doctor = null
    				param.doctorName = null
    			}
    			if(vm.doctorType == 3) {
    				param.doctorHealth = null
    				param.doctorHealthName = null
    			}
				signAPI.sign(vm.signInfo).then(function(res) {
					layer.close(loadding)
					if(res.status == 200) {
						showSuccessMessage(res.msg || "操作成功")
						setTimeout(function() {
							parent.gobalVue.signCount();
							layer.closeAll();
							parent.layer.closeAll();
						}, 1000)
					} else {
						showErrorMessage(res.msg);
					}
				})
			} else {
				signAPI.signRenew(vm.signInfo).then(function(res) {
					layer.close(loadding)
					if(res.status == 200) {
						showSuccessMessage(res.msg || "操作成功")
						setTimeout(function() {
							parent.gobalVue.signCount();
							layer.closeAll();
							parent.layer.closeAll();
						}, 1000)
					} else {
						showErrorMessage(res.msg);
					}
				})
			}
        }
    }
})
