<template>
	<div class="syllabus-container light-iview-select light-iview-input">
		<Loading v-if="isLoading" hideMask></Loading>
		<div class="syllabus-header">
			<div class="period-select" v-if="isSchool">
				<Select ref="periodSelect" v-model="currentPeriodIndex" @on-change="onPeriodChange">
					<Option v-for="(item, index) in periodList" :value="index" :key="index">{{ item.name }}</Option>
				</Select>
			</div>
			<div class="subject-select" v-if="isSchool">
				<span v-for="(subject,subjectIndex) in subjectList" :key="subjectIndex" :class="[
				  'subject-select-item',
				  subjectIndex == activeSubjectIndex ? 'item-active' : '',
				]" @click="onSubjectChange(subject,subjectIndex)">{{ subject.name }}</span>
			</div>
			<div v-if="!isSchool">
				<span :class="['syllabus-tab-item',activeTab === 'fromCreate' ? 'syllabus-tab-item-active' : '']"
					@click="onChangeSyllabusTab('fromCreate')">{{ $t('syllabus.fromCreate') }}</span>
				<span :class="['syllabus-tab-item',activeTab === 'fromShare' ? 'syllabus-tab-item-active' : '']"
					@click="onChangeSyllabusTab('fromShare')">{{ $t('syllabus.fromShare') }}</span>
			</div>
			<Button @click="onSaveSyllabus" class="btn-save-modify" icon="md-folder"
				v-if="(hasSyllabusAuth || hasEditAuth(curNode)) && hasModify">{{ $t('syllabus.btnSave') }}</Button>
		</div>
		<div class="syllabus-content">
			<div class="syllabus-left">
				<div class="syllabus-content-header">
					<div v-if="!isSearchVolume">
						<span>
						{{ $t('syllabus.volumeList') }}
						<Tooltip :content="$t('tip.volumeList')" class="common-toolTip" placement="bottom-start" theme="light" max-width="200">
						    <Icon type="ios-information-circle-outline"/>
						</Tooltip>
						</span>
						<span class="syllabus-content-header-tools">
							<Icon type="md-search" :title="$t('syllabus.search')" @click="doSearchVolume"
								v-if="volumeList.length" />
							<Icon type="md-create" :title="$t('syllabus.edit')" @click="doEditVolume"
								v-if="hasSyllabusAuth && !inShareView && volumeList.length" />
							<Icon type="md-trash" :title="$t('syllabus.delete')" @click="doDeleteVolume"
								v-if="hasSyllabusAuth && !inShareView && volumeList.length" />
							<Icon type="md-add" :title="$t('syllabus.add')" @click="doAddVolume"
								v-if="hasSyllabusAuth && !inShareView" />
						</span>
					</div>
					<div style="width: 90%;" v-else>
						<Input v-model="searchVolumeVal" :placeholder="$t('syllabus.place1')"
							icon="ios-close-circle-outline" @on-click="onCloseSearch" @on-change="onSearchChange" />
					</div>
				</div>
				<vuescroll>
					<EmptyData :top="100" v-if="!volumeList.length"></EmptyData>
					<div class="volume-list" v-else>
						<div v-for="(volume,volumeIndex) in volumeList" :key="volumeIndex"
							:class="['volume-item',activeVolumeIndex === volumeIndex ? 'volume-active' : '']"
							@click="onVolumeClick(volume,volumeIndex)">
							<p class="volume-item-name">{{ volume.name }} <span class="status-idDel"
									v-if="volume.isDel">{{ $t('syllabus.isDel') }}</span><span class="status-idDel status-coedit"
									v-if="hasVolumeAuth(volume.auth) && isSchool">{{ $t('syllabus.canEdit') }}</span> </p>
							<p class="volume-item-info" v-if="isSchool">
								<span>{{ getGradeName(volume.gradeId) }}</span>
								<span>|</span>
								<span>{{ getSemesterName(volume.semesterId) }}</span>
								<span style="margin: 0 8px;">|</span>
								<Tooltip placement="bottom" style="white-space: normal;" transfer>
									<span>{{ $t('syllabus.authorsTitle') }} {{ volume.auth.length }} </span>
									<!-- <Icon type="md-information-circle" color="#9e9e9e" /> -->
									<div slot="content">
										<p v-if="!volume.auth.length">{{ $t('syllabus.noAuth') }}</p>
										<p v-else v-for="(item,index) in volume.auth" :key="item.tmdid">
											{{ item.tmdname }}</p>
									</div>
								</Tooltip>
							</p>
							<p class="volume-item-info" v-if="inShareView">
								<span style="display: inline-flex;align-items: center;"
									@click.stop="onDeleteShareVolume(volume)">
									{{ $t('syllabus.from') }} {{ volume.creatorName }} {{ $t('syllabus.share') }}
								</span>
							</p>
							<p class="volume-item-info" v-if="inShareView" style="margin-top: 10px;">
								<span style="display: flex;align-items: center;"
									@click.stop="onDeleteShareVolume(volume)">
									<Icon type="ios-remove-circle-outline"
										style="font-weight: bold;margin-right: 5px;" />
									{{ $t('syllabus.deleteDelV') }}
								</span>
							</p>
						</div>
					</div>
				</vuescroll>
			</div>
			<div class="syllabus-mid">
				<div class="syllabus-content-header">
					<span>{{ $t('syllabus.syllabusMenu') }}</span>
					<span class="syllabus-content-header-tools"
						v-if="volumeList.length && curVolume.id && !inShareView">
						<Icon type="md-add" :title="$t('syllabus.tree.addChapterTitle')" @click="isAddTreeModal = true" v-if="hasSyllabusAuth || hasVolumeAuth(curVolume.auth)" />
					</span>
				</div>
				<div class="syllabus-tree-box">
					<EmptyData :top="-240" v-if="!treeOrigin.length"></EmptyData>
					<Tree ref="treeRef" :treeData="treeOrigin" :volume="curVolume"
						:editable="hasSyllabusAuth || hasEditAuth(curNode)" @onNodeClick="onNodeClick"
						@doShare="doShare" @addModifyId="addModifyId" v-else></Tree>
				</div>
			</div>
			<div class="syllabus-right">
				<div class="syllabus-content-header">
					<span>{{ $t('syllabus.relate') }}</span>
					<span class="syllabus-content-header-tools" v-if="curNode.id && (hasSyllabusAuth || hasEditAuth(curNode)) && !inShareView">
						<!-- <Icon type="md-add" @click="onAddResource" v-if="curNode.id"/> -->
						<Tooltip :content="$t('tip.addVolumeResource')" class="common-toolTip" placement="bottom" theme="light" max-width="200">
						    <Icon type="ios-information-circle-outline"/>
						</Tooltip>
						<Dropdown @on-click="onAddResource"
							>
							<a href="javascript:void(0)" style="color: #757575;">
								{{ $t('syllabus.addResource') }}
								<Icon type="ios-arrow-down"></Icon>
							</a>
							<DropdownMenu slot="list">
								<DropdownItem name="content">+{{ $t('syllabus.type1') }}</DropdownItem>
								<DropdownItem name="question">+{{ $t('syllabus.type2') }}</DropdownItem>
								<DropdownItem name="paper">+{{ $t('syllabus.type3') }}</DropdownItem>
								<DropdownItem name="file">+{{ $t('syllabus.type4') }}</DropdownItem>
								<DropdownItem name="link">+{{ $t('syllabus.type5') }}</DropdownItem>
							</DropdownMenu>
						</Dropdown>
					</span>
				</div>
				<div class="syllabus-tree-box">
					<EmptyData :top="-203" v-if="curNode.rnodes && !curNode.rnodes.length"></EmptyData>
					<div class="node-resource-box" v-else>
						<div class="node-resource-item" v-for="(item,index) in curNode.rnodes" @click="onPreview(item)" :title="$t('teachContent.tips4')">
							<img src="../../assets/source/image.png" v-if="item.type === 'image'" />
							<img src="../../assets/source/word.png"
								v-else-if="item.type === 'doc' && docType.includes(getSuffix(item.title))" />
							<img src="../../assets/source/excel.png"
								v-else-if="item.type === 'doc' && excelType.includes(getSuffix(item.title))" />
							<img src="../../assets/source/ppt.png"
								v-else-if="item.type === 'doc' && pptType.includes(getSuffix(item.title))" />
							<img src="../../assets/source/pdf.png"
								v-else-if="item.type === 'doc' && getSuffix(item.title) === 'pdf'" />
							<img src="../../assets/source/video.png" v-else-if="item.type === 'video'" />
							<img src="../../assets/source/audio.png" v-else-if="item.type === 'audio'" />
							<img src="../../assets/source/item.png" v-else-if="item.type === 'item'" />
							<img src="../../assets/source/folder.png" v-else-if="item.type === 'paper'" />
							<img src="../../assets/source/link.png" v-else-if="item.type === 'link'" />
							<img src="../../assets/source/zip.png" v-else-if="item.type === 'res'" />
							<img src="../../assets/source/image.png" v-else-if="item.type === 'thum'" />
							<img src="../../assets/source/unknow.png" v-else="item.type === 'other'" />
							<span v-html="item.title" style="max-width: 70%;cursor: pointer;"
								></span>
							<div class="node-resource-tools">
								<!-- <div class="node-resource-tool" >
									<Icon type="md-eye" />
									<span>{{ $t('syllabus.preview') }}</span>
								</div> -->
								<div class="node-resource-tool" @click.stop="onDeleteResource(item,index)" :title="$t('teachContent.tips7')"
									v-if="(hasSyllabusAuth || hasEditAuth(curNode)) && !inShareView">
									<Icon type="md-trash" />
									<span>{{ $t('syllabus.remove') }}</span>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!--上传文件-->
		<Modal v-model="isUploadModal" width="800" footer-hide class="tree-modal add-volume-modal tree-upload-modal">
			<div class="modal-header" slot="header">
				<span>{{ $t('syllabus.upload') }}</span>
			</div>
			<BaseUpload :auth="curSas" :scope="curScope" :prefix="curPrefix" @uploadFinish="uploadFinish"></BaseUpload>
		</Modal>

		<!-- 新增册别弹窗 -->
		<Modal v-model="isAddVolumeModal" width="500" footer-hide class="add-volume-modal">
			<div class="modal-header" slot="header">
				{{ isEditVolume ? $t('syllabus.editVolume') : $t('syllabus.addVolume') }}
			</div>
			<div class="modal-content">
				<div class="form-container">
					<Form :model="addVolumeForm" label-position="top" @submit.native.prevent>
						<FormItem :label="$t('syllabus.grade')" v-if="isSchool">
							<Select v-model="addVolumeForm.grade">
								<Option v-for="(item,index) in gradeList" :value="index" :key="index">{{item}}</Option>
							</Select>
						</FormItem>
						<FormItem :label="$t('syllabus.semester')" v-if="isSchool">
							<Select v-model="addVolumeForm.semester">
								<Option v-for="(item,index) in semesterList" :value="index" :key="index">{{item.name}}
								</Option>
							</Select>
						</FormItem>
						<FormItem :label="$t('syllabus.name')">
							<Input v-if="isSchool" v-model="addVolumeForm.name"
								:placeholder="$t('syllabus.place2')" @submit.native.prevent></Input>
							<Input v-else v-model="addVolumeForm.name" :placeholder="$t('syllabus.place3')"></Input>
						</FormItem>
						<FormItem :label="$t('syllabus.authors')" v-if="isSchool">
							<Select v-model="addVolumeForm.auth" multiple filterable>
								<Option v-for="(item,index) in teacherList" :value="item.id" :key="index">{{item.name}}
								</Option>
							</Select>
						</FormItem>
						<FormItem>
							<Button @click="handleSubmit" :loading="isAddLoading">{{ $t('syllabus.confirm') }}</Button>
						</FormItem>
					</Form>
				</div>
			</div>
		</Modal>

		<!-- 新增课纲节点弹窗 -->
		<Modal v-model="isAddTreeModal" width="500" footer-hide class="tree-modal add-volume-modal">
			<div class="modal-header" slot="header">{{ $t('syllabus.tree.addChapterTitle') }}</div>
			<div class="modal-content">
				<!-- <p class="node-title">{{ $t('syllabus.tree.parent') }}</p>
				<Input v-model="curVolume.name" style="width: 100%" disabled /> -->
				<p class="node-title">{{ $t('syllabus.tree.chapterName') }}</p>
				<Input v-model="nodeInfo.title" :placeholder="$t('syllabus.tree.place1')" style="width: 100%" />
			</div>
			<Button @click="onAddTreeNode" style="width: 88%;margin-left: 6%;margin-bottom: 20px;"
				class="modal-btn">{{ $t('syllabus.confirm') }}</Button>
		</Modal>

		<!-- 新增超链接资源弹窗 -->
		<Modal v-model="isShowLinkModal" width="500" footer-hide class="tree-modal add-volume-modal">
			<div class="modal-header" slot="header">{{ $t('syllabus.addLink') }}</div>
			<div class="modal-content">
				<p class="node-title">{{ $t('syllabus.linkName') }}</p>
				<Input v-model="curLink.name" style="width: 100%" />
				<p class="node-title">{{ $t('syllabus.linkUrl') }}</p>
				<Input v-model="curLink.url" placeholder="" style="width: 100%" />
			</div>
			<Button @click="onAddLink" style="width: 88%;margin-left: 6%;margin-bottom: 20px;"
				class="modal-btn">{{ $t('syllabus.confirm') }}</Button>
		</Modal>

		<!-- 关联内容弹窗 -->
		<Modal v-model="isRelateContentModal" width="900" class="tree-modal add-volume-modal choose-content-modal">
			<ChooseContent v-if="isRelateContentModal" ref="chooseContentRef" :showSyllabus="false"
				@previewPaper="onPreviewPaper"></ChooseContent>
			<Button slot="footer" @click="onRelateContent" style="margin-bottom: 20px;" class="modal-btn"
				:loading="isRelateLoading">{{ $t('syllabus.confirm') }}</Button>
		</Modal>

		<!-- 选择共编、分享弹窗 -->
		<Modal v-model="isInviteModal" width="750" footer-hide class="tree-modal add-volume-modal choose-content-modal">
			<div class="modal-header" slot="header">
				{{ isSchool ? $t('syllabus.chooseCoTeacher') : $t('syllabus.chooseShareTeacher') }}
			</div>
			<InviteTeacher :node="curShareNode" :authIds="curVolume.auth.map(i => i.tmdid)" ref="inviteRef" v-if="isInviteModal"></InviteTeacher>
			<!-- <Button slot="footer" @click="doInviteTeacher" style="margin-bottom: 20px;" class="modal-btn">确认</Button> -->
		</Modal>

		<!-- 预览试题试卷弹窗 -->
		<Modal v-model="isPreviewPaper" width="900" footer-hide class="tree-modal tree-paper-modal">
			<div class="paper-box" v-if="previewPaper">
				<p class="paper-title">{{ previewPaper.name }}</p>
				<p class="paper-info">
					<span>{{ $t('syllabus.score') }}：{{ previewPaper.score }}</span>
					<span style="margin-left: 50px;">{{ $t('syllabus.count') }}：{{ previewPaper.item.length  }}</span>
				</p>
			</div>
			<ExerciseList :propsList="questionList" ref="exList" :examScope="isFullList" isAnalysis :hasSas="previewPaper !== null"></ExerciseList>
		</Modal>

		<!--文件预览-->
		<div v-if="previewStatus" class="image-viewer">
			<div style="width:fit-content;position:relative;margin:auto;">
				<Icon type="md-close" class="close-icon" @click="previewStatus = false" />
				<video v-if="previewFile.type == 'video'" id="previewVideo" :src="previewFile.link" width="870"
					controls="controls" style="max-height: 800px;">
					{{$t('teachContent.tips8')}}
				</video>
				<audio v-else-if="previewFile.type == 'audio'" controls>
					<source :src="previewFile.link">
					{{$t('teachContent.notAudio')}}
				</audio>
				<img v-else-if="previewFile.type == 'image'" :src="previewFile.link"
					style="border-radius: 5px;max-height: 800px;max-width:870px;" />
				<!-- <embed v-else-if="previewFile.type == 'doc'" :src="previewFile.link" width="870" height="720" /> -->
				<iframe v-else :src="'https://view.officeapps.live.com/op/view.aspx?src=' + previewFile.link"
					width='870' height='700' frameborder='1'></iframe>
			</div>
		</div>
	</div>
</template>

<script>
	import BlobTool from '@/utils/blobTool.js'
	import Tree from "@/components/syllabus/DragTree";
	import InviteTeacher from "@/components/syllabus/InviteTeacher";
	import ChooseContent from '@/components/selflearn/NewChooseContent'
	import ExerciseList from '@/components/evaluation/ExerciseList.vue'
	export default {
		components: {
			Tree,
			InviteTeacher,
			ChooseContent,
			ExerciseList
		},
		data() {
			return {
				curPrefix:'',
				containerClient: null,
				docType: ['doc', 'docx'],
				excelType: ['xls', 'csv', 'xlsx'],
				pptType: ['ppt', 'pptx'],
				folder: '',
				searchVolumeVal: '',
				activeTab: 'fromCreate',
				isFullList: null,
				isPreviewPaper: false,
				previewStatus: false,
				hasModify: false,
				isLoading: false,
				isSearchVolume: false,
				isAddLoading: false,
				isRelateLoading: false,
				isShowLinkModal: false,
				isUploadModal: false,
				isAddTreeModal: false,
				isAddVolumeModal: false,
				isRelateContentModal: false,
				isInviteModal: false,
				isEditVolume: false,
				isSchool: false,
				currentPeriodIndex: 0,
				activeSubjectIndex: 0,
				activeVolumeIndex: null,
				periodList: [],
				gradeList: [],
				subjectList: [],
				semesterList: [],
				volumeList: [],
				originVolumeList: [],
				myVolumeList: [],
				questionList: [],
				allChapterIds: [],
				teacherList: [],
				schoolInfo: null,
				previewFile: {},
				previewPaper: null,
				curShareNode: null,
				curChapter: null,
				curLink: {
					name: '',
					link: ''
				},
				curSas: {
					sas: '',
					url: '',
					name: ''
				},
				curNode: {
					id: '',
					rnodes: []
				},
				treeOrigin: [],
				curVolume: {
					name: ''
				},
				addVolumeForm: {
					grade: 0,
					semester: 0,
					name: '',
					auth: []
				},
				nodeInfo: {
					"id": "",
					"pid": "",
					"title": "",
					"creatorId": this.curTeammodelId,
					"creatorName": this.curName,
					"type": 1,
					"children": [],
					"rnodes": []
				},
				modifyIdArr: [],
				flatArr: [],
				myCreateChapters:[],
				isSaveSyllabus: false,
			}
		},
		created() {
			this.isSchool = this.$route.name === 'syllabus'
			this.initBlobTool()
			if(this.hasSchool){
				this.getSchoolInfo()
				this.getAllTeacher()
			}else{
				this.getVolumeList()
			}
		},
		methods: {
			/* 初始化BLOB对象 */
			async initBlobTool() {
				let n = this.$route.name === 'syllabus' ? await this.$tools.getSchoolSas() : await this.$tools
					.getPrivateSas()
				this.containerClient = new BlobTool(n.url, n.name, n.sas, this.curScope)
			},
			/* 获取学校基础信息 */
			getSchoolInfo() {
				this.$store.dispatch("user/getSchoolProfile").then((res) => {
					let schoolBaseInfo = res.school_base;
					if (schoolBaseInfo) {
						this.schoolInfo = res;
						if (schoolBaseInfo.period.length) {
							this.periodList = schoolBaseInfo.period
							this.gradeList = schoolBaseInfo.period[0].grades;
							this.subjectList = schoolBaseInfo.period[0].subjects;
							this.semesterList = schoolBaseInfo.period[0].semesters;
							this.getVolumeList()
						}
					}
				});
			},
			/* 获取学校所有教师列表 */
			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')
						}
					},
					err => {
						this.$Message.error('user/setSchoolTeacher API error!')
					}
				)
			},
			/* 提取富文本内容中的文本 */
			async getItemSimpleText(item) {
				try {
					let sas = await this.$evTools.getBlobPrivateSas(item.cntr)
					let indexJsonFile = await this.$tools.getFile(this.$evTools.getBlobHost() + '/' + item.cntr + item
						.link + sas)
					let itemJson = JSON.parse(indexJsonFile)
					return itemJson.item[0].question.replace(/<[^>]+>/g, "") //去掉所有的html标记
				} catch (e) {
					this.$Message.error(e)
				}
			},
			/* 切换学段的操作 */
			onPeriodChange(val) {
				this.subjectList = this.periodList[val].subjects;
				this.gradeList = this.periodList[val].grades;
				this.semesterList = this.periodList[val].semesters;
				this.activeSubjectIndex = 0
				this.activeVolumeIndex = 0
				this.getVolumeList(true)
			},
			/* 切换科目的操作 */
			onSubjectChange(subject, index) {
				this.activeSubjectIndex = index
				this.getVolumeList(true)
			},
			/* 切换个人创建的课纲和他人分享的课纲 */
			onChangeSyllabusTab(type) {
				this.activeTab = type
				this.treeOrigin = []
				this.curNode = {
					id: '',
					rnodes: []
				}
				this.hasModify = false
				type === 'fromCreate' ? this.getVolumeList(true) : this.getShareVolumeList(true)
			},
			/* 获取册别列表 */
			getVolumeList(needRefresh) {
				// 如果当前学校没有科目信息 直接返回
				if(this.isSchool && !this.subjectList.length) return
				this.isLoading = true
				this.treeOrigin = []
				this.curNode = {
					id: '',
					rnodes: []
				}
				let findParams = {
					"periodId": this.isSchool ? this.periodList[this.currentPeriodIndex].id : '',
					"subjectId": this.isSchool ? this.subjectList[this.activeSubjectIndex].id : '',
					"status": 1,
					"code": this.curCode,
					"scope": this.curScope
				}
				// 查找列表
				this.$api.syllabus.FindVolumes(findParams).then(res => {
					if (!res.error) {
						this.isLoading = false
						this.volumeList = res.volumes.reverse()
						this.originVolumeList = JSON.parse(JSON.stringify(this.volumeList))
						this.myVolumeList = JSON.parse(JSON.stringify(this.volumeList))
						// let activeIndex = this.isEditVolume ? this.activeVolumeIndex : 0
						let activeIndex = this.activeVolumeIndex || 0
						// this.isEditVolume = false
						res.volumes.length && this.onVolumeClick(res.volumes[activeIndex], activeIndex,
							needRefresh)
					} else {
						this.$Message.warning(res.error);
					}
				}).catch(err => {
					this.$Message.error(err);
				})
			},
			/* 获取分享来的册别列表 */
			getShareVolumeList(needRefresh) {
				this.$api.syllabus.FindShare({
					"code": this.curTeammodelId,
					"type": "share"
				}).then(res => {
					if (!res.error) {
						this.isLoading = false
						if (res.shares.length) {
							let shareList = res.shares.map(i => {
								return {
									id: i.id,
									creatorId: i.code,
									creatorName:i.issuerName,
									name: i.list[0].volumeName,
									children: i.list,
									pk: 'Volume',
									school: '',
									scope: 'private',
									status: 1,
									auth:[]
								}
							})
							shareList.forEach(i => {
								if (i.children.length && !i.children.filter(j => j.agree !== -1).length) {
									i.isDel = true
								}
							})
							this.volumeList = shareList.reverse()
							this.originVolumeList = JSON.parse(JSON.stringify(this.volumeList))
							let activeIndex = this.isEditVolume ? this.activeVolumeIndex : 0
							shareList.length && this.onVolumeClick(shareList[activeIndex], activeIndex,
								needRefresh)
						} else {
							this.volumeList = []
							this.originVolumeList = []
						}

					} else {
						this.$Message.warning(res.error);
					}
				}).catch(err => {
					this.$Message.error(err);
				})
			},
			/* 删除已失效的册别 */
			onDeleteShareVolume(volume) {
				let chapterIds = volume.children.length ? volume.children.map(i => i.id) : []
				this.$Modal.confirm({
					title: this.$t('syllabus.tree.removeTitle'),
					content: this.$t('syllabus.deleteIsDelConfirm'),
					onOk: () => {
						this.$api.syllabus.ShareAgree({
							"code": this.curTeammodelId,
							"ids": chapterIds,
							"type": "share",
							"opt": "ignore"
						}).then(res => {
							if (res.status === 200) {
								this.$Message.success(this.$t('syllabus.doSuc'))
								this.getShareVolumeList(true)
							}
						})
					}
				})
			},
			/* 点击某个册别 */
			onVolumeClick(volume, volumeIndex, needRefresh) {
				if (this.hasModify && this.curVolume && volume.id !== this.curVolume.id) {
					this.$Modal.confirm({
						title: this.$t('evaluation.newExercise.modalTip'),
						content: this.$t('syllabus.unSaveTip'),
						onOk: () => {
							if (volume && volume.id !== this.curVolume.id){
								sessionStorage.removeItem('highlightId')
							}
							if (volume && volume.isDel) {
								this.$Message.warning(this.$t('syllabus.isDelTip'))
								this.activeVolumeIndex = volumeIndex
								this.curVolume = volume
								this.treeOrigin = []
								this.curNode = {
									id: '',
									rnodes: []
								}
								return
							}
							if (!volume || (volume.id === this.curVolume.id && !this.isEditVolume && !needRefresh)) return
							this.isLoading = true
							this.curVolume = volume
							this.allChapterIds = volume.syllabusIds || []
							this.activeVolumeIndex = volumeIndex
							this.activeTab === 'fromCreate' ? this.getTreeByVolumeId(volume) : this.getShareTree(volume)
							this.hasModify = false
							this.modifyIdArr = []
						}
					});
				}else{
					if (volume && volume.id !== this.curVolume.id){
						sessionStorage.removeItem('highlightId')
					}
					if (volume && volume.isDel) {
						this.$Message.warning(this.$t('syllabus.isDelTip'))
						this.activeVolumeIndex = volumeIndex
						this.curVolume = volume
						this.treeOrigin = []
						this.curNode = {
							id: '',
							rnodes: []
						}
						return
					}
					if (!volume || (volume.id === this.curVolume.id && !this.isEditVolume && !needRefresh)) return
					this.isLoading = true
					this.curVolume = volume
					this.allChapterIds = volume.syllabusIds || []
					this.activeVolumeIndex = volumeIndex
					this.activeTab === 'fromCreate' ? this.getTreeByVolumeId(volume) : this.getShareTree(volume)
					this.hasModify = false
					this.modifyIdArr = []
				}
			},
			/* 添加册别 */
			doAddVolume() {
				if(this.isSchool && (!this.subjectList.length || !this.semesterList.length || !this.gradeList.length)){
					this.$Message.warning(this.$t('evaluation.completeTip'))
					return
				}
				this.addVolumeForm = {
					grade: 0,
					semester: 0,
					name: '',
					auth:[]
				}
				this.isEditVolume = false
				this.isAddVolumeModal = true
			},
			/* 搜索册别 */
			doSearchVolume() {
				this.isSearchVolume = true
			},
			/* 搜索词汇发生变化 */
			onSearchChange() {
				this.volumeList = this.originVolumeList.filter(i => i.name.indexOf(this.searchVolumeVal) > -1)
				this.volumeList.length && this.onVolumeClick(this.volumeList[0], 0)
			},
			/* 关闭搜索 */
			onCloseSearch() {
				this.isSearchVolume = false
				this.searchVolumeVal = ''
				this.volumeList = JSON.parse(JSON.stringify(this.originVolumeList))
				this.volumeList.length && this.onVolumeClick(this.volumeList[0], 0)
			},
			/* 编辑当前册别 */
			doEditVolume() {
				this.addVolumeForm = {
					grade: this.curVolume.gradeId,
					semester: this.semesterList.map(i => i.id).indexOf(this.curVolume.semesterId),
					name: this.curVolume.name,
					auth:this.curVolume.auth.length ? this.curVolume.auth.map(i => i.tmdid) : []
				}
				this.isEditVolume = true
				this.isAddVolumeModal = true
			},
			/* 删除当前册别 */
			doDeleteVolume() {
				let curVolume = this.curVolume
				let links = this.getVolumeRnodeLinks()
				this.$Modal.confirm({
					title: this.$t('syllabus.deleteVolume'),
					content: this.$t('syllabus.deleteConfirm'),
					onOk: () => {
						this.isLoading = true;
						this.doDeleteBlobResource(links).then(result => {
							this.$api.syllabus.DeleteVolume({
								id: curVolume.id,
								code: curVolume.code.replace('Volume-', ''),
								scope: curVolume.scope
							}).then((res) => {
								if (res) {
									this.volumeList.splice(this.activeVolumeIndex, 1);
									this.treeOrigin = []
									this.curNode.rnodes = []
									this.curNode.id = ''
									this.$Message.success(this.$t('syllabus.deleteSuc'));
									console.log(this.activeVolumeIndex);
									this.onVolumeClick(this.volumeList.length ? this
										.volumeList[0] : null, 0, true)
									this.isLoading = false;
								} else {
									this.$Message.error(this.$t('syllabus.deleteFail'));
								}
							});
						}).catch(err => {
							this.isLoading = false;
							this.$Message.error(this.$t('syllabus.deleteFail') + err);
						})
					},
				});
			},
			/* 删除对应关联的资源 */
			doDeleteBlobResource(links) {
				return new Promise((r, j) => {
					if (!links.length) r(200)
					let syllabusLinks = links.filter(i => i.includes('/syllabus/'))
					if (syllabusLinks.length) {
						this.$api.syllabus.CheckLink({
							"links": syllabusLinks,
							"code": this.curCode,
							"scope": this.curScope
						}).then(res => {
							console.log(res)
							let needDeleteLink = []
							let curVolumeId = this.curVolume.id
							syllabusLinks.forEach(i => {
								if (!res.links.filter(j => j.link === i && j.volumeId !==
										curVolumeId).length) {
									needDeleteLink.push(i)
								}
							})
							if (needDeleteLink.length) {
								let promiseArr = []
								needDeleteLink.forEach(i => {
									promiseArr.push(this.deleteBlobPrefix({
										cntr: this.curCode,
										title: i.replace('/syllabus/', ''),
										link:i
									}))
								})
								Promise.all(promiseArr).then(result => {
									r(result)
								}).catch(err => {
									j(err)
								})
							} else {
								r(200)
							}
						}).catch(e => {
							j(e)
						})
					} else {
						r(200)
					}
				})
			},
			/* 获取当前册别课纲下所有的资源link */
			getVolumeRnodeLinks() {
				let volumeRnodeLinks = []
				if (this.treeOrigin.length) {
					this.treeOrigin.forEach(i => {
						volumeRnodeLinks.push(...this.getAllRNodes(i.trees[0]).map(j => j.link))
					})
					return volumeRnodeLinks
				} else {
					return []
				}
			},
			/* 获取章节下所有的资源节点 */
			getAllRNodes(chapterNode) {
				let result = []
				const fn = (source) => {
					result.push(...source.rnodes)
					if (source.children.length) {
						console.log(JSON.stringify(source.children[0].rnodes));
						source.children.forEach(i => {
							fn(i)
						})
					}
				}
				fn(chapterNode)
				return result
			},
			/* 根据册别查询对应课纲树形结构 */
			getTreeByVolumeId(volume) {
				this.curNode.rnodes = []
				this.curNode.id = ''
				this.$api.syllabus.GetTreeByVolume({
					volumeId: volume.id,
					volumeCode: volume.code,
					scope: volume.scope
				}).then(res => {
					if (!res.error) {
						this.treeOrigin = res.tree
						this.getAllChild(this.treeOrigin.map(i => {
							i.trees[0].auth = i.auth
							return i.trees[0]
						}))
					} else {
						this.$Message.warning(res.error);
						this.treeOrigin = []
					}
				}).catch(err => {
					this.treeOrigin = []
				}).finally(() => {
					this.isLoading = false
				})
			},
			/* 获取分享课纲的树形数据 */
			getShareTree(volume) {
				this.$api.syllabus.ViewShare({
					"scope": "private",
					"school": "",
					"issuer": volume.creatorId,
					"volumeId": volume.id,
					"syllabusId": volume.children.map(i => i.id)
				}).then(res => {
					if (!res.error) {
						this.treeOrigin = res.tree
						this.getAllChild(this.treeOrigin.map(i => {
							i.trees[0].auth = i.auth
							return i.trees[0]
						}))
					} else {
						this.$Message.warning(res.error);
						this.treeOrigin = []
					}
				}).catch(err => {
					this.treeOrigin = []
				}).finally(() => {
					this.isLoading = false
				})
			},
			/* 添加课纲的第一层节点 */
			onAddTreeNode() {
				this.nodeInfo.id = this.$tools.guid()
				this.nodeInfo.pid = this.curVolume.id
				this.nodeInfo.creatorId = this.curTeammodelId
				this.nodeInfo.creatorName = this.curName
				// 统一传给树形组件的数据结构
				this.treeOrigin.push({
					auth: this.isSchool ? [{
						agree:0,
						tmdid:this.curTeammodelId,
						tmdname:this.curName,
						type:'coedit'
					}] : [],
					id: this.nodeInfo.id,
					creatorId:this.curTeammodelId,
					creatorName:this.curName,
					scope: this.curVolume.scope,
					trees: [this.nodeInfo],
					volumeId: this.curVolume.id,
					rnodes: []
				})
				this.myCreateChapters.push({
					name:this.nodeInfo.title,
					id:this.nodeInfo.id
				})
				// 只要本地新增的章节 都要记录到修改数据里
				this.$nextTick(() => {
					this.modifyIdArr.push(this.nodeInfo.id)
					// 还原默认值
					this.nodeInfo = {
						"id": "",
						"pid": "",
						"title": "",
						"type": 1,
						"creatorId":this.curTeammodelId,
						"creatorName":this.curName,
						"children": [],
						"rnodes": []
					}
				})
				this.hasModify = true;
				this.isAddTreeModal = false

			},
			/* 有章节发生变化记录章节ID */
			addModifyId(id) {
				console.log(id)
				this.modifyIdArr.push(id)
			},
			/* 存储变更保存最新课纲数据 */
			onSaveSyllabus() {
				this.isSaveSyllabus = true
				// 拿到有修改变动的章节ID集合
				let modifyIdArr = [...new Set(this.modifyIdArr)].filter(i => i !== this.curVolume.id && i)
				console.log(modifyIdArr)
				let allChapter = this.$refs.treeRef ? this.$refs.treeRef.treeDatas : [];
				let modifyChapters = modifyIdArr.length ? modifyIdArr.map(id => {
					return {
						id: id,
						codeval: this.curCode,
						volumeId: this.curVolume.id,
						scope: this.curVolume.scope,
						creatorId:this.curTeammodelId,
						creatorName:this.curName,
						trees: allChapter.find(i => i.id === id) ? [allChapter.find(i => i.id === id)] : []
					}
				}) : [];
				this.allChapterIds = allChapter.map(i => i.id)
				// 先保存树结构数据
				this.$api.syllabus.UpsertTree(modifyChapters).then((res) => {
					if (!res.error && res) {
						// 然后保存册别的章节ID集合
						this.handleSubmit().then(result => {
							let promiseArr = []
							if(this.myCreateChapters.length){
								// 然后如果是自己新增的章节 则需要把自己加入到共编权限内
								this.myCreateChapters.forEach(i => {
									if(modifyIdArr.includes(i.id)){
										promiseArr.push(this.doShareMyself(i.id,i.name))
									}
								})
								Promise.all(promiseArr).then(shareResult => {
									console.log(res)
									// this.treeOrigin = res;
									this.hasModify = false;
									this.$refs.treeRef && (this.$refs.treeRef.modifyIdArr = [])
								}).catch(err => {
									this.$Message.error(err)
								})
							}
						})
					} else {
						this.$Message.warning(this.$t('syllabus.saveFailTip'));
					}
				});
			},
			/* 新增的章节 需要把创建者加入到共编数据内 */
			doShareMyself(id,name){
				return new Promise((r,j) => {
					let curVolume = this.curVolume
					this.$api.syllabus.ShareTree({
						"school": curVolume.school,
						"scope": curVolume.scope,
						"tmdInfo": [
							{
								"tmdid": this.curTeammodelId,
								"tmdname": this.curName
							}
						],
						"type": 'coedit',
						"issuer": this.curTeammodelId,
						"opt": 'add',
						"syllabusId": id,
						"syllabusName":name,
						"volumeId": curVolume.id,
						"volumeName": curVolume.name
					}).then(res => {
						if(res.code === 200){
							r(200)
						}
					}).catch(err => {
						this.$Message.error(err)
						j(err)
					})
				})
				
			},
			/* 点击某个节点 */
			onNodeClick(data) {
				this.curChapter = this.getChapterByNode(data.node)
				// 如果当前节点有关联试题资源 则需要去拿到试题完整信息 来给title赋值 保证为最新数据
				if (data.data.rnodes && data.data.rnodes.length) {
					let itemNodeArr = data.data.rnodes.filter(i => i.type === 'item')
					if (itemNodeArr.length) {
						itemNodeArr.forEach(async item => {
							item.title = await this.getItemSimpleText(item)
							this.curNode = data.data
						})
					} else {
						this.curNode = data.data
					}
				} else {
					this.curNode = data.data
				}
				console.log('当前点击节点数据 ==== ', data.data.title, data.data.rnodes)
			},
			/* 根据节点获取它所在的章节信息 */
			getChapterByNode(node) {
				if (node.level === 1) {
					return node
				} else {
					return this.getChapterByNode(node.parent)
				}
			},
			/* 点击节点进行分享 */
			doShare(data) {
				this.curShareNode = data
				this.isInviteModal = true
			},
			/* 点击确认进行课纲的共编或者分享功能 */
			doInviteTeacher() {
				let selectedTeacher = this.$refs.inviteRef.teacherList
			},
			/* 添加超链接 */
			onAddLink() {
				console.log(this.$refs.treeRef.curData)
				let curLink = this.curLink.url
				if (!/^(http:|https:)/i.test(curLink)) {
					curLink = "http://" + curLink;
				}
				if (!this.isURL(curLink)) {
					this.$Message.warning(this.$t('evaluation.repairResourse.formatErrorTip'))
					return
				}
				this.$refs.treeRef.curData.rnodes.push({
					code: this.curCode,
					scope: this.curScope,
					id: this.$tools.guid(),
					link: curLink,
					title: this.curLink.name,
					type: 'link',
					ctnr: ''
				})
				this.$refs.treeRef.curData.creatorId = this.curTeammodelId
				this.$refs.treeRef.curData.creatorName = this.curName
				this.modifyIdArr.push(this.curChapter.data.id)
				this.hasModify = true
				this.isShowLinkModal = false
			},
			/* 判断是否为正确的链接地址 */
			isURL(url) {
				const strRegex = '^((https|http|ftp)://)?' //(https或http或ftp):// 可有可无
					+
					'(([\\w_!~*\'()\\.&=+$%-]+: )?[\\w_!~*\'()\\.&=+$%-]+@)?' //ftp的user@ 可有可无
					+
					'(([0-9]{1,3}\\.){3}[0-9]{1,3}' // IP形式的URL- 3位数字.3位数字.3位数字.3位数字
					+
					'|' // 允许IP和DOMAIN（域名）
					+
					'(localhost)|' //匹配localhost
					+
					'([\\w_!~*\'()-]+\\.)*' // 域名- 至少一个[英文或数字_!~*\'()-]加上.
					+
					'\\w+\\.' // 一级域名 -英文或数字 加上.
					+
					'[a-zA-Z]{1,6})' // 顶级域名- 1-6位英文
					+
					'(:[0-9]{1,5})?' // 端口- :80 ,1-5位数字
					+
					'((/?)|' // url无参数结尾 - 斜杆或这没有
					+
					'(/[\\w_!~*\'()\\.;?:@&=+$,%#-]+)+/?)$'; //请求参数结尾- 英文或数字和[]内的各种字符
				const re = new RegExp(strRegex, 'i'); // 大小写不敏感
				if (re.test(encodeURI(url))) {
					return true;
				}
				return false;
			},
			/* 点击添加关联内容 */
			async onAddResource(type) {
				console.log(type)
				if (type === 'file') {
					this.curSas = this.isSchool ? await this.$tools.getSchoolSas() : await this.$tools.getPrivateSas()
					this.curPrefix = `syllabus/${this.curNode.id}`
					this.isUploadModal = true
				} else if (type === 'link') {
					this.curLink.name = ''
					this.curLink.url = ''
					this.isShowLinkModal = true
				} else {
					this.isRelateContentModal = true
					this.$nextTick(() => {
						this.$refs.chooseContentRef.clickTab(type)
					})
				}
			},
			/* 上传本地文件成功回调 */
			uploadFinish(result) {
				result.forEach(file => {
					this.$refs.treeRef.curData.rnodes.push({
						code: this.curCode,
						scope: this.curScope,
						id: this.$tools.guid(),
						link: `/syllabus/${this.curNode.id}/${file.name}`,
						title: file.name,
						type: file.type,
						cntr: this.curCode
					})
				})
				this.modifyIdArr.push(this.curChapter.data.id)
				// this.hasModify = true
				this.isUploadModal = false
				// this.$Message.success(this.$t('syllabus.uploadSuc'))
				// console.log(result)
				this.onSaveSyllabus()
			},
			/* 获取关联的内容数据，需要进行相应的文件拷贝 */
			async onSelectFile() {
				return new Promise(async (r, j) => {
					let list = this.$refs.chooseContentRef.selectedFiles
					if (!list.length) {
						r(200)
					} else {
						let promiseArr = []
						let privateSas = await this.$tools.getPrivateSas()
						let schoolSas = await this.$tools.getSchoolSas()
						let curResourceArr = this.$refs.treeRef.curData.rnodes
						for (let i = 0; i < list.length; i++) {
							promiseArr.push(new Promise((r2, j2) => {
								let file = list[i]
								let sas = file.scope === 'school' ? schoolSas.sas : privateSas
									.sas
								this.containerClient.copyBlob(`syllabus/${this.curNode.id}/` + file.name, file
									.url, sas).then(res => {
									curResourceArr.push({
										type: file.type,
										title: file.name,
										id: this.$tools.guid(),
										code: this.curCode,
										scope: this.isSchool ? 'school' :
											'private',
										cntr: this.isSchool ? this
											.$store.state.userInfo.schoolCode :
											this.$store.state
											.userInfo.TEAMModelId,
										link: `/syllabus/${this.curNode.id}/${file.name}`
									})
									r2(200)

								}).catch(err => {
									console.log(err)
									j2(err)
								})
							}))
						}
						Promise.all(promiseArr).then(result => {
							r(200)
						}).catch(err => {
							console.log(err)
							j(err)
						})
					}
				})

			},
			/* 保存单个试题 */
			saveExercise(item, scope) {
				console.log(item)
				console.log(scope)
				return new Promise(async (r, j) => {
					let cosmosItem = await this.$editorTools.transBase64Src(item)
					this.$api.newEvaluation.SaveSingleExercise({
						itemInfo: await this.$evTools.createCosmosItem(cosmosItem, scope),
						option: "insert",
					}).then((res) => {
						r(res)
					}).catch(err => {
						j(err)
					});
				});
			},
			/* 校本课纲关联个人试题试卷要进行入库操作 */
			saveItemToBlob(pItem, privateToSchool, isSaveToItem) {
				return new Promise(async (r, j) => {
					pItem = await this.$editorTools.doRemoveMideaHost(pItem)
					console.log(pItem)
					console.log(isSaveToItem)
					let targetPrefix = isSaveToItem ? 'item/' : `syllabus/${this.curNode.id}/`
					let sourcePrefix = 'item/'
					let targetPath = targetPrefix + pItem.id + '/'
					let sourcePath = sourcePrefix + pItem.id
					let privateSas = await this.$tools.getPrivateSas()
					let privateBlobTool = new BlobTool(privateSas.url, privateSas.name, privateSas.sas,
						'private')
					let schoolSas = await this.$tools.getSchoolSas()
					let schoolBlobTool = new BlobTool(schoolSas.url, schoolSas.name, schoolSas.sas,
						'school')
					let toClient = this.isSchool ? schoolBlobTool : privateBlobTool
					let fromClient = pItem.scope === 'private' ? privateBlobTool : schoolBlobTool
					const itemJsonFile = await this.$evTools.createBlobItem(pItem);
					let file = new File([JSON.stringify(itemJsonFile)], pItem.id + ".json", {
						type: "",
					});
					// 先把对应试题目录下的全部复制到校本BLOB 然后再更新添加学段科目等字段后的题目Json文件
					toClient.copyFolder(targetPath, sourcePath, fromClient).then(async res => {
						try {
							let blobFile = await toClient.upload(file, targetPrefix + pItem.id);
							if (blobFile.blob) {
								if(isSaveToItem){
									this.saveExercise(pItem).then(result => {
										console.log(result)
										r(result)
									})
								}else{
									r({
										id:pItem.id,
										question:pItem.question,
										blob: '/' + targetPath + pItem.id + '.json'
									})
								}
							}
						} catch (e) {
							console.log(e)
							j(e)
						}
					}).catch(err => {
						j(err)
					})
				})
			},
			/* 获取关联的试题数据 */
			async onSelectQuestion(val) {
				return new Promise(async (r, j) => {
					let exRef = this.$refs.chooseContentRef.$refs.exListRef
					let list = exRef ? exRef.selectItems : []
					if (!list.length) {
						r(200)
					} else {
						let curResourceArr = this.$refs.treeRef.curData.rnodes
						let promiseArr = []
						list.forEach(pItem => {
							promiseArr.push(this.saveItemToBlob(pItem, true, false))
						})
						Promise.all(promiseArr).then(result => {
							list.forEach(i => {
								if (!curResourceArr.filter(j => j.type === 'item').map(k => k
										.id).includes(i
										.id)) {
									curResourceArr.push({
										type: 'item',
										title: i.question,
										id: i.id,
										code: 'Item-' + this.curCode,
										scope: this.curScope,
										cntr: this.curCode,
										link: `/syllabus/${this.curNode.id}/${i.id}/${i.id}.json`
									})
								}
							})
							r(200)
						}).catch(err => {
							this.$Message.error(err)
						})
						
						/* 暂时取消入库操作 全部保存到syllabus目录下*/
						// 拿到关联的个人试题和校本试题
						// let privateItems = list.filter(i => i.scope === 'private')
						// let schoolItems = list.filter(i => i.scope === 'school')
						// // 如果是在校本课纲关联的个人试题 则需要进行入库操作
						// if (this.isSchool && privateItems.length) {
						// 	let isSaveToItem = await this.doConfirm()
						// 	let promiseArr = []
						// 	// 个人试题入库前需要补充必要的学段科目年级信息
						// 	privateItems.forEach(pItem => {
						// 		pItem.periodId = this.periodList[this.currentPeriodIndex].id
						// 		pItem.subjectId = this.subjectList[this.activeSubjectIndex].id
						// 		pItem.gradeIds = [this.curVolume.gradeId + '']
						// 		pItem.scope = 'school'
						// 		pItem.code = this.$store.state.userInfo.schoolCode
						// 		promiseArr.push(this.saveItemToBlob(pItem, true, isSaveToItem))
						// 	})
						// 	Promise.all(promiseArr).then(result => {
						// 		list.forEach(i => {
						// 			if (!curResourceArr.filter(j => j.type === 'item').map(k => k
						// 					.id).includes(i
						// 					.id)) {
						// 				curResourceArr.push({
						// 					type: 'item',
						// 					title: i.question,
						// 					id: i.id,
						// 					code: 'Item-' + this.$store.state.userInfo
						// 						.schoolCode,
						// 					scope: 'school',
						// 					cntr: this.$store.state.userInfo.schoolCode,
						// 					link: isSaveToItem ? i.blob : `/syllabus/${i.id}/${i.id}.json`
						// 				})
						// 			}
						// 		})
						// 		r(200)
						// 	}).catch(err => {
						// 		this.$Message.error(err)
						// 	})
						// } else if (!this.isSchool && schoolItems.length) {
						// 	let promiseArr = []
						// 	let isSaveToItem = await this.doConfirm()
						// 	// 个人试题入库前需要补充必要的学段科目年级信息
						// 	schoolItems.forEach(pItem => {
						// 		pItem.periodId = null
						// 		pItem.subjectId = null
						// 		pItem.gradeIds = null
						// 		pItem.scope = 'private'
						// 		pItem.code = this.curTeammodelId
						// 		promiseArr.push(this.saveItemToBlob(pItem, false, isSaveToItem))
						// 	})
						// 	Promise.all(promiseArr).then(result => {
						// 		list.forEach(i => {
						// 			if (!curResourceArr.filter(j => j.type === 'item').map(k => k
						// 					.id).includes(i
						// 					.id)) {
						// 				curResourceArr.push({
						// 					type: 'item',
						// 					title: i.question,
						// 					id: i.id,
						// 					code: 'Item-' + this.$store.state.userInfo
						// 						.TEAMModelId,
						// 					scope: 'private',
						// 					cntr: this.curTeammodelId,
						// 					link: isSaveToItem ? i.blob : `/syllabus/${i.id}/${i.id}.json`
						// 				})
						// 			}
						// 		})
						// 		r(200)
						// 	}).catch(err => {
						// 		this.$Message.error(err)
						// 	})
						// } else {
						// 	list.forEach(i => {
						// 		if (!curResourceArr.filter(j => j.type === 'item').map(k => k.id).includes(
						// 				i.id)) {
						// 			curResourceArr.push({
						// 				type: 'item',
						// 				title: i.question,
						// 				id: i.id,
						// 				code: i.code,
						// 				scope: i.scope,
						// 				cntr: i.scope === 'school' ? this.$store.state.userInfo
						// 					.schoolCode : this
						// 					.$store.state
						// 					.userInfo.TEAMModelId,
						// 				link: i.blob
						// 			})
						// 		}
						// 	})
						// 	r(200)
						// }
					}
				})
			},
			/* 入库前的确认操作 */
			doConfirm(){
				return new Promise((r,j) => {
					this.$Modal.confirm({
						title: '提示',
						content: `关联的试题试卷是否要同步到您的${this.isSchool ? '校本资源库' : '个人资源库'}?`,
						onOk: async () => {
							r(true)
						},
						onCancel: () => {
							r(false)
						}
					})
				})
			},
			/* 判断试卷名称是否已存在校本库中 */
			getSchoolPaperList() {
				return new Promise((r, j) => {
					this.$api.learnActivity.FindExamPaper({
						"code": this.$store.state.userInfo.schoolCode,
						"scope": "school"
					}).then(result => {
						if (!result.error) {
							r(result.papers)
						} else {
							j(result.error)
						}
					}).catch(e => {
						j(false)
					})
				})
			},
			/* 将个人同步到校本的试卷 保存一份到cosmos */
			savePaperToCosmos(paper, scoring, isUpdate) {
				paper.scoring = scoring
				paper.blob = '/paper/' + paper.name
				return new Promise(async (r, j) => {
					let params = {
						paper: await this.$evTools.createCosmosPaper(paper),
						option: isUpdate ? 'update' : 'insert'
					}
					//  保存试卷到cosmos
					this.$api.learnActivity.SaveExamPaper(params).then(
						res => {
							if (res.error == null) {
								r(res)
							} else {
								r(res.error)
							}
						},
						err => {
							j(err)
						}
					)
				})

			},
			/* 将个人试卷导入到校本试卷库中 */
			savePaperToSchoolBlob(paper, scoring, isUpdate) {
				return new Promise(async (r, j) => {
					let path = `syllabus/${this.curNode.id}/` + paper.name + '/'
					let sourcePath = 'paper/' + paper.name
					let privateSas = await this.$tools.getPrivateSas()
					let privateBlobTool = new BlobTool(privateSas.url, privateSas.name, privateSas.sas,'private')
					let schoolSas = await this.$tools.getSchoolSas()
					let schoolBlobTool = new BlobTool(schoolSas.url, schoolSas.name, schoolSas.sas,
						'school')
					let toClient = this.isSchool ? schoolBlobTool : privateBlobTool
					let fromClient = paper.scope === 'private' ? privateBlobTool : schoolBlobTool
					
					let file = new File([JSON.stringify(paper)], "index.json", {
						type: "",
					});
					// 先把对应试题目录下的全部复制到校本BLOB 然后再更新添加学段科目等字段后的题目Json文件
					toClient.copyFolder(path, sourcePath, fromClient)
						.then(async res => {
							r(200)
						}).catch(err => {
							j(err)
						})
				})
			},
			/* 获取关联的试卷数据 */
			onSelectPaper() {
				return new Promise(async (r, j) => {
					let paperRef = this.$refs.chooseContentRef.$refs.paperListRef
					let list = paperRef ? paperRef.checkedPaperList : []
					if (!list.length) {
						r(200)
					} else {
						let curResourceArr = this.$refs.treeRef.curData.rnodes
						// 拿到关联的个人试卷
						let privatePapers = list.filter(i => i.scope === 'private')
						let privateSas = await this.$tools.getPrivateSas()
						let promiseArr = []
						list.forEach(paper => {
							promiseArr.push(this.savePaperToSchoolBlob(paper, paper.scoring,true))
						})
						
						Promise.all(promiseArr).then(result => {
							console.log(result)
							list.forEach(i => {
								if (!curResourceArr.filter(j => j.type === 'paper').map(
										k => k.id).includes(i.id)) {
									curResourceArr.push({
										type: 'paper',
										title: i.name,
										id: i.id,
										code: 'Paper-' + this.curCode,
										scope: this.curScope,
										cntr: this.curCode,
										link: `/syllabus/${this.curNode.id}/${i.name}`
									})
								}
							})
							r(200)
						}).catch(err => {
							j(err)
						})
						
						/* =================暂时不做入库操作======================================== */
						// 如果是在校本课纲关联的个人试卷 则需要进行入库操作
						// if (this.isSchool && privatePapers.length) {
						// 	let schoolPaperList = await this.getSchoolPaperList()
						// 	console.log(privatePapers)
						// 	let promiseArr = []
						// 	privatePapers.forEach(async paper => {
						// 		if (schoolPaperList.map(i => i.name).includes(paper.name)) {
						// 			this.$Modal.confirm({
						// 				title: '提示',
						// 				content: this.$t('syllabus.copyTip1') + paper
						// 					.name +
						// 					this.$t('syllabus.copyTip2'),
						// 				onOk: async () => {
						// 					// 继续进行操作完成试卷覆盖
						// 					// 拿到试卷的index.json 先完善学段科目年级信息后 去进行上传覆盖操作
						// 					let indexJsonFile = await this.$tools
						// 						.getFile(this.$evTools.getBlobHost() +
						// 							'/' + paper.code.replace('Paper-',
						// 								'') + paper.blob +
						// 							'/index.json' + privateSas.sas)
						// 					let paperIndexJson = JSON.parse(
						// 						indexJsonFile)
						// 					paperIndexJson.periodId = this.periodList[
						// 						this.currentPeriodIndex].id
						// 					paperIndexJson.subjectId = this
						// 						.subjectList[this.activeSubjectIndex]
						// 						.id
						// 					paperIndexJson.subjectName = this
						// 						.subjectList[this.activeSubjectIndex]
						// 						.name
						// 					paperIndexJson.gradeIds = [this.curVolume
						// 						.gradeId + ''
						// 					]
						// 					paperIndexJson.scope = 'school'
						// 					paperIndexJson.code = this.$store.state
						// 						.userInfo.schoolCode
						// 					console.log(paperIndexJson)
						// 					promiseArr.push(this.savePaperToSchoolBlob(
						// 						paperIndexJson, paper.scoring,
						// 						true))
						// 				},
						// 				onCancel: () => {
						// 					// 取消则无法关联当前试卷到节点
						// 					curResourceArr.splice(curResourceArr.map(
						// 							i => i.id).indexOf(paper.id),
						// 						1)
						// 				}
						// 			})
						// 		} else {
						// 			// 拿到试卷的index.json 先完善学段科目年级信息后 去进行上传覆盖操作
						// 			let indexJsonFile = await this.$tools.getFile(this.$evTools
						// 				.getBlobHost() + '/' + paper.code.replace('Paper-',
						// 					'') + paper.blob + '/index.json' + privateSas.sas)
						// 			let paperIndexJson = JSON.parse(indexJsonFile)
						// 			paperIndexJson.periodId = this.periodList[this
						// 				.currentPeriodIndex].id
						// 			paperIndexJson.subjectId = this.subjectList[this
						// 				.activeSubjectIndex].id
						// 			paperIndexJson.subjectName = this.subjectList[this
						// 				.activeSubjectIndex].name
						// 			paperIndexJson.gradeIds = [this.curVolume.gradeId + '']
						// 			paperIndexJson.scope = 'school'
						// 			paperIndexJson.code = this.$store.state.userInfo.schoolCode
						// 			console.log(paperIndexJson)
						// 			promiseArr.push(this.savePaperToSchoolBlob(paperIndexJson,
						// 				paper.scoring))
						// 		}

						// 	})
						// 	Promise.all(promiseArr).then(result => {
						// 		console.log(result)
						// 		list.forEach(i => {
						// 			if (!curResourceArr.filter(j => j.type === 'paper').map(
						// 					k => k.id).includes(i.id)) {
						// 				curResourceArr.push({
						// 					type: 'paper',
						// 					title: i.name,
						// 					id: i.id,
						// 					code: 'Paper-' + this.curCode,
						// 					scope: 'school',
						// 					cntr: this.curCode,
						// 					link: i.blob
						// 				})
						// 			}
						// 		})
						// 		r(200)
						// 	}).catch(err => {
						// 		j(err)
						// 	})
						// } else {
						// 	list.forEach(i => {
						// 		if (!curResourceArr.filter(j => j.type === 'paper').map(k => k.id)
						// 			.includes(i.id)) {
						// 			curResourceArr.push({
						// 				type: 'paper',
						// 				title: i.name,
						// 				id: i.id,
						// 				code: i.code,
						// 				scope: i.scope,
						// 				cntr: i.scope === 'school' ? this.$store.state.userInfo
						// 					.schoolCode : this
						// 					.$store.state
						// 					.userInfo.TEAMModelId,
						// 				link: i.blob
						// 			})
						// 		}
						// 	})
						// 	r(200)
						// }
					}

				})

			},
			/* 点击确认 去获取关联的内容数据、试题试卷数据 */
			onRelateContent() {
				this.isRelateLoading = true
				Promise.all([this.onSelectFile(), this.onSelectQuestion(), this.onSelectPaper()]).then(result => {
					console.log(result)
					this.isRelateLoading = false
					this.isRelateContentModal = false
					this.hasModify = true
					this.modifyIdArr.push(this.curChapter.data.id)
					this.$refs.treeRef.curData.creatorId = this.curTeammodelId
					this.$refs.treeRef.curData.creatorName = this.curName
				}).catch(err => {
					console.log(err)
					this.isRelateLoading = false
					this.$Message.error(err)
				})
			},
			/* 预览关联资源 */
			async onPreview(item) {
				console.log(item)
				this.questionList = []
				let sasObj = item.scope === 'school' ? await this.$tools.getSchoolSas() : await this.$tools
					.getPrivateSas()
				switch (item.type) {
					case 'item':
					    this.isLoading = true
						this.previewPaper = null
						let tmdId = item.code.replace('Item-', '')
						// 如果不是当前用户自己的试题 则需要去获取他人BLOB内部的试题JSON文件
						if (tmdId !== this.curTeammodelId) {
							this.isFullList = 'true'
							let fullItemJson = await this.$evTools.getFullItemByTmdId(tmdId, item.link)
							this.questionList = [fullItemJson]
						} else {
							this.isFullList = null
							this.questionList = [{
								code: item.code,
								id: item.id,
								blob: item.link,
								scope: item.scope
							}]
						}
						this.$nextTick(() => {
							this.$refs.exList.collapseList = [0]
						})
						this.isPreviewPaper = true
						this.isLoading = false
						break;
					case 'paper':
						this.isLoading = true
						let paperTmdId = item.code.replace('Paper-', '')
						let fullPaper = null
						// 如果不是当前用户自己的试题 则需要去获取他人BLOB内部的试卷JSON文件
						if (paperTmdId !== this.curTeammodelId) {
							this.isFullList = 'true'
							fullPaper = await this.$evTools.getFullPaperByTmdId(paperTmdId, item.link)
						} else {
							this.isFullList = null
							let paper = {
								code: item.code,
								id: item.id,
								blob: item.link,
								scope: item.scope,
							}
							fullPaper = await this.$evTools.getFullPaper(paper)
						}
						this.previewPaper = fullPaper
						this.questionList = fullPaper.item
						this.$nextTick(() => {
							this.$refs.exList.collapseList = [...this.questionList.keys()]
						})
						this.isPreviewPaper = true
						this.isLoading = false
						break;
					case 'link':
						window.open(item.link);
						break;
					case 'other':
						this.$Message.warning(this.$t('syllabus.noPreview'))
						break;
					case 'doc':
						let copyLink = JSON.parse(JSON.stringify(item.link))
						let docSas = ''
						if (item.code !== this.curTeammodelId) {
							docSas = await this.$evTools.getBlobPrivateSas(item.code)
						} else {
							docSas = sasObj.sas
						}
						let fullLink = this.$evTools.getBlobHost() + '/' + item.cntr + item.link + docSas
						console.log(fullLink)
						if (this.getSuffix(item.title) === 'pdf') {
							this.openPdf(fullLink, item.title)
						} else {
							this.previewFile = JSON.parse(JSON.stringify(item))
							this.previewFile.link = escape(fullLink)
							this.previewStatus = true
						}
						break;
					default:
						let fileTmdId = item.code.replace('Item-', '')
						let sas = ''
						if (fileTmdId !== this.curTeammodelId) {
							sas = await this.$evTools.getBlobPrivateSas(fileTmdId)
						} else {
							sas = sasObj.sas
						}
						this.previewFile = JSON.parse(JSON.stringify(item))
						this.previewFile.link = this.$evTools.getBlobHost() + '/' + item.cntr + item.link + sas
						this.previewStatus = true
						break;
				}
			},
			/* 点击试卷列表预览试卷 */
			async onPreviewPaper(paper) {
				let fullPaper = await this.$evTools.getFullPaper(paper)
				this.previewPaper = fullPaper
				this.questionList = fullPaper.item
				this.isPreviewPaper = true
			},
			/* 打开PDF文件进行预览 */
			openPdf(url) {
				window.open('/web/viewer.html?file=' + encodeURIComponent(url));
			},
			/* 删除关联资源 */
			onDeleteResource(item, index) {
				this.$Modal.confirm({
					title: this.$t('settings.modalTip4'),
					content: this.$t('syllabus.removeConfirm'),
					onOk: () => {
						// 需要删除blob对应目录下的文件
						if (this.needDeleteFile(item)) {
							this.isLoading = true
							this.deleteBlobPrefix(item).then(r => {
								this.$Message.success(this.$t('evaluation.deleteSuc'))
								this.$refs.treeRef.curData.rnodes.splice(index, 1)
								this.hasModify = true
								this.modifyIdArr.push(this.curChapter.data.id)
								this.$refs.treeRef.curData.creatorId = this.curTeammodelId
								this.$refs.treeRef.curData.creatorName = this.curName
							}).catch(err => {
								this.$Message.error(err)
							}).finally(() => {
								this.isLoading = false
							})
						} else {
							this.$refs.treeRef.curData.rnodes.splice(index, 1)
							this.hasModify = true
							this.modifyIdArr.push(this.curChapter.data.id)
						}
					}
				})
			},
			/* 删除blob指定试题目录下所有 */
			deleteBlobPrefix(item) {
				return new Promise((resolve, reject) => {
					console.log(item);
					this.$api.blob.deletePrefix({
						"cntr": item.cntr,
						"prefix": item.link.substring(1)
					}).then(
						(res) => {
							if (!res.error) {
								resolve(200)
							} else {
								resolve(500)
							}
						},
						(err) => {
							reject(err)
						}
					)
				})
			},
			/* 提交新增册别 */
			handleSubmit() {
				return new Promise((r, j) => {
					this.isAddLoading = true
					let addVolumeParams = {
						"auth": this.addVolumeForm.auth.map(i => {
							return {
								tmdid: i,
								tmdname: this.teacherList.find(j => j.id === i).name
							}
						}),
						"code": this.curCode,
						"periodId": this.isSchool ? this.periodList[this.currentPeriodIndex].id : null,
						"subjectId": this.isSchool ? this.subjectList[this.activeSubjectIndex].id : null,
						"gradeId": this.isSchool ? this.addVolumeForm.grade : -1,
						"semesterId": this.isSchool ? this.semesterList[this.addVolumeForm.semester].id : null,
						"status": 1,
						"name": this.addVolumeForm.name || this.getDefaultVolumeName,
						"creatorId": this.curTeammodelId,
						"creatorName": this.curName,
						"school": this.isSchool ? this.$store.state.userInfo.schoolCode : '',
						"scope": this.curScope,
						"syllabusIds": []
					}
					if ((this.isEditVolume && this.curVolume)) {
						addVolumeParams.id = this.curVolume.id
						addVolumeParams.name = this.addVolumeForm.name
						addVolumeParams.syllabusIds = this.allChapterIds || []
						addVolumeParams.creatorId = this.curVolume.creatorId
						addVolumeParams.creatorName = this.curVolume.creatorName
					}
					if (this.isSaveSyllabus) {
						addVolumeParams = this.curVolume
						addVolumeParams.syllabusIds = this.allChapterIds || []
						this.isSaveSyllabus = false
					}
					// 发送新增或者编辑册别请求
					this.$api.syllabus.SaveOrUpdateVolume(addVolumeParams).then(res => {
						if (!res.error) {
							this.isAddVolumeModal = false
							this.$Message.success(this.$t('syllabus.doSuc'));
							this.getVolumeList(true)
							r(200)
						} else {
							this.$Message.warning(res.error === 4 ? this.$t('syllabus.isExistVolume') : res
								.error);
						}
					}).catch(err => {
						// this.$Message.error(err);
					}).finally(() => {
						this.isAddLoading = false
					})
				})

			},
			/* 获取整个树的章节与子节点归属 */
			getAllChild(arr) {
				let result = []
				arr.forEach(item => {
					result.push({
						chapterId: item.id,
						children: this.flatChildren(item.children)
					})
				})
				this.flatArr = result
			},
			/* 递归拉平所有children */
			flatChildren(children) {
				let result = []
				const fn = (source) => {
					source.forEach(i => {
						result.push(i.id)
						if (i.children.length) {
							fn(i.children)
						}
					})
				}
				fn(children)
				return result
			},
			/* 根据某个节点ID换取它对应的章节ID */
			getChapterIdById(id) {
				if (this.flatArr.map(i => i.chapterId).includes(id)) {
					return id
				} else {
					console.log(this.flatArr)
					console.log(id);
					let targetChapter = this.flatArr.find(i => i.children.includes(id))
					return targetChapter.chapterId
				}
			}
		},
		computed: {
			hasSchool() {
				return this.$store.state.userInfo.hasSchool;
			},
			curTeammodelId(){
				return this.$store.state.userInfo.TEAMModelId
			},
			curName(){
				return this.$store.state.userInfo.name
			},
			getDefaultVolumeName() {
				return this.hasSchool ? this.subjectList[this.activeSubjectIndex].name + this.gradeList[this.addVolumeForm.grade] + this
					.semesterList[this.addVolumeForm.semester].name : ''
			},
			getGradeName() {
				return index => {
					return this.periodList.length ? this.periodList[this.currentPeriodIndex].grades[index] : '0'
				}
			},
			getSemesterName() {
				return id => {
					if(this.periodList.length){
						let semesterItem = this.periodList[this.currentPeriodIndex].semesters.find(i => i.id === id)
						return semesterItem ? semesterItem.name : ''
					}else{
						return ''
					}
				}
			},
			curCode() {
				return this.isSchool ? this.$store.state.userInfo.schoolCode : this.curTeammodelId
			},
			curScope() {
				return this.isSchool ? "school" : "private"
			},
			getSuffix() {
				return name => {
					return name.substr(name.lastIndexOf(".") + 1)
				}
			},
			needDeleteFile() {
				return item => {
					return item.type !== 'item' && item.type !== 'paper' && item.type !== 'link'
				}
			},
			hasVolumeAuth(){
				return auth => {
					return (!this.isSchool && !this.inShareView) || this.$access.can('admin.*|syllabus-upd') || (auth && auth.length && auth.map(i => i.tmdid).includes(this.curTeammodelId))
				}
			},
			hasEditAuth() {
				return nodeData => {
					if (!nodeData.id) return false
					let userId = this.curTeammodelId
					// 判断是否为一级节点，如果是二级节点则需要拿对应的一级节点去做判断
					let chapterId = nodeData.pid === this.curVolume.id ? nodeData.id : this.getChapterIdById(nodeData
						.id)
					let chapterNode = this.treeOrigin.find(i => i.id === chapterId)
					return this.$access.can('admin.*|syllabus-upd') || this.curVolume.auth.map(i => i.tmdid).includes(userId) || (chapterNode.auth && chapterNode.auth.length &&
						chapterNode.auth.map(i => i.tmdid).includes(userId))
				}
			},
			// 是否可以操作课纲模块（个人课纲或者管理员或者有课纲权限）
			hasSyllabusAuth() {
				return !this.isSchool || this.$access.can('admin.*|syllabus-upd')
			},
			inShareView() {
				return !this.isSchool && this.activeTab === 'fromShare'
			}
		},
		// 路由离开生命周期函数
		beforeRouteLeave(to, from, next) {
			console.log(to);
			console.log(from);
			if (this.hasModify) {
				this.$Modal.confirm({
					title: this.$t('evaluation.newExercise.modalTip'),
					content: this.$t('syllabus.unSaveTip'),
					onOk: () => {
						next();
					}
				});
			}else{
				next();
			}
		},
		watch: {
			volumeList: {
				handler(n, o) {
					if (n.length === 0) {
						this.treeOrigin = []
						this.curNode = {
							id: '',
							rnodes: []
						}
					}
				},
				immediate: true
			}
		}
	}
</script>

<style lang="less" src="./Syllabus.less" scoped></style>
<style lang="less">
	.syllabus-header {
		.ivu-select-selection {
			width: 140px;
			// background-color: #252525e3 !important;
			border-radius: 0;
			// border-color: #96969640 !important;
			// color: #D0D0D0;
		}

		.ivu-select-dropdown {
			// background-color: #3c3c3c;

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

				&:hover {
					background-color: var(--hover-text-color);
				}
			}
		}
		.volume-list {
			.ivu-tooltip-inner{
				white-space: normal;
			}
		}

	}


	.syllabus-content-header {
		.ivu-input {
			// background-color: #262626;
			// border-color: #333;
			font-size: 12px;
			// color: #ddd;
		}
	}

	.tree-upload-modal {
		.ivu-modal-body {
			padding: 10px 40px;
		}

		.ivu-upload-drag {
			background: none;
			border-color: #8d8d8d;
		}

		.ivu-btn {
			height: 45px;
			margin: 20px auto;
		}
	}

	.tree-paper-modal {

		.ivu-modal-content {
			background-color: #fff;
		}

		.ivu-modal-body {
			overflow: auto;
			font-size: 14px !important;
			margin: 40px 10px;
		}

		.cp-exercise-item {
			border: 1px solid #dfdfdf !important;
		}

		.paper-box {
			display: flex;
			flex-direction: column;
			align-items: center;

			.paper-title {
				color: #333;
				font-size: 20px;
				font-weight: bold;
			}

			.paper-info {
				margin-top: 20px;
				color: #939393;
			}
		}
	}

	/* 修改iview Modal样式 */
	.add-volume-modal {
		font-family: 'NotoSerif', '微软正黑体', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Sans-serif;
	}

	.add-volume-modal .ivu-modal-content {
		// background: #3c3c3c;
		// color: #fff;
	}

	.add-volume-modal .ivu-modal-header {
		border-bottom: none;
		font-size: 16px;
		font-weight: bold;
		padding: 25px;

		.modal-header {
			display: inline-block;
		}

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

	.add-volume-modal .modal-content {
		padding: 10px 30px;
	}

	.form-container .ivu-form .ivu-form-item-label {
		// color: #fff;
		margin: 10px 0;
		font-weight: bold;
	}

	.form-container .ivu-input {
		// background: #575757;
		// border-color: transparent;
		height: 35px;
		color: var(--primary-text-color);
	}

	.form-container .ivu-input::-webkit-input-placeholder {
		color: #808080;
	}

	.form-container .ivu-select-selection {
		// background: #575757;
		color: var(--primary-text-color);
		// border-color: transparent;
		height: 35px;
	}

	.form-container .ivu-select-arrow {
		color: #fbfbfb;
	}

	.form-container .ivu-btn {
		width: 100%;
		height: 40px;
		margin-top: 20px;
		background: var(--assist-color-light);
		border: none;
		color: #fff;
	}

	.choose-content-modal {
		.ivu-modal-footer,.ivu-modal-body{
			// background-color: #444444;
		}
		.ev-list-container,
		.pl-container {
			height: 600px !important;
			overflow: auto;
			padding-right: 10px;
		}
		

		.modal-btn {
			width: 100%;
			margin: 20px 10px;
		}
	}
</style>
