<style>
</style>
<template>
	<div style='height: 100%;'>
		<div id='import-header'>
			<img src='../assets/images/nav_images.png' alt=''>照片批量上传工具
			<button id='exit-btn' @click='logout' title="退出"></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' @click="importPhotos">
		                	上传照片
		            </button>
	            </a>
	            <div id='progressDiv'>
	                <span>
	                	成功:
	                	<span style="color:green;">{{successNum}}</span>/{{allNum}}
	                </span>
	                <span>
	                	失败:<span style="color:red;">{{errorNum}}</span>/{{allNum}}
	                </span>
	                <span v-show="completeShow" style="color: green;font-weight: bold;">全部处理完成</span>
	                <span v-show="!completeShow&&(successNum>0||errorNum>0)" style="color: red;font-weight: bold;">处理中...</span>
	            </div>
			</div>
			<div id='progress-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>
						</p>
						<p class='console-line' v-if='!msgInfo.success'>
							<span><img src='../assets/images/icon_failed.png'></span>
							<span>{{msgInfo.fileName}}:{{msgInfo.msg}}</span>
						</p>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
    const CryptoJS = require('crypto-js');
    const Base64 = require('js-base64').Base64;
    const fs = nodeRequire("fs");
    
    import global_ from '../store/global';
    
	export default {
		data() {
			return {
				photoQuantityLimit:10000,//单次上传限制
			    photoList:[],//总的照片队列
			    photoLine:[],//正在处理的照片队列
			    concurrency:5,//同时处理的照片数量
			    returnMsgList:[],//返回信息
			    successNum:0,	//成功数量
			    errorNum:0,		//失败数量
			    allNum:0,		//总数
			    completeShow:false,
			    uploadDisabled:false,
			    seconds:0	//	耗时 秒
			}
		},
		methods: {
			init(){
				this.photoList = [];
			    this.photoLine = [];
			    this.returnMsgList = [];
			    this.successNum = 0;
			    this.errorNum = 0;
			    this.allNum = 0;
			    this.completeShow = false;
			},
			importPhotos() {
				this.init();
				var electron = nodeRequire('electron');
				let dialog = electron.remote.dialog;
		        dialog.showOpenDialog({
		            title: '选择照片所在目录',
		            properties: ["openDirectory"]
		        }, (folderPaths) => {
		            if (folderPaths) {
		            	this.processQueue(folderPaths[0]);
		            }
		        });
			},
			processQueue(folderPath){
				this.readFiles(folderPath);
				this.allNum = this.photoList.length;
				var _this = this;
				//初始化this.concurrency个到photoLine中，开始处理
				this.photoLine = this.photoList.splice(0,this.concurrency);
		    	for(var i = 0;i<this.photoLine.length;i++){
		    		this.processStudentPhoto(this.photoLine[i]);
		    	}
                
                /**
                 * 启动检查,看photoLine中是否有已完成的，如果有，从photoList中取出第一个将其替换
                 * 队列中一直保持this.concurrency个正在处理的照片
                 */
                global_.pageTimer['uploadTimer'] = setInterval(function(){
		            for (let i = 0; i < _this.photoLine.length; i++) {
		                if (_this.photoLine[i].finished) {
		                    if (_this.photoList.length > 0) {
		                        _this.photoLine[i] = _this.photoList.shift();
		                        _this.processStudentPhoto(_this.photoLine[i]);
		                    }
		                }
		            }
		            if (_this.photoList.length < 1) {
		                console.log('photoList处理完毕');
		                _this.completeShow = true;
		                clearInterval(global_.pageTimer['uploadTimer']);
		            }
		        },1500);
			},
			//读取文件
			readFiles(folderPath) {
		        let files = fs.readdirSync(folderPath);
		        files.forEach((fileName)=> {
		            let fullPath = folderPath + "\\" + fileName;
		            /*var stat = fs.lstatSync(fullPath);
		            if (stat.isDirectory()) {
		                this.readFiles(fullPath);
		            } else if (this.isImageFile(file)) {
		            	var student = {}
		                student.fileName = file;
		                student.path = fullPath;
		                this.photoList.push(student);
		            }*/
		           //只扫描当前文件夹，不递归扫描
		            if (this.isImageFile(fileName)) {
		            	var student = {}
		                student.fileName = fileName;
		                student.path = fullPath;
		                this.photoList.push(student);
		            }
		        });
		    },
		    isImageFile(fileName) {
		        let lowercaseName = fileName.toLowerCase();
		        if (lowercaseName.endsWith(".jpg") || lowercaseName.endsWith(".jpeg") || lowercaseName.endsWith(".png")) {
		            return true;
		        } else {
		            return false;
		        }
		    },
		    processStudentPhoto(studentPhoto) {
	    		let photoNameArr = studentPhoto.fileName.split('.');
		        let fileName = photoNameArr[0];//文件名就是身份证号码
		        let fileSuffix = photoNameArr[1];//文件后缀
		        
		        let photo = fs.readFileSync(studentPhoto.path);
		        //生成新名称
		        let md5Hash = CryptoJS.MD5(Base64.encode(fileName+new Date().getTime())).toString();
	    		let rootOrgId = localStorage.getItem('rootOrgId');
		        //根据身份证号码查询学生信息
		        this.$http.get('/api/ecs_core/studentFaceInfo/identityNumber?orgId='+rootOrgId+'&identityNumber='+fileName, {})
		        .then((response) => {
		        	var studentFaceInfo = response.body;
		        	if (studentFaceInfo.student && studentFaceInfo.student.id) {
		        		this.detectFace(photo).then((res)=>{
		        			if(res.body.faces.length>=1){
		        				let face_token = res.body.faces[0].face_token;
		        				this.getFaceSetToken().then((res)=>{
		        					//var face_set_token = res.bodyText;
		        					var face_set_token = '0c430026552ffcf4a8172e7182c91ae8';
		        					this.addFaceToSet(face_set_token, face_token).then((res)=>{
		        						this.saveStudentFaceInfo({
		        							'studentFaceInfoId':studentFaceInfo.id,
		        							'studentId':studentFaceInfo.student.id,
		        							'face_set_token':face_set_token,
		        							'face_token':face_token,
		        							'studentPhoto':studentPhoto,
		        							'identityNumber':fileName,
		        							'fileSuffix':fileSuffix,
		        							'photoNewName':md5Hash+'.'+fileSuffix,
		        							'file':photo
			        					});
		        					},(err)=>{
		        						this.finishOne(false,'addFaceToSet失败',studentPhoto);
		        					});
		        				},(err)=>{
		        					this.finishOne(false,'获取FaceSetToken失败',studentPhoto);
		        				});
		        			}else{
		        				this.finishOne(false,'face++没有检测到人脸',studentPhoto);
		        			}
		        		},(err)=>{
		        			this.finishOne(false,'调用face++检测人脸失败',studentPhoto);
		        		});
		        	}else{
                		this.finishOne(false,'查询身份证不存在',studentPhoto);
		        	}
                },(err)=>{
                	this.finishOne(false,'根据身份证号码查询失败',studentPhoto);
                });
			},
			//保存照片信息
			saveStudentFaceInfo(photoInfo){
		    	this.saveImageToUpyun(photoInfo).then((res)=>{
				 	//调用core后台接口，对数据进行保存
                	if(!photoInfo.studentFaceInfoId){
                		this.saveStudentFaceInfoByPost(photoInfo);
                	}else{
                		this.saveStudentFaceInfoByPut(photoInfo);
                	}
				 },(err)=>{
				 	this.finishOne(false,'saveImageToUpyun失败',photoInfo.studentPhoto);
				 });
		    },
		    //保存文件至又拍云
		    saveImageToUpyun(photoInfo){
		    	let fileBlob = new Blob([photoInfo.file]);
		    	var url = process.env.VUE_APP_UPYUN_BUCKETURL+'/student_base_photo/'+photoInfo.identityNumber+'/'+photoInfo.photoNewName;
		        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,photoInfo.file,headers);
		    },
		    //获取faceSetToken
			getFaceSetToken(){
		    	return this.$http.get('/api/ecs_core/faceSet/enableFaceSet');
		    },
		    //faceToken加入faceSetToken
		    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);
		    },
		    //face++分析人脸
		    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(photoInfo){
		    	this.$http.post('/api/ecs_core/studentFaceInfo', {
		            'faceSetToken': photoInfo.face_set_token,
		            'faceToken': photoInfo.face_token,
		            'photoMD5': photoInfo.photoNewName,
		            'student': {
		                'id': photoInfo.studentId
		            },
		            'createUser':localStorage.getItem('userName'),
		            'updateUser':localStorage.getItem('userName'),
		            'createType':'IMPORT_TOOL'
		        }).then((res)=>{
		        	this.finishOne(true,'处理成功',photoInfo.studentPhoto);
		        },(err)=>{
		        	this.finishOne(false,'saveStudentFaceInfoByPost失败',photoInfo.studentPhoto);
		        });
		    },
		    saveStudentFaceInfoByPut(photoInfo){
		    	this.$http.put('/api/ecs_core/studentFaceInfo', {
		            'faceSetToken': photoInfo.face_set_token,
		            'faceToken': photoInfo.face_token,
		            'photoMD5': photoInfo.photoNewName,
		            'student': {
		                'id': photoInfo.studentId
		            },
		            'createUser':localStorage.getItem('userName'),
		            'updateUser':localStorage.getItem('userName'),
		            'createType':'IMPORT_TOOL'
		        }).then((res)=>{
		        	this.finishOne(true,'处理成功',photoInfo.studentPhoto);
		        },(err)=>{
		        	this.finishOne(false,'saveStudentFaceInfoByPut失败',photoInfo.studentPhoto);
		        });
		    },
		    //成功或失败处理
		    finishOne(isSuccess,msg,studentPhoto){
		    	var fileName = studentPhoto.fileName;
		    	studentPhoto.finished = true;
		    	this.returnMsgList.push({'success':isSuccess,'fileName':fileName,'msg':msg});
	        	if(isSuccess){
	        		this.successNum++;
	        	}else{
	        		this.errorNum++;
        			var errorfilePath = studentPhoto.path.substring(0,studentPhoto.path.lastIndexOf("\\"))+"\\errorfiles";
	        		if (!fs.existsSync(errorfilePath)) {
            			fs.mkdirSync(errorfilePath);
            		}
	        		var readStream = fs.createReadStream(studentPhoto.path);
					var writeStream = fs.createWriteStream(errorfilePath+"\\"+fileName);
					readStream.pipe(writeStream);
					fs.appendFile(errorfilePath+'\\errorPhotos.txt',fileName+":"+msg+'\n',function (){});
	        	}
		    },
		    logout() {
				localStorage.removeItem("rootOrgId");
				localStorage.removeItem("userName");
				localStorage.removeItem("user_token");
				this.$router.push({path:'/login'});
			}
		}
	};
</script>