<style>
	#import-header {
		position: relative;
		background-color: #3ed798;
		color: white;
		height: 80px;
		padding: 0 30px;
		line-height: 80px;
	}
	
	#import-header>img {
		height: 34px;
		margin-right: 10px;
		position: relative;
		top: 10px;
	}
	
	#import-header #exit-btn {
		position: absolute;
		top: 0;
		right: 0;
		border: none;
		width: 60px;
		height: 36px;
		background: url('../assets/images/btn_closed.png') no-repeat center;
		background-size: cover;
		outline: none;
	}
	
	#import-header #exit-btn:hover {
		background: url('../assets/images/btn_closed_hover.png') no-repeat center;
	}
	
	#import-body {
		position: absolute;
		top: 80px;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		flex-direction: column;
	}
	
	#import-body #import-div {
		text-align: center;
		padding: 20px 0;
	}
	
	#import-body #import-div #import-btn {
		width: 316px;
		height: 70px;
		border-radius: 35px;
		border: none;
		font-size: 30px;
	}
	
	#import-body #progress-div {
		flex-grow: 1;
		display: flex;
		flex-direction: column;
		padding: 30px 50px;
	}
	
	#import-body #progress-div #console-panel {
		flex-grow: 1;
		background-color: #e3e3e3;
		overflow: auto;
	}
	
	#import-body #progress-div #console-panel .console-line {
		font-size: 14px;
		text-align: center;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	#import-body #progress-div #console-panel .console-line>span {
		margin: 0 10px;
	}
	
	#import-body #progress-div #console-panel .console-line>span.red {
		color: #fc7156;
	}
	
	#import-body #progress-div #console-panel .console-line>span.green {
		color: #3ed798;
	}
	.file {
	    position: relative;
	    display: inline-block;
	    border-radius: 4px;
	    padding: 4px 12px;
	    overflow: hidden;
	    color: white;
	    text-decoration: none;
	    text-indent: 0;
	    line-height: 20px;
	}
	.file input {
	    position: absolute;
	    font-size: 100px;
	    right: 0;
	    top: 0;
	    opacity: 0;
	}
	.file:hover {
	    color: #004974;
	    text-decoration: none;
    }
</style>
<template>
	<div style='height: 100%;'>
		<div id='import-header'>
			<img src='../assets/images/nav_images.png' alt=''>照片批量上传工具
			<button id='exit-btn' @click='logout'></button>
		</div>
		<div id='import-body'>
			<div id='import-div'>
	            <a href='javascript:;' class='file'>
	            	<!--webkitdirectory-->
	            	<input id='photos' :disabled='uploadDisabled' multiple="true" title=' ' name='files' type='file'  v-on:change='importPhotos'/>
	            	<button  id='import-btn'>
		                {{btnText}}
		            </button>
	            </a>
	            <button class='form-control' style='width: 40%;margin:auto;font-size:20px;'>
	                <span>成功:{{successNum}}/{{allNum}}</span>
	                <span>失败:{{errorNum}}/{{allNum}}</span>
	                <!--<span>处理进度:{{completeProportion}}</span>-->
	            </button>
			</div>
			<div id='progress-div'>
				<div>

				</div>
				<div id='console-panel'>
					<div v-for='msgInfo in returnMsgList'>
						<p class='console-line' v-if='msgInfo.success'>
							<span><img src='../assets/images/icon_sucess.png'></span>
							<span>{{msgInfo.fileName}}:{{msgInfo.msg}}</span>
							<span>处理成功</span>
						</p>
						<p class='console-line' v-if='!msgInfo.success'>
							<span><img src='../assets/images/icon_failed.png'></span>
							<span>{{msgInfo.fileName}}:{{msgInfo.msg}}</span>
							<span class='red'>处理失败</span>
						</p>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
    const CryptoJS = require('crypto-js');
    const Base64 = require('js-base64').Base64;
    const fs = nodeRequire("fs");
	export default {
		data() {
			return {
				btnText:'上传照片',
				uploadDisabled:false,
			    subTextShow: false,
			    totalCount:0,
			    photoList:[],//总的照片
			    returnMsgList:[],
			    successNum:0,
			    errorNum:0,
			    allNum:0,
			    completeProportion:0
			}
		},
		methods: {
			logout() {
				localStorage.removeItem('rootOrgId');
				localStorage.removeItem('userName');
				localStorage.removeItem('user_token');
				this.$router.push({path: '/login'});
			},
			importPhotos() {
				var photos = document.getElementById('photos');
				this.photoList = photos.files;
				if (this.photoList.length>0) {
				    this.returnMsgList = [];
				    this.successNum = 0;
				    this.errorNum = 0;
				    this.allNum = 0;
				    /*this.uploadDisabled = true;
				    this.btnText = '处理中';*/
	                this.processQueue();
	            }
			},
		    isImageFile(file) {
		        let lowercaseName = file.toLowerCase();
		        if (lowercaseName.endsWith('.jpg') || lowercaseName.endsWith('.jpeg') || lowercaseName.endsWith('.png')) {
		            return true;
		        } else {
		            return false;
		        }
		    },
		    processQueue(){
		    	this.allNum = this.photoList.length;
		    	for(var i = 0;i<this.allNum;i++){
		    		this.processStudentPhoto(this.photoList[i]);
		    	}
		    },
		    
		    processStudentPhoto(photo) {
	    		let arr = photo.name.split('.');
		        let fileName = arr[0];//文件名就是身份证号码
		        let fileSuffix = arr[1];//文件后缀
		        let md5Hash = CryptoJS.MD5(Base64.encode(photo.name)).toString();
		        let photoMD5 = md5Hash+'.'+fileSuffix;
	    		let rootOrgId = localStorage.getItem('rootOrgId');
		        //根据身份证号码查询学生信息
		        this.$http.get('/api/ecs_core/studentFaceInfo/identityNumber?orgId='+rootOrgId+'&identityNumber='+fileName, {
		        }).then((response) => {
		        	var studentFaceInfoJSON = response.body;
		        	if (studentFaceInfoJSON.student && studentFaceInfoJSON.student.id) {
		        		let md5 = studentFaceInfoJSON.photoMD5;
                    	let studentId = studentFaceInfoJSON.student.id;
                    	//分析人脸
		        		this.detectFace(photo).then((res)=>{
		        			if(res.body.faces.length<1){
		        				this.finishOneBack(false,fileName,'没有检测到人脸',photo);
		        			}else{
		        				let face_token = res.body.faces[0].face_token;
		        				this.getFaceSetToken().then((res)=>{
			        					var face_set_token = res.bodyText;
			        					let photoMD5 = md5Hash+'.'+fileSuffix;
			        					var savePhotoInfo = {
		        							'studentFaceInfoId':studentFaceInfoJSON.id,
		        							'face_set_token':face_set_token,
		        							'face_token':face_token,
		        							'studentId':studentId,
		        							'userName':localStorage.getItem('userName'),
		        							'fileName':fileName,
		        							'file':photo,
		        							'identityNumber':fileName,
		        							'fileSuffix':fileSuffix,
		        							'photoMD5':photoMD5
			        					};
			        					this.addFaceToSet(face_set_token, face_token).then((res)=>{
			        						this.saveImageToUpyun(savePhotoInfo);
			        					},(err)=>{
			        						this.finishOneBack(false,fileName,'addFaceToSet失败',photo);
			        					});
			        				},(error)=>{
			        					this.finishOneBack(false,fileName,'getFaceSetToken失败',photo);
			        				}
		        				);
		        			}
		        		},(err)=>{
		        			this.finishOneBack(false,fileName,'调用face++检测人脸失败',photo);
		        		});
		        	}else{
                		this.finishOneBack(false,fileName,'查询身份证不存在',photo);
		        	}
                },(error)=>{
                	this.finishOneBack(false,fileName,'根据身份证号码查询失败',photo);
                });
			},
			saveImageToUpyun(savePhotoInfo){
		    	this._saveImageToUpyun(savePhotoInfo).then((res)=>{
				 	//调用core后台接口，对数据进行保存
                	let photoMD5 = savePhotoInfo.md5Hash+'.'+savePhotoInfo.fileSuffix;
                	if(!savePhotoInfo.studentFaceInfoId){
                		this.saveStudentFaceInfoByPost(savePhotoInfo);
                	}else{
                		this.saveStudentFaceInfoByPut(savePhotoInfo);
                	}
				 },(err)=>{
				 	this.finishOneBack(false,savePhotoInfo.fileName,'saveImageToUpyun失败',savePhotoInfo.file);
				 });
		    },
		    _saveImageToUpyun(savePhotoInfo){
		    	var url = process.env.VUE_APP_UPYUN_BUCKETURL+'/student_base_photo/'
		    				+savePhotoInfo.identityNumber+'/'
		    				+savePhotoInfo.photoMD5;
		        var authorization = 'Basic '+Base64.encode(process.env.VUE_APP_UPYUN_OPERATOR+':'+process.env.VUE_APP_UPYUN_PASSWORD);
        		var headers = {headers:{'Authorization':authorization,'Content-Type': 'image/jpeg'}};
		        return this.$http.put(url,savePhotoInfo.file,headers);
		    },
			getFaceSetToken(){
		    	return this.$http.get('/api/ecs_core/faceSet/enableFaceSet');
		    },
		    addFaceToSet(faceset_token,face_token){
		        let formData_addface = new FormData();
		        formData_addface.append('api_key', process.env.VUE_APP_FACEPP_API_KEY);
		        formData_addface.append('api_secret',process.env.VUE_APP_FACEPP_API_SECRET);
		        formData_addface.append('faceset_token', faceset_token);
		        formData_addface.append('face_tokens', face_token);
		        return this.$http.post('/facepp/v3/faceset/addface', formData_addface);
		    },
		    detectFace(file){
		    	let fileBlob = new Blob([file]);
		        let formData_face_token = new FormData();
		        formData_face_token.append('api_key',process.env.VUE_APP_FACEPP_API_KEY);
		        formData_face_token.append('api_secret',process.env.VUE_APP_FACEPP_API_SECRET);
		        formData_face_token.append('image_file', fileBlob);
		        return this.$http.post('/facepp/v3/detect', formData_face_token);
		    },
		    saveStudentFaceInfoByPost(savePhotoInfo){
		    	this.$http.post('/api/ecs_core/studentFaceInfo', {
		            'faceSetToken': savePhotoInfo.face_set_token,
		            'faceToken': savePhotoInfo.face_token,
		            'photoMD5': savePhotoInfo.photoMD5,
		            'student': {
		                'id': savePhotoInfo.studentId
		            },
		            'createUser':savePhotoInfo.userName,
		            'updateUser':savePhotoInfo.userName,
		            'createType':'IMPORT_TOOL'
		        }).then((res)=>{
		        	this.finishOneBack(true,savePhotoInfo.fileName,'处理成功');
		        },(err)=>{
		        	this.finishOneBack(false,savePhotoInfo.fileName,'saveStudentFaceInfoByPost失败',savePhotoInfo.file);
		        });
		    },
		    saveStudentFaceInfoByPut(savePhotoInfo){
		    	this.$http.put('/api/ecs_core/studentFaceInfo', {
		            'faceSetToken': savePhotoInfo.face_set_token,
		            'faceToken': savePhotoInfo.face_token,
		            'photoMD5': savePhotoInfo.photoMD5,
		            'student': {
		                'id': savePhotoInfo.studentId
		            },
		            'createUser':savePhotoInfo.userName,
		            'updateUser':savePhotoInfo.userName,
		            'createType':'IMPORT_TOOL'
		        }).then((res)=>{
		        	this.finishOneBack(true,savePhotoInfo.fileName,'处理成功');
		        },(err)=>{
		        	this.finishOneBack(false,savePhotoInfo.fileName,'saveStudentFaceInfoByPut失败',savePhotoInfo.file);
		        });
		    },
		    finishOneBack(isSuccess,fileName,msg,file){
		    	this.returnMsgList.push({'success':isSuccess,'fileName':fileName,'msg':msg});
	        	if(isSuccess){
	        		this.successNum++;
	        	}else{
	        		this.errorNum++;
	        		if(fs){
	        			var errorfilePath = file.path.substring(0,file.path.lastIndexOf("\\"))+"\\errorfiles";
		        		if (!fs.existsSync(errorfilePath)) {
	            			fs.mkdirSync(errorfilePath);
	            		}
		        		var readStream = fs.createReadStream(file.path);
						var writeStream = fs.createWriteStream(errorfilePath+"\\"+file.name);
						readStream.pipe(writeStream);
	        		}
	        	}
		    	if(this.errorNum+this.successNum == this.allNum){
		    		this.btnText = '上传照片';
		    		this.uploadDisabled = false;
		    		var photos = document.getElementById('photos');
		    		photos.files = null;
		    	}
		    }
		},
		created() {
		}
	}
</script>