<template>
	<div class="review-container">
		<Spin size="large" fix v-if="isLoading"></Spin>
		<div class="review-header">
			<div class="review-title">
				<Icon type="md-arrow-back" @click="goBack" />
				<span>{{ data.targetName }} 【 {{ data.no}} {{ data.name }} 】</span>
			</div>
			<div class="ability-des">
				<p>{{ data.desc }}</p>
			</div>
		</div>
		<div class="unit-list">
			<div class="unit-item" v-for="(std,index) in data.stds" :key="index">
				<p class="unit-item-name">{{ index + 1 }}.{{ std.std }}</p>
				<span class="task-radio-group" v-if="std.task.length > 1 && mode === 'self'">
					<span v-for="(radio,radioIndex) in std.task" :class="[curTaskIndexArr[index] === radioIndex ? 'active' : '']" @click="onChangeTask(radioIndex,index)">任务 {{ radioIndex + 1 }}</span>
				</span>
				<div class="task-item" v-for="(task,taskIndex) in std.task" :key="taskIndex">
					<div v-if="curTaskIndexArr[index] === taskIndex">
						<p class="unit-item-des">{{ task.stddesc }}</p>
						<!-- 上传按钮 -->
						<div class="task-upload">
							<Button type="info" icon="md-cloud-upload" class="upload-btn" @click="onUpload(std,index)" v-show="!stdFileArr[index].length && mode === 'self'">上传资料</Button>
						</div>
						<!-- 文件清单 -->
						<div class="unit-item-files">
							<div class="unit-file-item" v-for="(file,fileIndex) in stdFileArr[index]" :key="fileIndex">
								<img :src="getTypeIcon(file)" width="30">
								<div class="file-info">
									<span class="file-name">{{ file.name }}</span>
									<span class="file-size">{{ getSizeByBytes(file.size) }}</span>
								</div>
								<div class="file-action">
									<span @click="onPreview(file)">预览</span>
									<span @click="onDownload(file)">下载</span>
									<span @click="onDelete(file,fileIndex,index)" v-if="mode === 'self'">删除</span>
								</div>
							</div>
						</div>
						<p class="appraise-title"><span style="font-size: 16px;font-weight: bold;">{{ mode === 'self' ? '请自我评价' : '请评价'}}</span> (请勾选下方评分项进行评价)</p>
						<div class="unit-item-appraise">
							<!-- 优秀 -->
							<div class="appraise-block" v-if="task.titles.length">
								<p class="title">
									<Icon type="ios-square-outline" size="18" @click="onCheckAll(index,'1',task.titles)" v-if="appraiseResultArr[index] !== 'good'"/>
									<Icon type="ios-checkbox" size="20" color="#2d8cf0" @click="onCheckAll(index,'1',task.titles)" v-if="appraiseResultArr[index] === 'good'"/>
									优秀
								</p>
								<CheckboxGroup v-model="appraiseList[index]" @on-change="onCheckChange(index,'1',task.titles)">
									<Checkbox 
									v-for="(point,pointIndex) in task.titles.filter(i => i.value === '1')" 
									:key="pointIndex" 
									:label="point.id">{{ point.title }}</Checkbox>
								</CheckboxGroup>
							</div>
							<!-- 合格 -->
							<div class="appraise-block" v-if="task.titles.length">
								<p class="title">
									<Icon type="ios-square-outline" size="18" @click="onCheckAll(index,'2',task.titles)" v-if="!isAllNormalArr[index]"/>
									<Icon type="ios-checkbox" size="20" color="#2d8cf0" @click="onCheckAll(index,'2',task.titles)" v-if="isAllNormalArr[index]"/>
									合格</p>
								<CheckboxGroup v-model="appraiseList[index]" @on-change="onCheckChange(index,'2',task.titles)">
									<Checkbox 
									v-for="(point,pointIndex) in task.titles.filter(i => i.value === '2')" 
									:key="pointIndex" 
									:label="point.id">{{ point.title }}</Checkbox>
								</CheckboxGroup>
							</div>
							<div v-if="!task.titles.length">
								<RadioGroup type="button" v-model="appraiseResultArr[index]" @on-change="getFinalResult()">
									<Radio label="good" border>优秀</Radio>
									<Radio label="normal" border>合格</Radio>
									<Radio label="bad" border>不合格</Radio>
								</RadioGroup>
							</div>
						</div>
						<div class="appraise-result">
							<span>评价结果：</span>
							<span class="good" v-if="appraiseResultArr[index] === 'good'"><Icon type="md-happy" size="22" />优秀</span>
							<span class="normal" v-else-if="appraiseResultArr[index] === 'normal'">合格</span>
							<span class="bad" v-else><Icon type="md-sad" size="22"/>不合格</span>
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<div style="margin-left: 40px;margin-bottom: 20px;">
			<p style="margin: 5px;margin-bottom: 20px;">总评价结果:
				<span class="good" v-if="finalResult === 2"><Icon type="md-happy" size="22" />优秀</span>
				<span class="normal" v-else-if="finalResult === 1">合格</span>
				<span class="bad" v-else><Icon type="md-sad" size="22"/>不合格</span>
			</p>
			<Input v-model="appraiseContent" type="textarea" :rows="4" placeholder="输入评价内容..." v-if="mode !== 'self'"/>
		</div>
		<!--文件预览-->
		<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>
		
		<Button type="success" size="large" :loading="isBtnLoading" icon="ios-paper-plane" @click="onSubmit">提交评审结果</Button>
		
		<!--上传文件-->
		<Modal v-model="uploadModal" width="800" footer-hide class="add-volume-modal">
			<div class="modal-header" slot="header">
				<span>{{ $t('syllabus.upload') }}</span>
			</div>
			<AbilityUpload :auth="curSas" :acceptTypes="['doc','docx','xls','xlsx','ppt','pptx','mp4','jpg','png','pdf','mp3','wav']" :scope="'school'" mode="modal" :prefix="curPrefix" @uploadFinish="uploadFinish"></AbilityUpload>
		</Modal>
	</div>
</template>

<script>
	export default {
		props: {
			mode:{
				type:String,
				default:'self'
			},
			reviewData:{
				type:Object,
				default:() => {
					id:''
				}
			}
		},
		data() {
			return {
				finalResult:0,
				isBtnLoading:false,
				curPrefix:'',
				appraiseContent:'',
				curTaskIndexArr:[],
				previewStatus:false,
				isLoading:false,
				indeterminate: true,
				checkAll: false,
				previewFile:null,
				checkAllGroup: [],
				fileArr:[],
				appraiseResultArr:[],
				appraiseList:[],
				isAllNormalArr:[],
				uploadModal:false,
				stdFileArr:[],
				curUploadIndex:0,
				curSas: {
					sas: '',
					url: '',
					name: ''
				},
				data:{
					name:''
				},
			}
		},
		methods: {
			goBack() {
				this.$emit('goBack')
			},
			/* 切换任务 */
			onChangeTask(taskIndex,stdIndex){
				this.$set(this.curTaskIndexArr,stdIndex,taskIndex)
				this.appraiseList[stdIndex] = []
				this.appraiseResultArr[stdIndex] = 'bad'
				this.isAllNormalArr[stdIndex] = false
				this.fileArr[stdIndex] = []
			},
			/* 转换size */
			getSizeByBytes(bytes) {
			    return bytes / 1024 < 1024 ? (bytes / 1024).toFixed(1) + 'KB' : bytes / 1024 / 1024 < 1024 ? (bytes / 1024 / 1024).toFixed(1) + 'M' : (bytes / 1024 / 1024 / 1024).toFixed(1) + 'G'
			},
			/* 提交评审 */
			onSubmit(){
				this.isBtnLoading = true
				console.log(this.finalUpload)
				console.log(this.appraiseResultArr)
				console.log(this.appraiseResultArr.every(i => i === 'good') ? 2 : (this.appraiseResultArr.every(i => i !== 'bad') ? 1 : 0))
				if(this.finalUpload.some(i => i.urls.length === 0)){
					this.$Message.warning('存在未提交资料的任务！')
					this.isBtnLoading = false
				}else if(this.mode === 'self' && this.finalResult === 0){
					this.$Message.warning('当前自评结果为不合格，无法提交！请修改自评结果！')
					this.isBtnLoading = false
				}else{
					let appraiseParams = {
						"tmdid": this.$store.state.userInfo.TEAMModelId,
						"abilityId": this.reviewData.id,
						"school": this.$store.state.userInfo.schoolCode,
						"opt": "Upload",
						"self": this.finalResult,
						"uploads": this.finalUpload
					}
					// 如果不是自评的话
					if(this.mode !== 'self'){
						appraiseParams.tmdid = this.data.targetId
						appraiseParams.opt = "YouRateSomone"
						appraiseParams.otherScore = {
							roleType:this.mode === 'school' ? 'school' : 'member',
							tmdid:this.$store.state.userInfo.TEAMModelId,
							tmdname:this.$store.state.userInfo.name,
							atTmdname:this.data.targetName,
							score:this.finalResult,
							reply: this.appraiseContent,
							scoreUploads:this.finalOtherResult
						}
						delete appraiseParams.upload
					}
					this.$api.jyzx.pointAction(appraiseParams).then(res => {
						this.isBtnLoading = false
						this.goBack()
						this.$Message.success('提交成功！')
					})
				}
				
			},
			/* 执行上传操作 */
			async onUpload(std,index){
				this.uploadModal = true
				this.curUploadIndex = index
				this.curSas = await this.$tools.getSchoolSas()
				this.curPrefix = this.$store.state.userInfo.TEAMModelId + '/' + std.id
			},
			/* 上传结束回调 */
			uploadFinish(res){
				this.$set(this.stdFileArr,this.curUploadIndex,this.stdFileArr[this.curUploadIndex].concat(res))
				this.uploadModal = false
				console.log(this.stdFileArr)
			},
			/* 预览文件 */
			async onPreview(file){
				this.curSas = await this.$tools.getSchoolSas()
				let fullFilePath = file.url + this.curSas.sas
				let suffix = this.getSuffix(file.name)
				console.log(file)
				console.log(fullFilePath)
				let isImg = ['jpg','png'].includes(suffix)
				let isDoc = ['doc','docx','xls','xlsx','ppt','pptx'].includes(suffix)
				let isPdf = suffix === 'pdf'
				let isVideo = suffix === 'mp4'
				let isAudio = ['mp3','wav'].includes(suffix)
				let type = isImg ? 'image' : isVideo ? 'video' : isAudio ? 'audio' : 'doc'
				switch (type) {
					case 'doc':
						if(isPdf){
							this.openPdf(fullFilePath, file.name)
						}else{
							this.previewFile = JSON.parse(JSON.stringify(file))
							this.previewFile.link = escape(fullFilePath)
							this.previewStatus = true
						}
						break;
					default:
						this.previewFile = JSON.parse(JSON.stringify(file))
						this.previewFile.link = fullFilePath
						this.previewFile.type = type
						this.previewStatus = true
						break;
				}
			},
			/* 获取文件后缀名 */
			getSuffix(name) {
				return name.substr(name.lastIndexOf(".") + 1).toLowerCase()
			},
			/* 打开PDF文件进行预览 */
			openPdf(url) {
				window.open('/web/viewer.html?file=' + encodeURIComponent(url));
			},
			/* 下载文件 */
			async onDownload(file){
				this.isLoading = true
				this.curSas = await this.$tools.getSchoolSas()
				let fullFilePath = file.url + this.curSas.sas
				/* 下载模板制作详情说明文件 */
				const downloadRes = async () => {
				  let response = await fetch(fullFilePath); // 内容转变成blob地址
				  let blob = await response.blob();  // 创建隐藏的可下载链接
				  let objectUrl = window.URL.createObjectURL(blob);
				  let a = document.createElement('a');
				  a.href = objectUrl;
				  a.download = file.name;
				  a.click()
				  a.remove(); 
				  this.isLoading = false
			   }
			  downloadRes();
			},
			/* 删除文件 */
			onDelete(file,index,stdIndex){
				console.log(file);
				this.isLoading = true
				this.deleteBlobPrefix(file.blob).then(r => {
					setTimeout(() => {
						this.$Message.success('删除成功！')
						this.stdFileArr[stdIndex].splice(index,1)
						this.isLoading = false
					},1000)
				}).catch(err => {
					this.$Message.error(err)
				}).finally(() => {
					// this.isLoading = false
				})
			},
			/* 删除blob指定试题目录下所有 */
			deleteBlobPrefix(prefix) {
				return new Promise((resolve, reject) => {
					this.$api.blob.deletePrefix({
						"cntr": this.$store.state.userInfo.schoolCode,
						"prefix": prefix.substring(1)
					}).then(
						(res) => {
							if (!res.error) {
								resolve(200)
							} else {
								resolve(500)
							}
						},
						(err) => {
							reject(err)
						}
					)
				})
			},
			/* 评价结果 */
			onCheckChange(stdIndex,type,allIds){
				let curStdChooseIds = this.appraiseList[stdIndex]
				let allGoodIds = allIds.filter(j => j.value === '1').map(k => k.id)
				let allNormalIds = allIds.filter(j => j.value === '2').map(k => k.id)
				// 优秀的判断就是所有优秀的评价ID都在选择内
				let isAllGood = allGoodIds.every(i => curStdChooseIds.includes(i))
				let isAllNormal = allNormalIds.every(i => curStdChooseIds.includes(i))
				// 未通过的判断就是当前未选择任何标准
				let isAllBad = curStdChooseIds.length === 0
				// 其余则为合格
				this.appraiseResultArr[stdIndex] = isAllGood ? 'good' : isAllNormal ? 'normal' : 'bad'
				this.isAllNormalArr[stdIndex] = !isAllGood && allNormalIds.every(i => curStdChooseIds.includes(i))
				this.getFinalResult()
			},
			/* 全选操作 */
			onCheckAll(stdIndex,type,allIds){
				let curStdChooseIds = this.appraiseList[stdIndex]
				let allGoodIds = allIds.filter(j => j.value === '1').map(k => k.id)
				let allNormalIds = allIds.filter(j => j.value === '2').map(k => k.id)
				let isAllGood = allGoodIds.every(i => curStdChooseIds.includes(i))
				if(type === '1'){
					if(this.appraiseResultArr[stdIndex] === 'good'){
						this.$set(this.appraiseList,stdIndex,this.appraiseList[stdIndex].filter(i => !allGoodIds.includes(i)))
						this.appraiseResultArr[stdIndex] = allNormalIds.every(i => curStdChooseIds.includes(i)) ? 'normal' : 'bad'
					}else{
						let addGoodIdsRes = [...new Set(this.appraiseList[stdIndex].concat(allGoodIds))]
						this.$set(this.appraiseList,stdIndex,addGoodIdsRes)
						this.appraiseResultArr[stdIndex] ='good'
					}
				}else{
					// 如果合格 点击全选时 处于已全选状态 则设置为全空
					 if(allNormalIds.every(i => curStdChooseIds.includes(i))){
						this.$set(this.appraiseList,stdIndex,this.appraiseList[stdIndex].filter(i => !allNormalIds.includes(i)))
						this.isAllNormalArr[stdIndex] = false
						if(this.appraiseList[stdIndex].length === 0 || !allGoodIds.every(i => curStdChooseIds.includes(i))){
							this.appraiseResultArr[stdIndex] ='bad'
						}
						
					}else{
						// 如果合格 点击全选时 处于未全选状态 则设置为全选
						let addNormalIdsRes = [...new Set(this.appraiseList[stdIndex].concat(allNormalIds))]
						this.$set(this.appraiseList,stdIndex,addNormalIdsRes)
						this.isAllNormalArr[stdIndex] = true
						if(!allGoodIds.every(i => curStdChooseIds.includes(i))){
							this.appraiseResultArr[stdIndex] ='normal'
						}else{
							this.appraiseResultArr[stdIndex] ='good'
						}
					}
				}
				this.getFinalResult()
				
				// this.isAllNormal = !isAllGood && allNormalIds.every(i => curStdChooseIds.includes(i))
				console.log(this.appraiseList[stdIndex]);
			},
			/* 获取能力点详情 */
			async getDetailById(id){
				let abilityDetail = await this.$evTools.getAbilityDetailById(id)
				console.log(abilityDetail)
				this.appraiseResultArr = abilityDetail.stds.map(i => 'bad')
				this.appraiseList = abilityDetail.stds.map(i => [])
				this.isAllNormalArr = abilityDetail.stds.map(i => false)
				this.stdFileArr = abilityDetail.stds.map(i => [])
				this.curTaskIndexArr = abilityDetail.stds.map(i => 0)
				abilityDetail.uploads = this.reviewData.uploads
				console.log(abilityDetail.uploads)
				if(this.mode !== 'self'){
					this.stdFileArr = abilityDetail.uploads.map(i => i.urls)
					abilityDetail.targetId = this.reviewData.targetId
					abilityDetail.targetName = this.reviewData.targetName
				}
				return abilityDetail
			},
			/* 根据类型换取ICON图标 */
			getTypeIcon(file){
				let suffix = file.name.split('.')[file.name.split('.').length - 1].toLowerCase()
				if(['jpg','png'].includes(suffix)){
					return require('../../assets/icon/pic50.png')
				}
				if(['doc','docx'].includes(suffix)){
					return require('../../assets/icon/word50.png')
				}
				if(['xls','xlsx'].includes(suffix)){
					return require('../../assets/icon/xls50.png')
				}
				if(['ppt','pptx'].includes(suffix)){
					return require('../../assets/icon/ppt50.png')
				}
				if(suffix === 'pdf'){
					return require('../../assets/icon/pdf50.png')
				}
				if(['mp3','wav'].includes(suffix)){
					return require('../../assets/icon/video50.png')
				}
				if(['mp4'].includes(suffix)){
					return require('../../assets/icon/video50.png')
				}
			},
			
			getFinalResult(){
				this.finalResult = this.appraiseResultArr.every(i => i === 'good') ? 2 : this.appraiseResultArr.some(i => i === 'bad') ? 0 : 1
				console.log(this.finalResult)
			}
			
		},
		computed:{
			finalUpload(){
				return this.stdFileArr.map((i,stdIndex) => {
					return {
						"stdid": this.data.stds[stdIndex].id,
						"taskid": this.data.stds[stdIndex].task[0].id,
						"urls": i.map(j => {
							return {
								url:j.url,
								name:j.name,
								size:j.size
							}
						}),
						"titleIds":this.appraiseList[stdIndex]
					}
				})
			},
			finalOtherResult(){
				return this.stdFileArr.map((i,stdIndex) => {
					return {
						"stdid": this.data.stds[stdIndex].id,
						"taskid": this.data.stds[stdIndex].task[0].id,
						"score": this.appraiseResultArr[stdIndex] === 'good' ? 2 : this.appraiseResultArr[stdIndex] === 'normal' ? 1 : 0,
						"titleIds":this.appraiseList[stdIndex]
					}
				})
			}
		},
		watch:{
			reviewData:{
				async handler(n,o){
					if(n){
						this.data = await this.getDetailById(n.id)
						console.log(this.data)
					}
				},
				immediate:true,
				deep:true
			}
		}
	}
</script>

<style lang="less" src="./Review.less" scoped></style>
<style lang="less">
	
	.ivu-spin-fix{
		background-color: rgba(255,255,255,.6) !important;
	}
	
	/* 修改iview Modal样式 */
	.add-volume-modal {
		font-family: 'NotoSerif', '微软正黑体', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Sans-serif;
	}
	
	
	.add-volume-modal .ivu-modal-header {
		border-bottom: none;
		font-size: 18px;
		font-weight: bold;
		padding: 25px;
	
		.modal-header {
			display: inline-block;
		}
	
		&::before {
			content: '';
			display: inline-block;
			border: 4px solid #2e97ff;
			border-radius: 50%;
			margin-right: 10px;
			margin-bottom: 2px;
		}
	}
	
	.add-volume-modal .modal-content {
		padding: 10px 30px;
	}
</style>
