var TeamEditPanel = {
    template: '<div>\
    			<div style="height: 34px;" >\
		    		指导模板\
		    		<div @click="saveAsPersonTemplate" class="save-btn ml10" v-if="sendMode" style="width: 150px;">\
		    		保存为个人模板\
		    		</div>\
		    		<div class="delete-btn ml10" v-if="isLeader && editable && !sendMode" @click="deleteTemplate">\
		    		删除\
		    		</div>\
		    	</div>\
		    	<div class="temp-info c-f14">\
		    		<div class="temp-name pl10 ptb10">\
		    			模板名称：<input v-model="modelName" placeholder="请输入模板名称( 10字内 )" class="c-f14" maxlength="10"/>\
		    		</div>\
		    		<div class="team-name pl10 ptb10">\
		    			所属团队：<select class="c-f14" style="border:0;">\
		    						<option v-for="(team, i) in teams" :value="i">{{team.teamName}}</option>\
		    					</select>\
		    		</div>\
		    		<div class="label-name pl10 ptb10 list-arrow-r" :class="{\'list-arrow-r\': !labelsDropdown, \'list-arrow-d\': labelsDropdown}">\
		    			<div @click="labelsDropdown = !labelsDropdown">指导标签：{{selectedLabel && selectedLabel.name}}</div>\
		    			<ul v-show="labelsDropdown" class="c-list msg-list clearfix">\
			    			<li @click="selectLabel(label)" v-for="(label, i) in labelList"  :class="{\'active-icon\': label.active}" class="c-list-li ">\
								<div>\
									<span>{{label.name}}</span>\
								</div>\
							</li>\
						</ul>\
		    		</div>\
		    		<div class="c-position-r">\
		    			<textarea @input="countWord" v-model="content" class="ptb10 plr10" style="border: 0;width: 100%;box-sizing: border-box;height: 180px;"></textarea>\
		    			<div class="c-t-right mr10 mb5 c-909090">{{count}}/{{words}}</div>\
		    		</div>\
		    	</div>\
		    	<div class="img-wrap mt20 c-f14">\
	    			<div>插入图片<span class="c-909090">（{{imgs.length}}/9）</span></div>\
	    			<div class="clearfix">\
	    				<div class="c-position-r fl mr15 mt20" v-for="(url,i) in imgs">\
				            <img class="upload_img" :src="url" width="65" height="65">\
				            <div class="delete-icon" @click="removeImg(url,i)"><img src="../../../images/delete_icon.png" width="18"></div>\
			            </div>\
	    				<img-upload @uploaded="imgUploaded" v-show="imgs.length<9"></img-upload>\
            		</div>\
	    		</div>\
	    		<div class="foot-btns">\
	    			<a class="preview-btn c-t-center mr15" @click="preview" v-show="editable || sendMode">\
		    			预览\
		    		</a>\
		    		<a class="send-btn c-t-center" @click="save" v-show="isLeader && editable && !sendMode">\
		    			保存\
		    		</a>\
		    		<a class="send-btn c-t-center" @click="sendTeamTemplate" v-show="sendMode">\
		    			发送\
		    		</a>\
		    	</div>\
    </div>',

    props: [],
    data: function() {
        return {
			words: 1000,
			count: 0,
			content: "",
			modelName: "",
			imgs: [],
			modelCode: "",
			teamId: "",
			teamTemplateCode: "",
			teams: [],
			labelsDropdown: false,
			selectedLabel: null,
			labelList: [],
			editable: true,
			sendMode: false // 根据url中是否携带patient来判断是否是"发送"模式
        }
    },
    beforeRouteEnter: function(to, from, next) {
	    next(function(vm) {
	      	var query = vm.$route.query
	      	
	      	if(!storage.patient && !query.patient) {
	    		vm.sendMode = false
	    	} else {
	    		storage.patient = storage.patient || query.patient
	    		vm.sendMode = true
	    	}
	      	
	    	if(query && query.teamTemplateCode && from.path != "/preview-panel") {
	    		vm.modelCode = query.modelCode
	    		vm.teamId = query.teamId
	    		vm.teamTemplateCode = query.teamTemplateCode
	    		vm.editable = true
	    		vm.getTeamGuidanceDetail().then(function() {
	    			vm.findAllLabelList()
	    		})
	    	}
	    })
	},
    computed: {
    	isLeader: function() {
    		var vm = this
	    	var leaderCode = storage.docInfo.adminTeamCode
	    	
	    	if(!vm.teams || !vm.teams.length || !leaderCode) {
	    		return 0
	    	}
	    	
	    	var team = _.filter(vm.teams, function(o) {
	    		return o.teamId == leaderCode
	    	})
	    	if(team.length) {
	    		vm.teams = team
	    		return 1
	    	} 
	    	return 0
    	}
    },
    created: function() {

    },
    mounted: function() {
		EventBus.$emit('active-nav-tab', 1)
    },
    methods: {
        countWord: function() {
        	if(this.content.length <= this.words) {
        		this.count = this.content.length
        	} else {
        		this.content = this.content.slice(0, this.words)	
        	}
        },
        findAllLabelList: function() {
        	var vm = this
        	return guidanceAPI.findAllLabelList({
        		teamId: vm.teamId
        	}).then(function(res) {
        		var selected = null
        		var label = vm.selectedLabel? vm.selectedLabel.name: '未分组'
        		selected = _.filter(res.data, function(o) {
    				return o.name == label
    			})
    			if(selected[0]) {
    				selected[0].active = true
    				vm.selectedLabel = selected[0]
    			}
    			
    			vm.labelList = res.data
        	}).catch(function(e){
        		console.error(e)
        	})
        },
        selectLabel: function(label) {
        	var vm = this
        	vm.selectedLabel && (vm.selectedLabel.active = false)
        	label.active = true
        	vm.selectedLabel = label
        	vm.labelsDropdown = false
        },
        getTeamGuidanceDetail: function() {
        	var vm = this
        	return guidanceAPI.getTeamGuidanceDetail({teamTemplateCode: vm.teamTemplateCode,teamId:vm.teamId}).then(function(res) {
        		if(res.status == 200) {
        			var detail = res.guidanceDetail
        			vm.teams = detail.teamList
        			vm.modelName = detail.title
        			vm.content = detail.content
        			vm.imgs = detail.imagesUrl && detail.imagesUrl.split(',') || []
        			vm.selectedLabel = {
        				name: detail.labelName,
        				code: detail.labelCode
        			}
        		}
        	})
        },
        imgUploaded: function(url) {
        	var vm = this
        	vm.imgs.push(httpRequest.getImgUrl(url))
        },
        removeImg: function(url, idx) {
        	var vm = this
        	vm.imgs.splice(idx, 1)
        },
        save: function() {
        	var vm = this
        	if(!vm.modelName) {
        		toastr && toastr.error("模板名称不能为空")
        		return
        	}
        	if(!vm.content) {
        		toastr && toastr.error("模板内容不能为空")
        		return
        	}
        	guidanceAPI.modifyTeamGuidance({
	            content: vm.content,
				title: vm.modelName,
				labelCode: vm.selectedLabel.code,
				images: vm.imgs.join(','),
				teamInfo: vm.teams&&JSON.stringify(vm.teams)||"",
				saveAsGuidance:0,
				guidanceCode: vm.teamTemplateCode,
				isLeader: vm.isLeader || 0
        	}).then(function(res) {
        		if(res.status == 200) {
        			toastr && toastr.success("保存成功")
        			EventBus.$emit('refresh-team-panel')
        		}
        	}).catch(function(e) {
        		console.error(e)
        	})
        },
        deleteTemplate: function() {
        	var vm = this
        	var d = dialog({
        		width: 350,
				title: '删除模板',
				content: '删除后无法恢复,是否确认删除?',
				okValue: '确定',
				ok: function () {
					guidanceAPI.deleteTeamGuidance( { deleteAll: 0, guidanceCode: vm.teamTemplateCode, teamId:vm.teamId}).then(function(res) {
        				toastr && toastr.success("删除成功")
        				vm.editable = false
        				EventBus.$emit('refresh-team-panel')
		        	}).catch(function(e) {
		        		console.error(e)
		        	})
				},
				cancelValue: '取消',
				cancel: function () {}
			});
			d.showModal();
        	
        },
        sendTeamTemplate: function() {

        	var vm = this
            if(!vm.modelName) {
        		toastr && toastr.error("模板名称不能为空")
        		return
        	}
        	if(!vm.content) {
        		toastr && toastr.error("模板内容不能为空")
        		return
        	}
        	
        	var team = _.filter(vm.teams, function(o) {
	    		return o.teamId == vm.teamId
	    	})
        	
        	if(!team.length) {
        		// 匹配不了说明医生修改了指导所属的 团队，并且入口团队并不在选中的列表中。则默认选择选中团队中的第一个团队来发送
        		team = [vm.teams[0]]
        	}
        	
            var d = dialog({
            	width: 350,
				content: '发出后无法变更，是否确认发送给居民？',
				okValue: '继续发送',
				ok: function () {
					guidanceAPI.sendTemplate( {
		        		patient: storage.patient,
		                content: vm.content,
		                guidanceCode: vm.teamTemplateCode,
		                images: vm.imgs.join(','),
						teamId: JSON.stringify(team)
		        	}).then(function(res) {
        				toastr && toastr.success("发送成功")
        				var obj = {
        					rehabilitationDetailId: storage.planId,
				            patientCode: storage.patient,
				            // patientName: patientName,
				            doctorCode: storage.docInfo.code,
				            doctorName: storage.docInfo.name,
				            relationRecordType: 2, //健康指导
				            relationRecordCode: res.data.id
        				}
        				guidanceAPI.saveRehabilitationOperateRecord({
        					dataJson: JSON.stringify(obj)
        				}).then(function(res) {
        					if(res.status == 200) {
        						var index = top.layer && top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
								top.layer && top.layer.close(index)
        					} else {
        						toastr && toastr.success(res.msg)
        					}
        				})
		        	}).catch(function(e) {
		        		console.error(e)
		        	})
				},
				cancelValue: '取消',
				cancel: function () {}
			});
			d.showModal();
        },
        saveAsPersonTemplate: function() {
        	var vm = this
        	if(!vm.modelName) {
        		toastr && toastr.error("模板名称不能为空")
        		return
        	}
        	if(!vm.content) {
        		toastr && toastr.error("模板内容不能为空")
        		return
        	}
        	
        	var param = {
	            content: vm.content,
	            modelName: vm.modelName
        	}
        	
        	var img = vm.imgs.join(',').trim()
        	
        	if(img) {
        		param.imagesUrl = img
        	}
        	guidanceAPI.newTemplate(param).then(function(res) {
        		if(res.status == 200) {
        			toastr && toastr.success("保存成功")
        			EventBus.$emit('refresh-person-panel')
        		} else {
        			toastr && toastr.error(res.msg)
        		}
        	}).catch(function(e) {
        		console.error(e)
        	})
        },
        preview: function() {
        	var vm = this
			
			var query = {
        		modelCode: vm.modelCode,
        		patient: storage.patient||"",
        		timestemp: $.now()
        	}
        	this.$router.push({path:'/preview-panel',query:query})
        }
    },
    watch: {
    '$route': function (to, from) {
    	var vm = this
      	var query = vm.$route.query
    	if(query && query.teamTemplateCode && from.path == "/team-edit-panel"&& to.path == "/team-edit-panel") {
    		vm.modelCode = query.modelCode
    		vm.teamId = query.teamId
    		vm.editable = true
    		vm.teamTemplateCode = query.teamTemplateCode
    		vm.getTeamGuidanceDetail().then(function() {
    			vm.findAllLabelList()
    		})
    	}
    	
    	if(storage.patient) {
    		vm.sendMode = true
    	} else {
    		vm.sendMode = false
    	}
    	
    	if(to.path == "/preview-panel") {
    		EventBus.$emit('preview-template', {
    			content: vm.content,
	            modelName: vm.modelName,
	            imgs: vm.imgs
    		})
    	}
    },
    'content': function(v) {
    	this.countWord()
    }
  }
}