import $api from '@/api'
import store from '@/store'
import $tools from './public.js'
import $editorTools from './editorTools.js'
import {
	Message,
	Modal
} from 'view-design'
import { app } from '@/boot-app.js'


export default {
	
	/* 根据登录后的用户信息获取blobHOST域名 */
	getBlobHost(){
		let s = store.state.user.userProfile.blob_uri || store.state.user.studentProfile.blob_uri || 'https://teammodelstorage.blob.core.chinacloudapi.cn/hbcn'
		return s.split(s.substring(s.lastIndexOf('/')))[0]
	},
	
	/* 获取试题保存在Blob的JSON文件 */
	createBlobItem(item){
		return new Promise((r,j) => {
			let itemJson = {
				id:item.id,
				pid:item.pid || null,
				exercise:{
					answer:item.answer,
					explain:item.explain,
					type:item.type,
					objective:this.getItemType(item.type),
					opts:item.option.length,
					knowledge:item.knowledge,
					field:item.field,
					level:item.level,
					periodId:item.periodId,
					gradeIds:item.gradeIds,
					subjectId:item.subjectId,
					children:item.children || [],
					scope:item.scope,
					score: item.score||0,
					blankCount: item.blankCount||1,
					repair:item.repair,
					createTime:new Date().getTime(),
					creator:store.state.userInfo.TEAMModelId || 'null'
				},
				item:[{
					type:'Html',
					uid:item.id,
					question:item.question,
					option:item.option
				}]
			}
			r(itemJson)
		})
	},
	
	/* 获取保存在COSMOS里面的试题格式 */
	createCosmosItem(item){
		return new Promise((r,j) => {
			let cosmosItem  = {
				id:item.id,
				pid:item.pid || null,
				code:item.code,
				scope:item.scope,
				score:item.score||0,
				type:item.type,
				objective:this.getItemType(item.type),
				question:this.getSimpleText(item.question),
				knowledge:item.knowledge,
				field:item.field,
				level:item.level,
				periodId:item.periodId,
				gradeIds:item.gradeIds,
				subjectId:item.subjectId,
				repair:item.repair,
				blankCount: item.blankCount || 1,
				blob:item.blob,
				createTime:new Date().getTime(),
				creator:store.state.userInfo.TEAMModelId || 'null'
			}
			r(cosmosItem)
		})
	},
	
	/* 生成试卷的index.json文件格式 */
	createBlobPaper(paper,slides){
		return new Promise((r,j) => {
			let paperItem  = {
				id:paper.id,
				name:paper.name,
				code:paper.code,
				scope:paper.scope,
				multipleRule:paper.multipleRule,
				slides:slides,
				points:paper.points,
				periodId:paper.periodId,
				gradeIds:paper.gradeIds,
				subjectId:paper.subjectId,
				subjectName:paper.subjectName,
				score:paper.score
			}
			r(paperItem)
		})
	},
	
	/* 生成试卷保存在cosmos的数据结构 */
	createCosmosPaper(paper){
		return new Promise((r,j) => {
			let paperItem  = {
				id:paper.id,
				name:paper.name,
				code:paper.code,
				blob:paper.blob,
				scope:paper.scope,
				scoring:paper.scoring,
				points:paper.points,
				periodId:paper.periodId,
				gradeIds:paper.gradeIds,
				subjectId:paper.subjectId,
				subjectName:paper.subjectName,
				score:paper.score,
				multipleRule:paper.multipleRule
			}
			r(paperItem)
		})
	},
	
	/* 获取完整的试题数据 */
	getFullItem(list,examScope){
		console.log('接受到的examScope',examScope)
		return new Promise(async (resolve,reject) => {
			if(list.length === 0) return
			let promiseArr = []
			console.log('getFullITEM接收到的list')
			console.log(list)
			for(let i=0; i<list.length; i++){
				promiseArr.push(new Promise(async (r,j) => {
					if(list[i].blob){
						let curScope = list[i].scope
						const blobHost = curScope === 'school' ?  JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri :  JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8")).blob_uri
						// 根据试题的Blob地址 去读取JSON文件
						let sasString = curScope === 'school' ?  await $tools.getSchoolSas() : await $tools.getPrivateSas()
						let jsonInfo = list[i].blob.includes('https://') ? await $tools.getFile(list[i].blob + sasString.sas) : await $tools.getFile(blobHost + list[i].blob + sasString.sas)
						let jsonData = JSON.parse(jsonInfo)
						// 如果是综合题 那就拿到children里面的小题id集合 去换取小题的blobJSON文件 然后替换children的内容
						if(jsonData.exercise.children.length && jsonData.exercise.type === 'compose'){
							let childrenUrls = jsonData.exercise.children.map(i => blobHost + '/item/' + i + '/' + i + '.json' + sasString.sas)
							jsonData.exercise.children = await this.getFullChildren(childrenUrls,list[i].code)
						}
						// 调整渲染试题数据结构
						jsonData.id = list[i].id
						jsonData.exercise.question = jsonData.item[0].question
						jsonData.exercise.createTime = list[i].createTime || 0
						jsonData.exercise.blob = list[i].blob
						jsonData.exercise.code = list[i].code
						jsonData.exercise.option = jsonData.item[0].option
						jsonData.exercise.id = list[i].id
						jsonData.exercise.pid = jsonData.pid
						jsonData.exercise = await this.doAddHost(jsonData.exercise)
						r(jsonData.exercise)
					}else{
						r(null)
					}
				}))
			}
			Promise.all(promiseArr).then(result => {
				console.log('从Blob获取来的试题',result)
				resolve(result)
			}).catch(err => {
				Message.error(app.$t('utils.fileReadFail'))
				reject(err)
			})
		})
	},
	
	/* 给富文本添加 */
	doAddHost(exerciseItem,paperItem){
		/* 如果操作的是试卷内的试题 则需要拿试卷的code来作为containerName */
		let curScope = paperItem ? paperItem.scope : exerciseItem.scope
		let container = curScope === 'school' ? store.state.userInfo.schoolCode : store.state.userInfo.TEAMModelId
		let isSubjective = exerciseItem.type === 'complete' || exerciseItem.type === 'subjective' || exerciseItem.type === 'compose'
		let richTextObj = {
			question: exerciseItem.question,
			answer: Array.isArray(exerciseItem.answer) && exerciseItem.answer.length ? exerciseItem.answer[0] : exerciseItem.answer,
			explain: exerciseItem.explain,
		}
		isSubjective && delete richTextObj.answer
		return new Promise((resolve, reject) => {
			let promiseArr = []
			// 遍历题目的所有富文本内容
			for (let key in richTextObj) {
				promiseArr.push(new Promise(async (r, j) => {
					let videoSrcList = $editorTools.getRichTextSrc(richTextObj[key],'video')
					let audioSrcList = $editorTools.getRichTextSrc(richTextObj[key],'audio')
					let srcList = videoSrcList.concat(audioSrcList)
					if(srcList.length){
						console.log('要添加list',srcList)
						for(let i = 0;i<srcList.length;i++){
							let src = srcList[i]
							/* 如果是来自试卷的题目 则需要匹配试卷HOST */
							if(paperItem && paperItem.examId){
								let examContainer = paperItem.examId
								let blobUrl = this.getBlobHost() +  '/' + examContainer  + paperItem.blob +  '/' + src
								try{
									let addSasUrl = await $tools.getFileSas(blobUrl)
									richTextObj[key] = richTextObj[key].replace(`src="${ src }"`, `src="${ addSasUrl.url }"`);
								}catch(e){
									j(500)
								}
							}else if(paperItem){
								let blobUrl = this.getBlobHost() +  '/'  + container + '/paper/' + paperItem.name + '/' + src
								try{
									let addSasUrl = await $tools.getFileSas(blobUrl)
									richTextObj[key] = richTextObj[key].replace(`src="${ src }"`, `src="${ addSasUrl.url }"`);
								}catch(e){
									j(500)
								}
							}else{
								let blobUrl = this.getBlobHost() +  '/'  + container + '/item/' + exerciseItem.id + '/' + src
								try{
									let addSasUrl = await $tools.getFileSas(blobUrl)
									richTextObj[key] = richTextObj[key].replace(`src="${ src }"`, `src="${ addSasUrl.url }"`);
								}catch(e){
									j(500)
								}
								
							}
						}
						if(key === 'answer' && Array.isArray(exerciseItem.answer) && exerciseItem.answer.length){
							exerciseItem.answer[0] = richTextObj[key]
						}else{
							exerciseItem[key] = richTextObj[key]
						}
						r(200)
					}else{
						r(200)
					}
				}))
			}
			Promise.all(promiseArr).then(result => {
				//console.log('添加HOST之后的',exerciseItem)
				resolve(exerciseItem)
			}).catch(e => {
				reject(e)
			})
		})
	},
	
	/* 保存综合题小题 */
	saveChildren(children,containerClient){
		return new Promise((resolve,reject) => {
			let promiseArr = []
			let itemJsonFiles = []
			children.forEach(exerciseItem => {
				promiseArr.push(new Promise(async (r,j) => {
					// 将当前的试题数据转化为BLOB内部的试题JSON格式
					const itemJsonFile = await this.createBlobItem(exerciseItem)
					const cosmosItem = await this.createCosmosItem(exerciseItem)
					// 首先保存新题目的JSON文件到Blob 然后返回URL链接
					let file = new File([JSON.stringify(itemJsonFile)], exerciseItem.id + ".json");
					try{
						// 等待上传blob的返回结果
						let blobFile = await containerClient.upload(file, 'item/' + exerciseItem.id)
						if (blobFile.blob) {
							// 保存试题JSON文件到试卷文件夹需要
							itemJsonFiles.push(file)
							// 保存到COSMOS是不含base64图片编码的数据 避免数据量过大
							cosmosItem.blob = blobFile.blob
							// 保存当前试题到数据库
							that.saveExercise(cosmosItem).then(res => {
								r(res.itemInfo)
							})
						}else{
							j(500)
						}
					}catch(e){
						j(500)
					}
				}))
			})
			Promise.all(promiseArr).then(result => {
				if(result.length){
					resolve(itemJsonFiles)
				}else{
					resolve([])
				}
			})
			
		})
		
	},
	
	/* 获取综合题子题的Blob数据 */
	getFullChildren(urls,code){
		return new Promise((resolve,reject) => {
			let promiseArr = []
			urls.forEach(url => {
				promiseArr.push(new Promise(async (r,j) => {
					let jsonData = JSON.parse(await $tools.getFile(url))
					// 调整渲染试题数据结构
					jsonData.exercise.question = jsonData.item[0].question
					jsonData.exercise.blob = url
					jsonData.exercise.code = code
					jsonData.exercise.option = jsonData.item[0].option
					jsonData.exercise.id = jsonData.id
					jsonData.exercise.pid = jsonData.pid
					r(jsonData.exercise)
				}))
			})
			
			Promise.all(promiseArr).then(result => {
				if(result.length){
					resolve(result)
				}else{
					resolve([])
				}
			})
		})
	},
	
	/* 获取完整的试卷数据 */
	getFullPaper(paper,examScope){
		console.log(paper)
		console.log(examScope)
		let curScope = examScope || paper.examScope || paper.scope
		return new Promise(async (r,j) => {
			let blobHost = curScope === 'school' ?  JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri :  JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8")).blob_uri
			// 根据试卷的Blob地址 去读取JSON文件
			let sasString = curScope === 'school' ?  await $tools.getSchoolSas() : await $tools.getPrivateSas()
			try{
				let jsonInfo = await $tools.getFile(blobHost + paper.blob + '/index.json' + sasString.sas)
				let jsonData = JSON.parse(jsonInfo)
				// 获取试卷包含的试题数据并包装好
				if(jsonData.slides && jsonData.slides.length){
					let promiseArr = []
					let allItems = []
					jsonData.item = []
					const path = blobHost + paper.blob
					jsonData.slides.forEach(async (item,index) => {
						promiseArr.push(new Promise(async (resolve,reject) => {
							try{
								// 获取题目JSON并且包装成完整试题对象
								let itemJson = JSON.parse(await $tools.getFile(path + '/' + item.url + sasString.sas))
								itemJson.exercise.question = itemJson.item[0].question
								itemJson.exercise.option = itemJson.item[0].option
								itemJson.exercise.id = itemJson.id 
								itemJson.exercise.pid = itemJson.pid 
								itemJson.exercise.blob = path + '/' + item.url // 添加blob是方便在保存试卷是 refresh 与导入的试题区分开
								itemJson.exercise.score = item.scoring ? item.scoring.score : 0
								try{
									// if(paper.examId){
									// 	itemJson.exercise = await this.doAddHost(itemJson.exercise,paper) // 检测试题中的富文本 为有src为相对路径的音视频文件添加blob的HOST地址
									// }else{
									// 	itemJson.exercise = await this.doAddHost(itemJson.exercise,paper) // 检测试题中的富文本 为有src为相对路径的音视频文件添加blob的HOST地址
									// }
									itemJson.exercise = await this.doAddHost(itemJson.exercise,paper) // 检测试题中的富文本 为有src为相对路径的音视频文件添加blob的HOST地址
									resolve(itemJson.exercise)
								}catch(e){
									reject(e)
								}
							}catch(e){
								reject(e)
							}
						}))
					})
					
					Promise.all(promiseArr).then(res => {
						res.forEach((resItem,resIndex) => {
							resItem.children = []
							if(resItem.pid){
								let pItem = res.filter(i => i.id === resItem.pid)[0]
								pItem.children.push(resItem)
								pItem.score = pItem.score + resItem.score
							}
						})
						jsonData.item = res.filter(i => !i.pid)
						r(jsonData)
					}).catch(e => {
						// Message.error('试卷文件读取失败')
						j(e)
					})
				}
			}catch(e){
				j(e)
			}
		})
	},
	
	
	/* 获取完整的试卷数据 */
	getStuPaper(paper, examScope) {
		let curScope = examScope || paper.scope
		return new Promise(async (r,j) => {
			let blobHost = JSON.parse(decodeURIComponent(localStorage.student_profile, "utf-8")).blob_uri
			let splitHost = blobHost.split('/')
			// 根据试卷的Blob地址 去读取JSON文件
			let sasString = curScope === 'school' ? await $tools.getSchoolSas(paper.code) : await $tools.getPrivateSas(paper.code)
			try {
				let jsonInfo = await $tools.getFile(sasString.url + '/' + paper.code + paper.blob + '/index.json' + sasString.sas)
				let jsonData = JSON.parse(jsonInfo)
				// 获取试卷包含的试题数据并包装好
				if (jsonData.slides && jsonData.slides.length) {
					jsonData.item = []
					const path = sasString.url + '/' + paper.code + paper.blob
					let promiseArr = []
					jsonData.slides.forEach((item, index) => {
						promiseArr.push(new Promise(async (resolve, reject) => {
							// 获取题目JSON并且包装成完整试题对象
							let itemJson = JSON.parse(await $tools.getFile(path + '/' + item.url + sasString.sas))
							itemJson.exercise.question = itemJson.item[0].question
							itemJson.exercise.option = itemJson.item[0].option
							itemJson.exercise.id = itemJson.id 
							itemJson.exercise.pid = itemJson.pid 
							itemJson.exercise.score = item.scoring ? item.scoring.score : 0
							// jsonData.item.push(itemJson.exercise)
							try{
								itemJson.exercise = await this.doAddHost(itemJson.exercise,paper)
								resolve(itemJson.exercise)
							}catch(e){
								reject(e)
							}
						}))
					})
					Promise.all(promiseArr).then(res => {
						res.forEach((resItem,resIndex) => {
							resItem.children = []
							if(resItem.pid){
								let pItem = res.filter(i => i.id === resItem.pid)[0]
								pItem.children.push(resItem)
								pItem.score = pItem.score + resItem.score
							}
						})
						jsonData.item = res.filter(i => !i.pid)
						r(jsonData)
					}).catch(e => {
						j(e)
					})
				}
			}catch(e){
				j(e)
			}
		})
	},
	/* 获取完整的试卷数据 */
	getComposeItem(paper) {
		return new Promise(async (r, j) => {
			// 根据试卷的Blob地址 去读取JSON文件
			let sasString = paper.scope === 'school' ? await $tools.getSchoolSas(paper.code) : await $tools.getPrivateSas(paper.code)
			try {
				let jsonInfo = await $tools.getFile(paper.blob + sasString.sas)
				let jsonData = JSON.parse(jsonInfo)
				// 获取试卷包含的试题数据并包装好
				if (jsonData.length) {
					r(jsonData)
				}
			} catch (e) {
				j(e)
			}
		})
	},
	
	// 提取富文本内容中的文本
	getSimpleText(html) {
		var r = /<\/?(img)[^>]*>/gi;
		return html.replace(r, "");
	},
	
	getItemType(type){
		const objective = ['single','multiple','judge']
		return objective.includes(type)
	},
	
	getImgSrc(richtext) {
	    let imgList = [];
	    richtext.replace(/<video [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
	          imgList.push(capture);
	    });
	    return imgList;
	}
}
