<template>
	<div class="base-class-select">
		<RadioGroup v-model="targetType" @on-change="onTargetTypeChange" style="margin-bottom: 10px;">
		    <Radio label="research">{{ $t('teachermgmt.page.text3') }}</Radio>
		    <Radio label="student">{{ $t('courseManage.classroom.studentList')}}</Radio>
		</RadioGroup>
		<el-cascader v-if="targetType === 'student'" v-model="defaultArr" ref="demoCascader" :key="modelKey" :props="props" :options="csOptions" @change="treeChange" :show-all-levels="false" clearable popper-class="myCascader"
			filterable></el-cascader>
		<Select v-model="groupArr" multiple v-if="targetType === 'research'" @on-change="onGroupChange">
			<Option v-for="(item, index) in groupList" :value="item.id" :key="index">{{ item.name }}</Option>
		</Select>	
	</div>
</template>

<script>
	export default {
		props:{
			type:{
				type:String,
				default:'school'
			},
			classes:{
				type:Array,
				default:() => []
			}
		},
		data() {
			return {
				groupArr:[],
				groupList:[],
				targetType:'research',
				defaultArr:[],
				evaluationInfo: {
				    scope: 'school'
				},
				modelKey:1,
				props: {
					multiple: true,
					emitPath:false,
					value: 'id',
					label: 'name',
				},
				stuList: [],
				classList:[],
				preCheckList:[],
				prePeriodId:'',
				preCheckType:'',
				privateClassType:'school'
			};
		},
		created() {
			this.findStuList()
			this.findResearchList()
		},
		methods: {
			/* 查找学校检验组信息 */
			findResearchList(){
				this.$api.schoolUser.getResearchGroup({
					code:this.$store.state.userInfo.schoolCode,
					scope:'school'
				}).then(res => {
					this.groupList = res.tchLists
				})
			},
			/* 选择教研组发生变化 */
			onGroupChange(){
				this.$emit('onChange', this.groupArr)
			},
			/* 发布对象流程发生变化 */
			onTargetTypeChange(val){
				this.defaultArr = []
				this.groupArr = []
				this.targetType = val
			},
			changeLabel(val) {
			  // 是否与上次的类型相同
			  let changeFlag = false
			  let changeItem = null
			  if (this.shareScopeEnd.length == 0) {
				this.defaultArr = val
			  } else {
				// 与原数组比对
				this.defaultArr.forEach((item) => {
				  if (item[0] !== this.shareScopeEnd[0][0]) { // 一级标签不同
					changeFlag = true
					changeItem = item
				  } else if (item[1] != this.shareScopeEnd[0][1]) { // 一级标签相同但是二级标签不同
					changeFlag = true
					changeItem = item
				  } else if ((!item[2] && this.shareScopeEnd[0][2]) || (item[2] && !this.shareScopeEnd[0][2])) {
					changeFlag = true
					changeItem = item
				  }
				})
			  }
			  if (changeFlag) {
				this.defaultArr = []
				this.defaultArr.push(changeItem)
			  }
			  console.log(this.defaultArr)
			  this.shareScopeEnd = this.defaultArr
			},

			getClassesDataByPeriodId(id) {
				let data = []
				if (this.$store.state.user.schoolProfile) {
					let curPd = this.$store.state.user.schoolProfile.school_base.period.find(i => i.id === id)
					let schoolClasses = this.$store.state.user.schoolProfile.school_classes
					data = [{
							id: 'class',
							name: this.$t('stuAccount.adminClass'),
							children: []
						},
						{
							id: 'stulist',
							name: this.$t('stuAccount.teachClass'),
							children: []
						}
					]
					if (curPd) {
						//计算学级逻辑
						let date = new Date()
						let curYear = date.getFullYear()
						let month = date.getMonth() + 1
						let start = curPd.semesters.find(item => {
							return item.start == 1
						})
						// 根据入学月份确定当前年级和学级的关系
						if (start && month < start.month) {
							curYear--
						}
						curPd.grades.forEach((item, index) => {
							let dataItem = {
								id: index, //年级使用index
								name: `${item}(${curYear - index}${this.$t('unit.gradeYear')})`,
								year: curYear - index,
								children: []
							}
							let child = schoolClasses.filter(classItem => {
								return (classItem.year == curYear - index) && classItem.periodId == curPd
									.id
							})
							dataItem.children = child
							this.classList = schoolClasses.map(i => i.id)
							data[0].children.push(dataItem)
						})
					}
					// 填充教学班数据
					let curStuList = this.stuList.filter(item => {
					    return item.periodId == curPd.id
					})
					data[1].children.push(...curStuList)
				}
				return data
			},
			visibleChange(status) {
			    if (status) {
			        this.selectBefore = this._.cloneDeep(this.defaultArr)
			    }
			},
			treeChange(data) {
				console.log(data)
				if(!data.length){
					this.$refs.demoCascader.panel.activePath = [];
					this.preCheckList = []
					this.defaultArr = []
				}
				let curCheckType = ''
				let xArr = data.filter(i => !this.preCheckList.includes(i))
				let alreadyType = this.preCheckList.every(i => this.classList.includes(i)) ? 'class' : 'stuList'
				const obj = this.$refs['demoCascader'].getCheckedNodes()
				if(obj.length && xArr.length){
					// 如果切换了学段 则要全部置空 再将最新选择的作为结果
					let curCheckNodePeriod = obj.find(i => i.data.id === xArr[0]).data.periodId
					if(curCheckNodePeriod !== this.prePeriodId){
						this.$refs.demoCascader.panel.activePath = [];
						this.prePeriodId = curCheckNodePeriod
						this.defaultArr = xArr
					}
				}
				if(xArr.length){
					curCheckType = this.classList.includes(xArr[0]) ? 'class' : 'stuList'
				}
				// 如果切换了班级类型 也需要全部置空 再将最新选择的作为结果
				if(alreadyType !== curCheckType && xArr.length){
					this.$refs.demoCascader.panel.activePath = [];
					this.defaultArr = xArr
				}
				console.log(alreadyType);
				console.log(curCheckType);
				this.evaluationInfo.scope = this.defaultArr.every(i => this.classList.includes(i)) ? 'school' : 'private'
				this.preCheckList = this.defaultArr
				this.$emit('onChange', this.defaultArr)
			},
			findStuList() {
			    let params = {
			        code: this.$store.state.userInfo.schoolCode,
			        scope: 'school'
			    }
			    this.$api.courseMgmt.findStulist(params).then(
			        res => {
			            this.stuList = res.stuList
			        },
			        err => {
			            this.$Message.error('API error')
			        }
			    )
			},
		},
		mounted() {
			this.$EventBus.$off('onCreateVote')
			this.$EventBus.$on('onCreateVote',() => {
				this.defaultArr = []
			})
		},
		computed: {
			csOptions() {
				if (this.$store.state.user.schoolProfile) {
					let periodList = this.$store.state.user.schoolProfile.school_base.period.map(i => {
						return {
							id: i.id,
							name: i.name,
							children: this.getClassesDataByPeriodId(i.id)
						}
					})
					return periodList
				} else {
					return []
				}
			},
		},
		watch:{
			classes:{
				handler(n,o){
					if(n.length){
						this.targetType = this.type
						setTimeout(() => {
							if(this.type === 'research'){
								this.groupArr = n
							}else{
								this.defaultArr = n
								this.preCheckList = n
								this.modelKey++
							}
						},200)
					}
				},
				immediate:true,
				deep:true
			}
		}
	};
</script>
<style lang="less">
	.myCascader {
		.el-cascader {
			width: 100%;

			.el-input__inner {
				background-color: #353535;
				border: none;
			}
		}
		
		.el-cascader-panel {
		  .el-scrollbar:first-child {
		    .el-checkbox {
		      display: none;
		    }
		  }
		  // .el-scrollbar:nth-child(2) {
		  //   .el-checkbox {
		  //     display: none;
		  //   }
		  // }
		}
	}
</style>
