<template>
	<div class="it-container">
		<div class="node-info">
			<span>{{ $t('syllabus.curChapter') }}：</span>
			<span class="node-name">{{ nodeInfo.title }}</span>
			<br>
			<br>
			<div style="display: inline-block;" v-if="!isSchool">
				<span>{{ $t('syllabus.sharedTeacher') }}：</span>
				<!-- <span v-for="(item,index) in nodeInfo.auth" :key="item.tmdid" class="share-item">{{ item.tmdname }}( {{ item.tmdid }})</span> -->
				<span v-if="!nodeInfo.auth || !nodeInfo.auth.length" style="color: #dacaca;">{{ $t('syllabus.noData') }}</span>
				<Tag closable color="success" v-for="(item,index) in nodeInfo.auth" :key="item.tmdid" @on-close="doDelShare(item,index)">{{ item.tmdname }}( {{ item.tmdid }})</Tag>
			</div>
		</div>
		<div class="search-wrap" v-if="isSchool">
			<Input v-model="searchVal"  :placeholder="$t('syllabus.itPlace1')"
			icon="ios-close-circle-outline" @on-click="onCloseSearch" @on-change="onSearchChange"/>
		</div>
		<div class="teacher-wrap">
			<Table :columns="teacherCol" :data="teacherList" height="400" v-if="isSchool">
				<template slot-scope="{ row }" slot="name">
					<div style="display: flex;align-items: center;">
						<PersonalPhoto :name="row.name" :picture="row.picture" />
						<span style="margin-left: 10px;">{{ row.name }}</span>
					</div>
				</template>
				<template slot-scope="{ row }" slot="action">
					<div style="display: flex;align-items: center;">
						<i-switch true-color="#13ce66" :value="hasAuth(row.id)" :before-change="handleBeforeChange"  @on-change="onSwitchChange(row,$event)"></i-switch>
					</div>
				</template>
			</Table>
			<div class="search-id-wrap" v-else>
				<div class="id-search">
					<Input v-model="searchIdVal" :placeholder="$t('syllabus.itPlace2')" search @on-search="onIdSearch"/>
					<p v-html="$t('teachermgmt.addTeacher.content')"></p>
					<p v-if="curTeacher && curTeacher.id" class="search-result-text">{{ $t('syllabus.searchResult') }}</p>
					<div v-if="curTeacher && curTeacher.id" class="search-result-wrap">
						<PersonalPhoto :name="curTeacher.name" :picture="curTeacher.picture" />
						<p class="t-name">{{ curTeacher.name }}</p>
						<p class="t-id">{{ curTeacher.id }}</p>
					</div>
					<p v-if="!curTeacher && hasSearchResult" class="search-none">{{ $t('syllabus.noSearchResult') }}</p>
					<p v-if="hasSearchResult" class="re-search" @click="onReSearch">{{ $t('syllabus.reSearch') }}</p>
					<Button type="success" :laading="isShareLoading" v-if="hasSearchResult"  @click="doShare">{{ $t('syllabus.confirmShare') }}</Button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import PersonalPhoto from '@/components/public/personalPhoto/Index.vue'
	export default {
		components: {
			PersonalPhoto
		},
		props: {
			node: {
				type: Object,
				default: () => {
					return {
						title: ''
					}
				}
			},
			authIds: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				isSchool:false,
				isShareLoading:false,
				hasSearchResult:false,
				searchVal:'',
				searchIdVal:'',
				nodeInfo: {
					title: ''
				},
				curTeacher:{
					name:'',
					picture:'',
					id:'',
					job:''
				},
				teacherCol: [{
						title: this.$t('teachermgmt.table.th2'),
						key: 'name',
						slot: 'name'
					},
					{
						title: this.$t('teachermgmt.table.th1'),
						key: 'id'
					},
					{
					  title: this.$t('teachermgmt.table.th3'),
					  key: 'job',
					  render: (h, params) => {
					    if (typeof params.row.job === 'undefined' || params.row.job == null || params.row.job === '') {
					      return h('span', this.$t('teachermgmt.job.teacher'))
					    } else {
					      return h('span', params.row.job)
					    }
					  }
					},
					{
						title: this.$t('syllabus.isCoEdit'),
						key:'action',
						slot: 'action'
					}
				],
				teacherList: [],
				originList:[]
			}
		},
		created() {
			this.isSchool = this.$route.name === 'syllabus'
		},
		methods: {
			/* 获取学校所有教师列表 */
			getAllTeacher() {
				this.$store.dispatch('user/getSchoolTeacher').then(
					res => {
						if (res.code == 0) {
							this.$Message.error('無法取得使用者資料')
						} else {
							this.teacherList = this.$store.state.user.schoolUserList.filter(i => i.status === 'join' && i.id !== this.$store.state.userInfo.TEAMModelId)
							this.originList = JSON.parse(JSON.stringify(this.teacherList))
						}
					},
					err => {
						this.$Message.error('user/setSchoolTeacher API error!')
					}
				)
			},
			/* 搜索词汇发生变化 */
			onSearchChange(){
				this.teacherList = this.originList.filter(i => i.name.indexOf(this.searchVal) > -1 || i.id.indexOf(this.searchVal) > -1)
			},
			/* 关闭搜索 */
			onCloseSearch(){
				this.searchVal = ''
				this.teacherList = JSON.parse(JSON.stringify(this.originList))
			},
			/* 根据ID邮箱手机号搜索教师信息 */
			onIdSearch(){
				let paramsVal = this.searchIdVal
				if (paramsVal.indexOf(0) == 0) paramsVal = paramsVal.substr(1)
				this.$store.dispatch('user/getUserFromCoreId', [paramsVal]).then(
				    (res) => {
				        if (res.code == 1) {
				            this.curTeacher = res.data.length ? res.data[0] : null
				        } else {
				            this.$Message.error('user/getUserFromCoreId API error!')
				        }
						this.hasSearchResult = true
				    },
				    (err) => {
				        this.$Message.error('user/getUserFromCoreId API error!')
				    }
				)
			},
			/* 重新搜索 */
			onReSearch(){
				this.searchIdVal = ''
				this.curTeacher = null
				this.hasSearchResult = false
			},
			/* 修改共编权限前回调 */
			handleBeforeChange(){
				return new Promise((resolve) => {
					this.$Modal.confirm({
						title: this.$t('syllabus.modifyTip'),
						content: this.$t('syllabus.modifyText'),
						onOk: () => {
							resolve();
						}
					});
				});
			},
			/* 修改共编权限 */
			onSwitchChange(val,isAdd){
				this.sendShareApi(val.id,val.name,false,isAdd).then(res => {
					this.$Message.success(isAdd ? this.$t('syllabus.authSuc') : this.$t('syllabus.authFail'))
					if(isAdd){
						this.nodeInfo.auth.push({
							tmdid:val.id,
							tmdname:val.name,
							aggre:0,
							type:'coedit'
						})
					}else{
						this.nodeInfo.auth.splice(this.nodeInfo.auth.map(i => i.tmdid).indexOf(val.id),1)
					}
				})
			},
			/* 分享课纲操作 */
			doShare(){
				if(this.curTeacher.id === this.$store.state.userInfo.TEAMModelId){
					this.$Message.warning(this.$t('syllabus.noShareMyself'))
					return
				}
				let val = this.curTeacher
				this.isShareLoading = true
				this.sendShareApi(val.id,val.name,true,true).then(res => {
					setTimeout(() => {
						this.$Message.success(this.$t('syllabus.shareSuc'))
						if(!this.nodeInfo.auth.map(i => i.tmdid).includes(val.id)){
							this.nodeInfo.auth.push({
								tmdid:val.id,
								tmdname:val.name,
								aggre:0,
								type:'share'
							})
						}
						this.isShareLoading = false
						this.curTeacher = null
						this.hasSearchResult = false
						this.searchIdVal = ''
					},500)
				})
			},
			/* 取消分享操作 */
			doDelShare(val,index){
				this.$Modal.confirm({
					title: this.$t('syllabus.cancelShare'),
					content:this.$t('syllabus.cancelTip1') + val.tmdname + this.$t('syllabus.cancelTip2'),
					onOk: () => {
						this.sendShareApi(val.tmdid,val.tmdname,true,false).then(res => {
							this.nodeInfo.auth.splice(index,1)
							this.$Message.success(this.$t('syllabus.shareFail'))
							this.$forceUpdate()
						})
					}
				});
			},
			/* 发送共编或者分享API请求 */
			sendShareApi(toId,toName,isShare,isAdd){
				return new Promise((r,j) => {
					let curVolume = this.$parent.$parent.curVolume
					this.$api.syllabus.ShareTree({
						"school": curVolume.school,
						"scope": curVolume.scope,
						"tmdInfo": [
							{
								"tmdid": toId,
								"tmdname": toName
							}
						],
						"type": isShare ? 'share' : 'coedit',
						"issuer": this.$store.state.userInfo.TEAMModelId,
						"issuerName": this.$store.state.userInfo.name,
						"opt": isAdd ? 'add' : 'del',
						"syllabusId": this.nodeInfo.id,
						"syllabusName": this.nodeInfo.title,
						"volumeId": curVolume.id,
						"volumeName": curVolume.name
					}).then(res => {
						if(res.code === 200){
							r(200)
						}
					}).catch(err => {
						this.$Message.error(err)
						j(err)
					})
				})
				
			},
			
		},
		mounted() {
			this.isSchool && this.getAllTeacher()
		},
		computed:{
			/* 判断当前用户是否已被授权 */
			hasAuth(){
				return id => {
					if(!this.nodeInfo.auth){
						return false
					}else{
						let matchItem = this.nodeInfo.auth.filter(i => i.tmdid === id)
						if((matchItem.length && matchItem[0].type === 'coedit') || this.authIds.includes(id)){
							return true
						}else{
							return false
						}
					}
				}
			}
		},
		watch: {
			node: {
				handler(n, o) {
					if (n) {
						console.log(this.authIds)
						this.nodeInfo = n
						this.nodeInfo.auth = this.nodeInfo.auth.filter(i => i.tmdid !== this.$store.state.userInfo.TEAMModelId)
					}
				},
				immediate: true
			}
		}
	}
</script>

<style lang="less" scoped src="./InviteTeacher.less"></style>
<style lang="less">
	.it-container{
		.teacher-wrap {
			.dark-iview-table .ivu-table td {
				border-color: #494949;
				color: #c4c4c4 !important;
			}
		}
		
		.share-item{
			display: inline-block;
			margin-left: 10px;
			padding: 2px 5px;
			background-color: #005C5F;
		}
		
		.search-wrap{
			.ivu-input-wrapper{
				width: 300px;
				line-height: 35px;
			}
			.ivu-input{
				// background-color: #474747;
				// border-color: #515151;
				font-size: 12px;
				// color: #ddd;
				margin: 20px 0;
				border-radius: 50px;
				padding-left: 10px;
				height: 35px;
			}
			
			.ivu-input-icon{
				line-height: 75px;
			}
		}
		
		.search-id-wrap{
			margin-top: 20px;
			color: #adadad;
			.point{
				color: #F1F1F1;
				font-weight: bold;
				font-size: 16px;
				margin: 0 10px;
			}
			
			.id-search{
				min-height: 400px;
				width: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;
				
				.ivu-input-wrapper{
					width: 500px;
					line-height: 35px;
				}
				.ivu-input{
					background-color: #474747;
					border-color: #515151;
					font-size: 14px;
					color: #ddd;
					margin: 20px 0;
					border-radius: 50px;
					padding-left: 20px;
					height: 45px;
				}
				
				.ivu-input-icon{
					line-height: 86px;
					margin-right: 10px;
				}
			}
			
			.search-result-text{
				margin-top: 60px;
				margin-bottom: 10px;
			}
			
			.search-result-wrap{
				background-color: #4e4e4e;
				padding: 20px;
				border-radius: 10px;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				.avatar , .fakeAvatar{
					width: 60px !important;
					height: 60px !important;
					border-radius: 50%;
				}
				.t-name{
					color: #fff;
					font-size: 16px;
					font-weight: bold;
					margin: 10px 0;
				}
			}
			
			.search-none{
				color: #ff4f80;
				font-size: 16px;
				font-weight: bold;
				margin-top: 80px;
			}
			
			.re-search{
				margin: 20px 0;
				text-decoration: underline;
				color: #FFFCFC;
				font-size: 14px;
				cursor: pointer;
			}
		}
	}
</style>
