<template>
	<div class="school-container">
		<Loading v-show="isLoading"></Loading>
		<div class="school-container-left">
			<div class="school-container-header">
				<span>{{ $t('settings.schoolList')}}</span>
			</div>
			<vuescroll>
				<div class="school-list-wrap">
					<!-- <Loading :top="200" bgColor="rgba(103, 103, 103, 0.27)" type="1" v-show="isLoadList"></Loading> -->
					<div v-if="mySchoolList.length === 0">
						<EmptyData :top="50"></EmptyData>
					</div>
					<div class="list-wrap" v-else>
						<div class="school-item" v-for="(item,index) in mySchoolList" :key="index">
							<div>
								<img :src="item.picture" alt="" width="40px">
							</div>
							<div style="display: flex;flex-direction: column;margin-left: 10px;">
								<span class="school-item-name">
									<span>{{ item.name }}</span>
									<span class="school-item-status"
										:style='{ background:bgFilter(item.status) }'>{{ statusFilter(item.status) }}</span>
									<span class="school-item-status" style="background-color: #008352;"
										v-show="item.schoolId === teacherInfo.defaultschool">{{ $t('settings.defaultSchool')}}</span>
									<span class="school-item-status" style="background-color: #f59a2a;"
										v-show="item.schoolId === curSchool">{{ $t('settings.curSchool')}}</span>
								</span>
								<span class="school-item-code">{{ item.schoolId  }}
									<span class="school-item-nums" v-if="item.status === 'request'">
										{{ getTime(item.time) }} {{ $t('settings.joinStatus')}}
									</span>
									<span class="school-item-nums" v-if="item.status === 'invite'">
										{{ getTime(item.time) }} {{ $t('settings.requestStatus')}}
									</span>
								</span>
								<!-- <span class="school-item-nums" v-if="item.status === 'join'">
									<span>
										<Icon type="md-bookmarks" />
										<span>{{ $t('settings.courseNum')}}</span>
										<span style="margin-left: 10px;">{{ item.course }}</span>
									</span>
									<span style="margin-left: 20px;">
										<Icon type="md-star" />
										<span>{{ $t('settings.activityNum')}}</span>
										<span style="margin-left: 10px;">{{ item.activity }}</span>
									</span>
								</span> -->
								<span class="school-item-role">{{ item.role }}</span>
								<span class="school-item-btn"
									v-if="item.status === 'join' && item.schoolId !== curSchool"
									@click="onGoSchool(item)">
									<span :title="$t('settings.goSchool')">
										<Icon type="md-log-in" size="25" color="#00c4ff" />
										<!-- <span>{{ $t('settings.goSchool')}}</span> -->
									</span>
								</span>
								<span class="school-item-btn" v-if="item.status === 'request'"
									@click="undoRequest(item)">
									<span :title="$t('settings.undoJoin')">
										<Icon type="ios-close-circle-outline" size="25" color="#a9a9a9"
											style="font-weight: bold;" />
									</span>
								</span>
								<span class="school-item-btn" style="right: 70px;" v-if="item.status === 'invite'"
									@click="onConfirmJoin(item)">
									<span :title="$t('settings.agreeJoin')">
										<Icon type="md-checkmark-circle-outline" size="25" color="#27c684" />
									</span>
								</span>
								<span class="school-item-btn" v-if="item.status === 'invite'"
									@click="undoRequest(item)">
									<span :title="$t('settings.cancelAdd')">
										<Icon type="ios-close-circle-outline" size="25" color="#d02a4e"
											style="font-weight: bold;" />
									</span>
								</span>
							</div>

						</div>
					</div>
				</div>
			</vuescroll>
		</div>
		<div class="schoolmgmt-container-right">
			<div class="school-container-header">
				<span>{{ $t('settings.requestJoin')}}</span>
			</div>
			<div class="table-wrap">
				<!-- <Table stripe :columns="schoolColumns" :data="schoolList"></Table> -->
				<div class="search-wrap">
					<p class="search-wrap-tip">请输入<span>学校名称</span>或者<span>学校代码</span>进行搜索</p>
					<!-- <Input class="searchIpt" prefix="ios-search" v-model="schoolListSearch" /> -->
					<Select v-model="searchSchoolIndex" placeholder="" clearable filterable prefix="ios-search"
						@on-query-change="onQueryChange" ref="schoolSelect">
						<Option v-for="(item,index) in originSchoolList" :value="item.name" :key="index">
							<span>{{ item.name }} <span style="color:#838383;">( {{ item.id }} )</span></span>
							<span :class="['select-tool',canJoin(item.id) ? 'select-tool-join' : '']"
								@click="onSelectSchool(canJoin(item.id),item)">{{ tbStatusFilter(item.id) }}</span>
							<span
								style="color:#838383;margin-left: 20px;">{{ item.region }}-{{ item.province }}-{{ item.city }}</span>
						</Option>
					</Select>
					<p class="errorMsg">{{searchIdErrorMsg}}</p>
					<p class="searchBtn-tip">* 如未搜索到您想要的学校，可点击下方申请建立您的学校</p>
					<Button :loading="searchLoading" type="info" class="searchBtn" @click="applyJoin()">申请建立学校</Button>
				</div>
			</div>
		</div>
		<Modal v-model="goSchoolModal" class-name="go-school-modal" footer-hide>
			<p>{{ $t('settings.modalTip1')}}</p>
			<p>{{ $t('settings.modalTip2')}}</p>
			<p>{{ curSchoolItem ? curSchoolItem.name : '' }}</p>
			<p>{{ $t('settings.modalTip3')}}</p>
			<Button @click="onChangeSchool">{{ $t('evaluation.confirm')}}</Button>
		</Modal>

		<Modal v-model="applyModal" class-name="go-school-modal" footer-hide width="500">
			<span class="apply-title">申请建立学校</span>
			<BaseApplyForm></BaseApplyForm>
		</Modal>

	</div>
</template>

<script>
	import BaseApplyForm from './BaseApplyForm.vue'
	export default {
		components:{BaseApplyForm},
		data() {
			return {
				applyModal: false,
				searchSchoolIndex: null,
				selectSchoolItem: {
					picture: '',
					name: '',
					code: ''
				},
				applyForm: {
					name: '',
					region: '',
					province: '',
					city: '',
					picture: ''
				},
				uploadList:[],
				searchLoading: false,
				searchIdErrorMsg: '',
				teacherInfo: {
					defaultschool: ''
				},
				mySchoolSearch: '',
				schoolListSearch: '',
				goSchoolModal: false,
				isLoading: false,
				mySchoolList: [],
				originMySchoolList: [],
				originList: [],
				activeIndex: 0,
				isLoadList: false,
				allSchoolList: [],
				curArea: 'default',
				curProvince: 'default',
				curCity: 'default',
				curSchoolItem: null,
				schoolList: [],
				originSchoolList: [],
			}
		},
		created() {
			this.initTeacherInfo()
			this.getAllShoolList()
			this.mySchoolList = []

		},
		methods: {

			async initTeacherInfo() {
				let teacherInfo = await this.getTeacherInfo()
				this.teacherInfo = teacherInfo
				this.mySchoolList = teacherInfo.schools || []
				this.originMySchoolList = JSON.parse(JSON.stringify(this.mySchoolList))
			},

			/* 前往学校 */
			onGoSchool(school) {
				this.curSchoolItem = school
				this.goSchoolModal = true
			},

			/* 获取老师的个人清单信息 */
			getTeacherInfo() {
				return new Promise((r, j) => {
					this.isLoading = true
					this.$api.schoolSetting.getTeacherInfo({
						id_token: localStorage.getItem('id_token')
					}).then(
						(res) => {
							if (!res.error) {
								r(res)
								this.isLoading = false
							}
						},
						(err) => {
							console.log(err)
							this.$Message.error("数据获取失败！")
						}
					)
				})

			},

			/* 获取老师所在学校的信息 */
			getTeacherSchoolInfo(code) {
				return new Promise((r, j) => {
					this.$api.schoolSetting.getTeacherSchoolInfo({
						id_token: localStorage.getItem('id_token'),
						school_code: code
					}).then(
						(res) => {
							if (!res.error) {
								r(res)
							}
						},
						(err) => {
							this.$Message.error("数据获取失败！")
						}
					)
				})
			},

			/* 获取所有授权学校列表 */
			getAllShoolList() {
				this.$api.schoolSetting.getSchoolList().then(
					(res) => {
						if (!res.error) {
							this.schoolList = res.schools || []
							this.originSchoolList = JSON.parse(JSON.stringify(res.schools))
							console.log(this.originSchoolList)
						}
					},
					(err) => {
						this.$Message.error("数据获取失败！")
					}
				)
			},

			/* 申请加入学校 */
			onJoinSchool(item) {
				this.$Modal.confirm({
					title: this.$t('settings.modalTip4'),
					content: this.$t('settings.modalTip5') + item.name + ' ?',
					onOk: () => {
						this.$api.schoolSetting.joinSchool({
							grant_type: 'request',
							school_code: item.id,
							school_name: item.name
						}).then(
							(res) => {
								console.log(res)
								if (!res.error) {
									this.$Message.success(this.$t('settings.submitSucTips'))
									this.initTeacherInfo()
									this.getAllShoolList()
								}
							},
							(err) => {
								this.$Message.error(this.$t('settings.submitFailTips'))
							}
						)
					},
					onCancel: () => {
						this.$refs.schoolSelect.setQuery(' ')
					}
				})
			},

			/* 撤销加入学校申请 */
			undoRequest(item) {
				console.log(item)
				this.$Modal.confirm({
					title: this.$t('settings.modalTip4'),
					content: this.$t('settings.modalTip6') + item.name + ' ?',
					onOk: () => {
						this.$api.schoolSetting.joinSchool({
							grant_type: 'cancel',
							school_code: item.schoolId,
							school_name: item.name
						}).then(
							(res) => {
								console.log(res)
								if (!res.error) {
									this.$Message.success(this.$t('settings.submitSucTips'))
									this.initTeacherInfo()
									this.getAllShoolList()
								}
							},
							(err) => {
								this.$Message.error(this.$t('settings.submitFailTips'))
							}
						)
					},
					onCancel: () => {
						this.$refs.schoolSelect.setQuery(' ')
					}
				})
			},

			/* 同意邀请 */
			onConfirmJoin(item) {
				console.log(item)
				this.$Modal.confirm({
					title: this.$t('settings.modalTip4'),
					content: this.$t('settings.modalTip5') + item.name + ' ?',
					onOk: () => {
						this.$api.schoolSetting.joinSchool({
							grant_type: 'join',
							school_code: item.schoolId,
							school_name: item.name
						}).then(
							async (res) => {
									console.log(res)
									if (!res.error) {
										this.$Message.success(this.$t('settings.joinSucTips'))
										// 如果之前用户没有加入任何学校
										if (this.mySchoolList.length && this.mySchoolList.filter(i => i
												.status === 'join').length === 0) {
											let teacherInfo = await this.getTeacherInfo()
											let schoolCode = item.schoolId
											let schoolInfo = await this.getTeacherSchoolInfo(schoolCode)
											this.$EventBus.$emit('onChangeSchool', {
												user: teacherInfo,
												schoolCode: schoolCode,
												isFirst: true
											})
											this.$EventBus.$off('onChangeSchool')
										} else {
											this.initTeacherInfo()
										}
									}
								},
								(err) => {
									this.$Message.error(this.$t('settings.submitFailTips'))
								}
						)
					},
					onCancel: () => {}
				})
			},

			/* 前往学校 */
			async onChangeSchool() {
				console.log('触发切换学校')
				this.$EventBus.$emit('onChangeSchool', {
					user: this.teacherInfo,
					schoolCode: this.curSchoolItem.schoolId
				})
				// this.$EventBus.$off('onChangeSchool')
				this.goSchoolModal = false
			},

			applyJoin() {
				this.applyModal = true
			},

			onSelectSchool(val, item) {
				console.log(val)
				if (val) {
					this.onJoinSchool(item)
					this.searchSchoolIndex = null
					this.$refs.schoolSelect.setQuery(' ')
				}
			},

			onQueryChange(val) {
				// if(val === ''){
				// 	this.searchSchoolIndex = null
				// }
			},

		},
		computed: {
			canJoin() {
				return id => {
					return this.mySchoolList.map(j => j.schoolId).indexOf(id) === -1
				}
			},
			statusFilter() {
				return status => {
					return status === 'join' ? this.$t('settings.status1') : status === 'invite' ? this.$t(
						'settings.status2') : this.$t('settings.status3')
				}
			},
			bgFilter() {
				return status => {
					return status === 'join' ? '#1CC0F3' : status === 'invite' ? '#ea6223' : '#019eff'
				}
			},
			tbStatusFilter() {
				return id => {
					// 判断当前学校是否已加入
					let isJoin = this.mySchoolList.filter(i => i.status === 'join').map(j => j.schoolId).indexOf(id) >
						-1
					let isInvite = this.mySchoolList.filter(i => i.status === 'invite').map(j => j.schoolId).indexOf(
						id) > -1
					let isRequest = this.mySchoolList.filter(i => i.status === 'request').map(j => j.schoolId).indexOf(
						id) > -1
					return isJoin ? this.$t('settings.status1') : isInvite ? this.$t('settings.status2') : isRequest ?
						this.$t('settings.status3') : this.$t('settings.requestJoin')
				}
			},
			curSchool() {
				return this.$store.state.userInfo.schoolCode
			},
			getTime() {
				return time => {
					return this.$tools.formatTime(time, 'yyyy-MM-dd')
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	@import "./SchoolMgmt.less";
</style>

<style lang="less">
	@borderColor: #424242;
	@second-textColor: #CBCBCB; //文本副级颜色

	.schoolmgmt-container-right {
		.search-wrap {
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			color: #afafaf;
			height: 100%;
			padding-bottom: 250px;

			&-tip {
				span {
					color: #fff;
					font-weight: bold;
					margin: 0 10px;
				}
			}

			.searchBtn-tip {
				margin: 40px 0 20px 0;
			}

			.searchBtn {
				background-color: #006778;
				border: none;
			}

			.ivu-input-wrapper {
				width: auto;
				margin: 40px 0;
			}

			.ivu-input-prefix i {
				line-height: 40px !important;
				margin-left: 10px;
			}

			.ivu-input {
				background: transparent;
				border-color: #4a4a4a;
				width: 450px;
				height: 40px;
				border-radius: 50px;
				color: @second-textColor;

				&::-webkit-input-placeholder {
					/* WebKit browsers */
					color: #999;
					font-size: 12px;
				}
			}

			.ivu-select-selection {
				border-radius: 20px;
				margin: 40px auto;
				height: 40px;
				line-height: 40px;
				background: transparent;
				border-color: #4a4a4a;
				width: 650px;
				cursor: text;
			}

			.select-tool {
				display: inline-block;
				margin-left: 10px;
				float: right;
				color: #0bddff;
			}

			.select-tool-join {
				background: #07b15b;
				color: #fff !important;
				padding: 3px 10px;
				border-radius: 4px;
			}

			.ivu-select-visible .ivu-select-selection {
				box-shadow: none;
				background-color: #3c3c3c;
				border-radius: 20px 20px 0px 0px;
			}

			.ivu-select-dropdown {
				background-color: #3c3c3c;
				border-radius: 0 0 20px 20px;
				margin: 0;
				padding-bottom: 40px;

				li {
					padding: 10px 16px;
				}

				.ivu-select-item {
					color: #e6e6e6;

					&:hover {
						background-color: #565656;
					}
				}

				.ivu-select-item-focus {
					background-color: #3c3c3c;
				}
			}

			.ivu-select-prefix i {
				line-height: 40px;
				margin-left: 10px;
			}

			.ivu-select-input {
				color: #fff;
				cursor: text;
			}

			.ivu-select-arrow {
				display: none;
			}

			.ivu-select {
				background: transparent;
				border-color: #4a4a4a;
				width: 650px;
			}

		}

		.table-wrap {
			height: 100%;
		}
	}


	.apply-title {
		color: #cacaca;
		font-size: 18px;
		font-weight: bold;

		&::before {
			content: '';
			display: inline-block;
			border: 4px solid #1ee6aa;
			border-radius: 50%;
			margin-right: 10px;
			margin-bottom: 3px;
		}
	}


	.go-school-modal {
		font-family: 'NotoSerif', '微软正黑体', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Sans-serif;

		.ivu-modal-content {
			background: #3f3f3f;
			color: #b6b6b6;
		}

		p {
			text-align: center;
			font-size: 14px;
			margin: 10px 0;

			&:first-child {
				font-size: 20px;
				font-weight: bold;
				color: #1CC0F3;
				margin: 30px 0;
			}

			&:nth-child(3) {
				color: #fff;
				font-weight: bold;
				font-size: 18px;
				margin: 20px 0;
			}
		}

		.ivu-btn {
			background: #1CC0F3;
			color: #fff;
			border-radius: 5px;
			width: 60%;
			height: 40px;
			margin: 30px 20%;
			border: none;
		}
	}

	.show-school-modal {
		.s-name {
			font-size: 20px;
			font-weight: bold;
			color: #1CC0F3;
			margin: 30px 0;
		}


	}
</style>
