<template>
	<div class="ability-mgmt-container">
		<Loading v-if="isLoading" hideMask></Loading>
		<div class="ability-mgmt-header">
			<div class="period-select">
				<span style="margin-left: 10px;">编号查询：</span>
				<Select ref="periodSelect" v-model="curNoIndex" @on-change="onNoChange" style="width: 200px;">
					<Option v-for="(item, index) in noArr" :value="index" :key="index">{{ item }}</Option>
				</Select>
				
				<Button style="margin-left: 10px;" @click="isShowPaper = !isShowPaper" v-if="volumeList.length">{{ isShowPaper ? '查看章节目录' : '查看检测试卷'}}</Button>
				<!-- <div class="subject-select">
					<span v-for="(item,index) in dimensionList" :key="index" :class="[
					  'subject-select-item',
					  index == activeSubjectIndex ? 'item-active' : '',
					]" @click="onPeriodChange(item.code,index)">{{ item.val }}</span>
				</div> -->
			</div>
			<Button @click="onSaveSyllabus" class="btn-save-modify" icon="md-folder"
				v-if="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') }}-->
							微能力点 （{{ volumeList.length }}）
						</span>
						<span class="syllabus-content-header-tools">
							<Icon type="md-search" :title="$t('syllabus.search')" @click="doSearchVolume"
								v-if="volumeList.length" />
							<!-- <Icon type="ios-paper" title="查看检测试卷" @click="onShowPaper"
								v-if="volumeList.length" />	 -->
							<Icon type="md-create" :title="$t('syllabus.edit')" @click="doEditVolume"
								v-if="!inSchoolAbility" />
							<!-- <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="输入能力点名称..." 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">
								<span>
									<span class="status-idDel">{{ volume.no }}</span>
									{{ volume.name }}
									<span class="status-idDel status-compulsory" v-if="volume.compulsory">必修</span>
								</span>
								<span style="float: right;font-size: 12px;color: #858585;"></span>
							</p>
							<p class="volume-item-info" v-if="isSchool">
								<span>学时：{{ volume.hour }}</span>
								<span>|</span>
								<span>能力点数：{{ volume.abilityCount }}</span>
								<span style="margin: 0 5px;">|</span>
								<span>维度：{{ getName(volume.dimension) }}</span>
							</p>

						</div>
					</div>
				</vuescroll>
			</div>
			
			<div class="syllabus-paper" v-show="isShowPaper">
				<div class="syllabus-content-header">
					<!--<span>{{ $t('syllabus.syllabusMenu') }}</span>-->
					自我检测试卷
					<span class="syllabus-content-header-tools"
						v-if="volumeList.length && curVolume.id && !inShareView &&  !inSchoolAbility">
						<span style="margin-right: 20px;font-weight: 400;font-size: 12px;cursor: pointer;" @click="isShowPaper = false"><Icon type="md-reorder" size="16" style="margin-right: 5px;"/>切换到章节视图</span>
						<Dropdown @on-click="onAddQues" style="font-weight: 400;">
							<a href="javascript:void(0)" style="color: #6b6b6b;font-size: 12px;">
								<Icon type="md-add" size="14" style="margin-right: 0;"></Icon>
								新增试题
								<Icon type="ios-arrow-down"></Icon>
							</a>
							<DropdownMenu slot="list">
								<DropdownItem name="single" style="color: #6b6b6b;font-size: 12px !important;">+单选题</DropdownItem>
								<DropdownItem name="multiple" style="color: #6b6b6b;font-size: 12px !important;">+多选题</DropdownItem>
								<DropdownItem name="judge" style="color: #6b6b6b;font-size: 12px !important;">+判断题</DropdownItem>
								<DropdownItem name="import" style="color: #6b6b6b;font-size: 12px !important;">+导入试题</DropdownItem>
							</DropdownMenu>
						</Dropdown>
						<!-- <Icon type="md-add" @click="isAddTreeModal = true" v-if="hasSyllabusAuth || hasVolumeAuth(curVolume.auth)" /> -->
					</span>
				</div>
				<div>
					<TestPaper isNewPaper :abilityData="curVolume" ref="testPaper"></TestPaper>
				</div>
			</div>
			
			<div class="syllabus-mid" v-show="!isShowPaper">
				<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" @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" v-show="!isShowPaper">
				<div class="syllabus-content-header">
					<!--<span>{{ $t('syllabus.relate') }}</span>-->
					关联资源（{{ curNode.rnodes.length }}）
					<span class="syllabus-content-header-tools" v-if="!inSchoolAbility">
						<!-- <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" v-if="curNode.id">
							<a href="javascript:void(0)" style="color: #6b6b6b;">
								{{ $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">
							<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;"
								@click="onPreview(item)"></span>
							<div class="node-resource-tools"  v-if="$access.can('area.*')">
								<!-- <div class="node-resource-tool" >
									<Icon type="md-eye" />
									<span>{{ $t('syllabus.preview') }}</span>
								</div> -->
								<div class="node-resource-tool" @click="onDeleteResource(item,index)" >
									<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>
			<AbilityUpload :auth="curSas" :scope="curScope" mode="modal" :prefix="curPrefix" @uploadFinish="uploadFinish">
			</AbilityUpload>
		</Modal>

		<!-- 新增册别弹窗 -->
		<Modal v-model="isAddVolumeModal" width="600" footer-hide class="add-volume-modal">
			<div class="modal-header" slot="header">
				{{ isEditVolume ? '编辑微能力点' : '新增微能力点' }}
			</div>
			<div class="modal-content">
				<div class="ability-form-container">
					<Form :model="addVolumeForm" label-position="top" :rules="ruleValidate" ref="addForm">
						<FormItem label="编号" prop="no">
							<Input v-model="addVolumeForm.no" placeholder="填写微能力点编号..." disabled></Input>
						</FormItem>
						<FormItem label="名称" prop="name">
							<Input v-model="addVolumeForm.name" placeholder="填写微能力点名称..." disabled></Input>
						</FormItem>
						<FormItem label="描述" prop="desc">
							<Input v-model="addVolumeForm.desc" placeholder="填写微能力点描述信息..."></Input>
						</FormItem>
						<FormItem label="环境" prop="env">
							<Input v-model="addVolumeForm.env" placeholder="填写微能力点环境..."></Input>
						</FormItem>
						<FormItem label="建议" prop="sug">
							<Input v-model="addVolumeForm.sug" placeholder="填写微能力点名称..."></Input>
						</FormItem>
						<FormItem label="选修/必修" prop="compulsory">
							<i-switch size="large" v-model="addVolumeForm.compulsory">
								<span slot="open">必修</span>
								<span slot="close">选修</span>
							</i-switch>
						</FormItem>
						<FormItem label="总学时" prop="hour">
							<InputNumber :max="100" :min="1" v-model="addVolumeForm.hour"></InputNumber>
						</FormItem>
						<FormItem label="能力点数" prop="abilityCount">
							<InputNumber :max="100" :min="1" v-model="addVolumeForm.abilityCount"></InputNumber>
						</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.addTitle') }}</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.nodeName') }}</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="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>

		<!--文件预览-->
		<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" autoplay 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'
	import TestPaper from '@/view/ability/TestPaper.vue'
	export default {
		components: {
			Tree,
			InviteTeacher,
			ChooseContent,
			ExerciseList,
			TestPaper
		},
		data() {
			return {
				isShowPaper:false,
				noArr: [],
				curNoIndex: 0,
				curPrefix: '',
				curDimensionCode: '2438e72f-4de8-4ccb-8cae-3f1dce89a769',
				dimensionList: this.$GLOBAL.DIMENSIONS(),
				ruleValidate: {
					no: [{
						required: true,
						message: '编号不能为空',
						trigger: 'blur'
					}],
					name: [{
						required: true,
						message: '名称不能为空',
						trigger: 'blur'
					}]
				},
				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: [],
					no: '',
					hour: 1,
					abilityCount: 1,
					compulsory: false,
					desc: '',
					env: '',
					sug: ''
				},
				nodeInfo: {
					"id": "",
					"pid": "",
					"title": "",
					"creatorId": this.curTeammodelId,
					"creatorName": this.curName,
					"type": 1,
					"children": [],
					"rnodes": []
				},
				modifyIdArr: [],
				flatArr: [],
				myCreateChapters: [],
				isSaveSyllabus: false,
			}
		},
		created() {
			this.isSchool = true
			this.initBlobTool()
			if (this.hasSchool) {
				this.getSchoolInfo()
				this.getAllTeacher()
			} else {
				this.getVolumeList()
			}

			let judgeJson = require('@/static/judge.json')
			let copyArr = JSON.parse(JSON.stringify(judgeJson))
		},
		methods: {
			getName(code) {
				return this.$GLOBAL.DIMENSIONS().find(i => i.code === code).val
			},
			
			onAddQues(val){
				this.$refs.testPaper.onChooseType(val)
			},
			
			onShowPaper(){
				this.isShowPaper = true
			},
			
			/* 初始化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, index) {
				this.activeSubjectIndex = index
				this.curDimensionCode = val
				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)
			},

			onNoChange(val) {
				if (val === 0) {
					this.volumeList = this.originVolumeList
				} else {
					this.volumeList = this.originVolumeList.filter(i => i.no === this.noArr[val])
				}
				this.onVolumeClick(this.volumeList[0], 0, true)
			},

			/* 获取册别列表 */
			getVolumeList(needRefresh) {
				this.isLoading = true
				this.treeOrigin = []
				this.curNode = {
					id: '',
					rnodes: []
				}
				let findParams = {
					"scope": "school",
					"code": this.$store.state.userInfo.schoolCode,
					"dimension": "",
					"status": 1
				}
				// 查找列表
				this.$api.ability.FindVolumes(findParams).then(res => {
					if (!res.error) {
						this.isLoading = false
						this.noArr = res.abilities.map(i => i.no).sort()
						this.volumeList = res.abilities.sort(function(s, t) {
							var a = s.no.toLowerCase();
							var b = t.no.toLowerCase();
							if (a.length === 2) {
								a = a.slice(0, a.length - 1) + '0' + a.slice(-1)
							}
							if (b.length === 2) {
								b = b.slice(0, b.length - 1) + '0' + b.slice(-1)
							}

							if (a < b) return -1;
							if (a > b) return 1;
							return 0;
						});

						this.noArr.sort(function(s, t) {
							var a = s.toLowerCase();
							var b = t.toLowerCase();
							if (a.length === 2) {
								a = a.slice(0, a.length - 1) + '0' + a.slice(-1)
							}
							if (b.length === 2) {
								b = b.slice(0, b.length - 1) + '0' + b.slice(-1)
							}

							if (a < b) return -1;
							if (a > b) return 1;
							return 0;
						});
						this.noArr.unshift('全部')
						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.abilities.length && this.onVolumeClick(res.abilities[activeIndex], activeIndex,
							needRefresh)
					} else {
						this.isLoading = false
						this.$Message.warning(res.error);
					}
				}).catch(err => {
					this.isLoading = false
					// 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)
							}
						})
					}
				})
			},
			/* 点击某个册别 */
			async onVolumeClick(volume, volumeIndex, needRefresh) {
				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() {
				this.addVolumeForm = {
					grade: 0,
					semester: 0,
					name: '',
					auth: [],
					no: '',
					hour: 1,
					abilityCount: 1,
					compulsory:false,
					desc: '',
					env: '',
					sug: ''
				}
				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 = JSON.parse(JSON.stringify(this.curVolume))
				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.ability.DeleteVolume({
								id: curVolume.id,
								code: curVolume.code.replace('Ability-', ''),
								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.$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(`/yxpt/${this.curStandard}/jyzx/`))
					if (syllabusLinks.length) {
						this.$api.ability.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: 'teammodelos',
										title: i.replace(`/yxpt/${this.curStandard}/jyzx/`, '')
									}))
								})
								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.ability.GetTreeByVolume({
					"abilityId": volume.id,
					"abilityCode": volume.code,
					"scope": "school"
				}).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(noLoading) {
				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.$store.state.userInfo.schoolCode,
						abilityId: 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.ability.UpsertTree(modifyChapters).then((res) => {
					if (!res.error && res) {
						this.hasModify = false;
						this.$refs.treeRef && (this.$refs.treeRef.modifyIdArr = [])
						this.$Message.success(this.$t('syllabus.doSuc'));
						!noLoading && this.getVolumeList(true)
						// // 然后保存册别的章节ID集合
						// 	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()
					let s = this.$store.state.user.osblob_uri
					this.curSas = {
						sas: '?' + this.$store.state.user.osblob_sas,
						name: 'teammodelos',
						url: s.split(s.substring(s.lastIndexOf('/')))[0]
					}
					this.isUploadModal = true
					this.curPrefix = this.curNode.id
					console.log(this.curPrefix)
				} 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: `/yxpt/${this.curStandard}/jyzx/${this.curNode.id}/${file.name}`,
						title: file.name,
						type: file.type,
						cntr: 'teammodelos'
					})
				})
				this.modifyIdArr.push(this.curChapter.data.id)
				this.hasModify = true
				this.isUploadModal = false
				// this.$Message.success(this.$t('syllabus.uploadSuc'))
				this.onSaveSyllabus(true)
				console.log(result)
			},
			/* 获取关联的内容数据，需要进行相应的文件拷贝 */
			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/' + 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: `/jyzx/${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) {
				return new Promise(async (r, j) => {
					pItem = await this.$editorTools.doRemoveMideaHost(pItem)
					console.log(pItem)
					let path = 'item/' + 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 = privateToSchool ? schoolBlobTool : privateBlobTool
					let fromClient = privateToSchool ? privateBlobTool : schoolBlobTool
					const itemJsonFile = await this.$evTools.createBlobItem(pItem);
					let file = new File([JSON.stringify(itemJsonFile)], pItem.id + ".json", {
						type: "",
					});
					// 先把对应试题目录下的全部复制到校本BLOB 然后再更新添加学段科目等字段后的题目Json文件
					toClient.copyFolder(path, path.slice(0, path.length - 1), fromClient).then(async res => {
						try {
							let blobFile = await toClient.upload(file, "item/" + pItem.id);
							if (blobFile.blob) {
								this.saveExercise(pItem).then(result => {
									console.log(result)
									r(result)
								})
							}
						} catch (e) {
							j(e)
						}
					}).catch(err => {
						j(err)
					})
				})
			},


			/* 获取关联的试题数据 */
			onSelectQuestion(val) {
				return new Promise((r, j) => {
					let exRef = this.$refs.chooseContentRef.$refs.exListRef
					let list = exRef ? exRef.selectItems : []
					console.log('xxxxx', list)
					if (!list.length) {
						r(200)
					} else {
						let curResourceArr = this.$refs.treeRef.curData.rnodes
						// 拿到关联的个人试题和校本试题
						let privateItems = list.filter(i => i.scope === 'private')
						let schoolItems = list.filter(i => i.scope === 'school')
						// 如果是在校本课纲关联的个人试题 则需要进行入库操作
						if (this.isSchool && privateItems.length) {
							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))
							})
							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: i.blob
										})
									}
								})
								r(200)
							}).catch(err => {
								this.$Message.error(err)
							})
						} else if (!this.isSchool && schoolItems.length) {
							let promiseArr = []
							// 个人试题入库前需要补充必要的学段科目年级信息
							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))
							})
							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: i.blob
										})
									}
								})
								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)
						}
					}
				})


			},
			/* 判断试卷名称是否已存在校本库中 */
			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 = 'paper/' + paper.name + '/'
					let privateSas = await this.$tools.getPrivateSas()
					let privareBlobTool = new BlobTool(privateSas.url, privateSas.name, privateSas.sas,
						'private')
					let file = new File([JSON.stringify(paper)], "index.json", {
						type: "",
					});
					// 先把对应试题目录下的全部复制到校本BLOB 然后再更新添加学段科目等字段后的题目Json文件
					this.containerClient.copyFolder(path, path.slice(0, path.length - 1), privareBlobTool)
						.then(async res => {
							try {
								let blobFile = await this.containerClient.upload(file, "paper/" + paper
									.name);
								if (blobFile.blob) {
									this.savePaperToCosmos(paper, scoring, isUpdate).then(result => {
										console.log(result)
										r(result)
									})
								}
							} catch (e) {
								j(e)
							}
						}).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()
						// 如果是在校本课纲关联的个人试卷 则需要进行入库操作
						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.$store.state.userInfo
												.schoolCode,
											scope: 'school',
											cntr: this.$store.state.userInfo
												.schoolCode,
											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.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
						break;
					case 'paper':
						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
						break;
					case 'link':
						window.open(item.link);
						break;
					case 'other':
						this.$Message.warning(this.$t('syllabus.noPreview'))
						break;
					case 'doc':
					    let userProfile2 = JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8"))
						let copyLink = JSON.parse(JSON.stringify(item.link))
						let docSas = '?' + userProfile2.osblob_sas
						// if (item.code !== this.curTeammodelId) {
						// 	docSas = await this.$evTools.getBlobPrivateSas(item.code)
						// } else {
						// 	docSas = sasObj.sas
						// }
						let fullLink = userProfile2.osblob_uri  + 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 userProfile = JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8"))
						let fileTmdId = item.code.replace('Item-', '')
						let sas = '?' + userProfile.osblob_sas
						// if (fileTmdId !== this.curTeammodelId) {
						// 	sas = '?' + this.$store.state.user.osblob_sas
						// } else {
						// 	sas = sasObj.sas
						// }
						this.previewFile = JSON.parse(JSON.stringify(item))
						this.previewFile.link = userProfile.osblob_uri  + 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) {
				console.log(item)
				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
								this.onSaveSyllabus(true)
							}).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) => {
					this.$api.blob.deletePrefix({
						"cntr": 'teammodelos',
						"prefix": item.link.substring(1)
					}).then(
						(res) => {
							if (!res.error) {
								resolve(200)
							} else {
								resolve(500)
							}
						},
						(err) => {
							reject(err)
						}
					)
				})
			},
			/* 提交新增册别 */
			handleSubmit() {
				return new Promise((r, j) => {
					console.log(this.curVolume);
					this.$refs.addForm.validate((valid) => {
						if (valid) {
							console.log(this.addVolumeForm);
							this.isAddLoading = true
							let addVolumeParams = {
								"code": this.$store.state.userInfo.schoolCode,
								"no": this.addVolumeForm.no,
								"hour": this.addVolumeForm.hour,
								"abilityCount": this.addVolumeForm.abilityCount,
								"status": 1,
								"name": this.addVolumeForm.name,
								"desc": this.addVolumeForm.desc,
								"env": this.addVolumeForm.env,
								"sug": this.addVolumeForm.sug,
								"compulsory": this.addVolumeForm.compulsory,
								"dimension": this.curDimensionCode,
								"creatorId": this.$store.state.userInfo.TEAMModelId,
								"creatorName": this.$store.state.userInfo.name,
								"school": this.$store.state.userInfo.schoolCode,
								"scope": "school"
							}
							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
							}
							addVolumeParams.stds = this.curVolume.stds
							addVolumeParams.blob = this.curVolume.blob
							addVolumeParams.comid = this.curVolume.comid
							addVolumeParams.standard = this.curVolume.standard
							// 发送新增或者编辑册别请求
							this.$api.ability.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
							})
						} else {
							this.$Message.error('请将信息填写完整！');
						}
					})
				})
			},
			/* 获取整个树的章节与子节点归属 */
			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
				}
			}
		},
		mounted() {
			console.log(this.curStandard);
		},
		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('area.*|Syllabus_Edit') || (
						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('area.*|Syllabus_Edit') || 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('area.*|Syllabus_Edit')
			},
			inShareView() {
				return !this.isSchool && this.activeTab === 'fromShare'
			},
			curStandard(){
				return this.$store.state.user.schoolProfile.school_base.standard
			},
			inSchoolAbility(){
				return this.$route.name === 'abilityMgmt'
			},
			isAreaAbility(){
				return this.$route.name === 'areaAbilityMgmt'
			}
		},
		watch: {
			volumeList: {
				handler(n, o) {
					if (n.length === 0) {
						this.treeOrigin = []
						this.curNode = {
							id: '',
							rnodes: []
						}
					}
				},
				immediate: true
			}
		}
	}
</script>

<style lang="less" src="./Index.less" scoped></style>
<style lang="less">
	.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;
			}
		}
	}

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

	.choose-content-modal {

		.ev-list-container,
		.pl-container {
			height: 600px !important;
			overflow: auto;
			padding-right: 10px;
		}

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