<template>
    <div class="cp-import-container">
            <div v-if="!isImportFinish" style="padding:40px 0;height:100%">
                <Upload multiple
						:disabled="isBtnLoading"
                        :action="uploadUrl"
                        :headers="headers"
                        :format="['docx','xlsx','xls']"
                        :on-format-error="handleFormatError"
						:on-error="onUploadError"
                        :show-upload-list="isShowList"
                        :before-upload="beforeUpload"
                        :on-success="uploadSuccess">
                        <Icon type="md-cloud-upload" size="150" color="#ffffff" style="margin: 30px 0;"/>
                    <div v-show="isBtnLoading" class="import-loading-wrap">
                        <img src="@/assets/loading/loading.svg" width="100px" />
						<p style="color: #fff;">{{ $t('http.loading')}}</p>
                    </div>
                </Upload>
				<div class="import-tips">
					<div style="display: flex;margin-bottom: 20px;justify-content: space-around;">
						<Dropdown @on-click="onTemplateSelect">
						        <Button type="primary">
									<Icon type="md-cloud-download"  style="margin-right: 5px;"/>
						            Word {{$t('evaluation.importFile.templateDownload')}}
						            <Icon type="ios-arrow-down"></Icon>
						        </Button>
						        <DropdownMenu slot="list">
						            <DropdownItem :name="0">中文简体(zh-CN)</DropdownItem>
						            <DropdownItem :name="1">中文繁体(zh-TW)</DropdownItem>
						            <DropdownItem :name="2">英文(en-US)</DropdownItem>
						        </DropdownMenu>
						</Dropdown>
						<Dropdown @on-click="onTemplateSelect" style="margin-left: 15px;">
						        <Button type="primary">
									<Icon type="md-cloud-download"  style="margin-right: 5px;"/>
						            Excel {{$t('evaluation.importFile.templateDownload')}}
						            <Icon type="ios-arrow-down"></Icon>
						        </Button>
						        <DropdownMenu slot="list">
						            <DropdownItem :name="3">中文简体(zh-CN)</DropdownItem>
						        </DropdownMenu>
						</Dropdown>
						<Button type="primary" icon="md-cloud-download" style="margin-left: 15px;" @click="onDownloadDetails">{{$t('evaluation.importFile.downloadDetails')}}</Button>	
					</div>
					
					<p style="font-size:18px;font-weight:bold;color: #fff;">{{$t('evaluation.importFile.importTips')}}</p>
					<p>1.{{$t('evaluation.importFile.tips1')}}</p>
					<p>2.{{$t('evaluation.importFile.tips2')}}</p>
					<p>3.{{$t('evaluation.importFile.tips3')}}</p>
					<p>4.{{$t('evaluation.importFile.tips4')}}</p>
					<p>5.{{$t('evaluation.importFile.tips5')}}</a></p>
				</div>
            </div>
			
			<!-- 添加小题弹窗 -->
			<Modal v-model="errorModal" width="800" class="bmf-error-modal" :ok-text="$t('evaluation.reImport')" :cancel-text="$t('evaluation.continueImport')" @on-ok="onErrorOk" @on-cancel="onErrorCancel">
				<div class="modal-header" slot="header">{{ $t('evaluation.imgError') }}</div>
				<p class="error-title">{{ $t('evaluation.imgErr1') }} <mark>{{ errorList.length }}</mark> {{ $t('evaluation.imgErr2') }}<mark> {{ $t('evaluation.imgErr3') }} </mark>{{ $t('evaluation.imgErr4') }}<mark> {{ $t('evaluation.imgErr5') }} </mark>？</p>
				<div class="error-item-list">
					<p v-for="(item,index) in errorList" :key="index" v-html="item" class="error-item"></p>
				</div>
			</Modal>
    </div>
</template>
<script>
	import excel from '@/utils/excel.js'
	import FileSaver from "file-saver";
    export default {
        props: ['period', 'subject'],
        data() {
            return {
				curLang:'',
				errorList:[],
				importList:[],
				errorModal:false,
                isBtnLoading: false,
                isSelectFinish: false,
                importLoading: false,
                isImportFinish: false,
                isShowList: true,
                exerciseList: [],
                importPreviewModal: false,
                uploadUrl: '',
				downloadUrls:[{
					url:'/download/%E9%A2%98%E7%9B%AE%E6%A8%A1%E6%9D%BF%E7%AE%80%E4%BD%93.docx',
					fileName:'题目模板（简体）.docx'
				},{
					url:'/download/%E9%A2%98%E7%9B%AE%E6%A8%A1%E6%9D%BF%E7%B9%81%E4%BD%93.docx',
					fileName:'題目範本（繁体）.docx'
				},{
					url:'/download/%E9%A2%98%E7%9B%AE%E6%A8%A1%E6%9D%BF%E8%8B%B1%E8%AF%AD.docx',
					fileName:'題目範本（英语）.docx'
				},{
					url:'/download/%E9%A2%98%E7%9B%AE%E6%A8%A1%E6%9D%BF.xls',
					fileName:'題目範本.xls'
				}],
				hostName:'',
				fieldArr:['記憶记忆1','理解2','應用应用3','分析4','评价評鑒5','创造創造6']
            }
        },
        created() {
            this.uploadUrl = window.location.origin  + '/import/parse-docx'
			this.curLang = localStorage.getItem('local')
			this.hostName = this.$store.state.privateSas ? this.$store.state.privateSas.url : 'https://teammodelstorage.blob.core.chinacloudapi.cn'
        },
        methods: {

            /** 点击导入习题 */
            handleUpload() {
                this.importPreviewModal = true
                this.exerciseList = []
                this.isImportFinish = false
            },
			
			/* 下载模板 */
			async onTemplateSelect(val){
				let curFile = this.downloadUrls[val]
				const downloadRes = async () => {
				      let response = await fetch(this.hostName + curFile.url); // 内容转变成blob地址
				      let blob = await response.blob();  // 创建隐藏的可下载链接
				      let objectUrl = window.URL.createObjectURL(blob);
				      let a = document.createElement('a');
				      a.href = objectUrl;
				      a.download = curFile.fileName;
				      a.click()
				      a.remove(); 
				   }
				  downloadRes();
			},
			
			/* 下载模板制作详情说明文件 */
			onDownloadDetails(){
				const downloadRes = async () => {
				      let response = await fetch(this.hostName + '/download/IES5%E8%AF%95%E5%8D%B7%E6%A8%A1%E6%9D%BF%E5%88%B6%E4%BD%9C%E8%AF%B4%E6%98%8E%EF%BC%88%E7%BB%88%EF%BC%89.pdf'); // 内容转变成blob地址
				      let blob = await response.blob();  // 创建隐藏的可下载链接
				      let objectUrl = window.URL.createObjectURL(blob);
				      let a = document.createElement('a');
				      a.href = objectUrl;
				      a.download = 'IES5试卷导入模板制作说明.pdf';
				      a.click()
				      a.remove(); 
				   }
				  downloadRes();
			},

            importModalChange(val) {
                if (!val) {
                    this.isImportFinish = false
                    this.isSelectFinish = false
                    this.isBtnLoading = false
                    this.importLoading = false
                    this.exerciseList = []
                }
            },

            /** 重新导入文件 */
            onReImport() {
                this.isImportFinish = false
                this.isSelectFinish = false
                this.exerciseList = []
            },

            /** 选择文件上传之前 */
            beforeUpload(file) {
				this.isBtnLoading = true
				this.isSelectFinish = true
				// 如果是excel格式文档 则需要进行对应解析
				if(this.isExcel(file)){
					let excelResult = []
					this.readExcel(file,data => {
						if(data.results.length){
							data.results.forEach(item => {
								excelResult.push({
									question:item.Question || '',
									answer:item.Answer ? [item.Answer] : [],
									knowledge:item.Concept ? item.Concept.split(',') : [],
									field:this.getItemField(item),
									score:item.Point || 0,
									type:item.Type,
									children:[],
									option:this.getItemOptions(item)
								})
							})
							this.$Message.success(this.$t('evaluation.importFile.warningTips3'))
							this.$emit('importFinish',excelResult)
							this.isImportFinish = false
							this.isBtnLoading = false
							this.exerciseList = []
						}
					})
					return false
				}
            },

			
			/* 获取表格解析试题的选项 */
			getItemOptions(item){
				let options = []
				let optionIndex = 0
				if(item.Type === 'judge'){
					return [{
						code:'A',
						value:'对'
					},{
						code:'B',
						value:'错'
					}]
				}else{
					for(let key in item){
						if(key.includes('Option')){
							options.push({
								code: String.fromCharCode(64 + parseInt(optionIndex + 1)),
								value:item[key]
							})
							optionIndex++
						}
					}
					return options
				}
				
				
			},
			
			/* 获取表格解析试题的认知层次 */
			getItemField(item){
				for (let i in this.fieldArr) {
					if(this.fieldArr[i].includes(item.Edu_Goal)){
						return + i + 1
						break
					}
				}
			},
			
			
			/* 判断上传的是否为excel表格文件 */
			isExcel(file){
				let  fileType = file.name.split('.')[file.name.split('.').length - 1]
				return  fileType === 'xlsx' || fileType === 'xls'
			},
			
			/* 解析excel表格 */
			readExcel(file, callback) {
			    var reader = new FileReader();
			    reader.onload = function (e) {
			        var data = e.target.result;
			        var workbook = excel.read(data, 'binary');                
			        if (callback) callback(workbook);
			    };
			    reader.readAsBinaryString(file);
			},

            /**
             * 当上传文件格式错误
             * @param
             */
            handleFormatError() {
                this.$Message.error(this.$t('evaluation.importFile.warningTips1'))
                this.isBtnLoading = false
				this.isSelectFinish = false
            },

            /**
             * 当上传文件超过限制大小
             * @param file
             */
            handleMaxSize() {
                this.$Message.error(this.$t('evaluation.importFile.warningTips2'))
                this.isBtnLoading = false
				this.isSelectFinish = false
            },
			
			/* 有异常图片情况下选择重新导入模板 */
			onErrorOk(){
				this.$Message.warning(this.$t('evaluation.reImportTip'))
				this.isImportFinish = false
				this.isBtnLoading = false
				this.errorList = []
				this.importList = []
				this.exerciseList = []
			},
			
			/* 有异常图片情况下选择继续预览 */
			onErrorCancel(){
				this.$Message.success(this.$t('evaluation.importFile.warningTips3'))
				this.$emit('importFinish',this.importList)
				this.isImportFinish = false
				this.isBtnLoading = false
				this.exerciseList = []
				this.errorList = []
				this.importList = []
			},
			
			/* 上传异常处理 */
			onUploadError(e){
				this.$Message.error(this.$t('evaluation.importFile.warningTips4'))
				this.isBtnLoading = false
			},

            /**
             * 上传文件成功回调
             * @param response
             */
            uploadSuccess(res) {
				// 匹配模板文档中的数学公式
				var regex = /(\<math.*?<\/math\>)/g;
				var html = res.html
				var arr = html.match(regex);
				if(arr && Array.isArray(arr) && arr.length){
					// 对所有的mathml进行转换成svg操作
					arr.forEach(math => {
						let svgHtml = window.MathJax.mathml2svg(math, { em: 12, ex: 6 })
						var regex2 = /\<svg .*\>.*\<\/svg\>/;
						var arr2 = svgHtml.outerHTML.match(regex2);
						html = html.replace(math, `<span>&nbsp;</span>${arr2[0]}<span>&nbsp;</span>`)
					})
				}
				// 解析成题目列表
				this.$api.SaveAnalyzeHtml({ html : html }).then(response => {
					if(response.tests.length && !response.emferror.length){
						this.$emit('importFinish',response.tests)
						this.isImportFinish = false
						this.isBtnLoading = false
						this.exerciseList = []
					}else if(response.emferror.length){
						this.errorModal = true
						this.importList = response.tests
						this.errorList = response.emferror
						this.isImportFinish = false
						this.isBtnLoading = false
					}else{
						this.$Message.error(this.$t('evaluation.importFile.warningTips4'))
						this.isBtnLoading = false
					}
					this.isSelectFinish = false
				}).catch(e => {
					console.log(e)
				})
            },
        },
        computed: {
            headers() {
                let hd = {}
                hd['Authorization'] = 'Bearer ' + localStorage.getItem('token')
                return hd
            }

        }
    }
</script>

<style scoped lang="less">
	@import "../index/CommonExercise.less";
</style>

<style lang="less">
	.cp-import-container{
		background: #404040;
		height: 100%;
	}
	
	.bmf-error-modal{
		.error-title{
			margin: 15px 15px 0 15px;
			letter-spacing: 1px;
			font-size: 16px;
			font-weight: bold;
		}
		
		mark{
			color: red;
		}
		
		.error-item-list{
			max-height: 500px;
			overflow-y:scroll;
			padding: 15px;
			
			.error-item{
				margin-top: 20px;
				background: #efefef;
				padding: 10px;
			}
		}
	}
	
    .cp-import-container,
    .cp-import-container .ivu-upload {
		display: flex;
		justify-content: center;
		align-items: center;
		
		.ivu-upload-list{
			display: none;
		}
		
		.ivu-icon{
			cursor: pointer;
		}
		
		.ivu-btn-primary{
			background-color: #00756f;
			border: none;
		}
    }

        .cp-import-container .ivu-upload-drag {
            padding-top:8%;
            background:#2e2e2e;
            border: 1px dashed #626365;
            color: #b8b8b8;
            font-size: 16px;
        }

    .cp-import-container .ivu-modal-body,
    .edit-exercise-modal .ivu-modal-body {
        max-height: 700px;
        overflow: auto;
        padding: 0;
    }


    .cp-import-container .item-explain-details {
        width: 94%;
    }

    .cp-import-container .ivu-modal {
        max-height: 600px;
        position: relative;
    }

    .import-tips {
        padding: 20px 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #b8b8b8;
    }

        .import-tips p {
            margin: 5px;
        }

    .cp-import-container .exercise-item:not(:first-child) {
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #DEDEDE;
    }

    .cp-import-container .exercise-item .btn-edit-exercise {
        display: none;
    }

    .cp-import-container .exercise-item:hover .btn-edit-exercise {
        display: unset;
    }


    .cp-import-container .import-loading-wrap {
        position: absolute;
		margin-top: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }

</style>
