package com.yizhi.application.assignment.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.yizhi.assignment.application.feign.AssignmentClient;
import com.yizhi.assignment.application.vo.AnswersDownVO;
import com.yizhi.assignment.application.vo.DownloadAnswerVO;
import com.yizhi.assignment.application.vo.entity.AssignmentAnswerFile;
import com.yizhi.core.application.context.TaskContext;
import com.yizhi.core.application.file.constant.FileConstant;
import com.yizhi.core.application.file.task.AbstractDefaultTask;
import com.yizhi.core.application.file.util.OssUpload;
import com.yizhi.util.application.zip.ZipUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yizhi.application.assignment.util.FileReadUtil;


@Component
public class AssignmentDownloadAnswerExport extends AbstractDefaultTask<String, Map<String,Object>> {


	private static final Logger logger = LoggerFactory.getLogger(AssignmentDownloadAnswerExport.class);




	@Autowired
	private AssignmentClient assignmentClient;
	@Autowired
	private FileReadUtil fileReadUtil;

	@Override
	protected String execute(Map<String, Object> arg0) {
		// TODO Auto-generated method stub

		String upload=null;

		  /*
		   *  思路  1通过接口得到文件的url
		   *      2  通过阿里云的url下载到服务器
		   *      3将下载到服务器的文件打包
		   *      4将打包的zip  打成一个大的包
		   */

		  DownloadAnswerVO vo=(DownloadAnswerVO) arg0.get("vo");
		  Long accountId=(Long) arg0.get("accountId");
		  Long siteId=(Long) arg0.get("siteId");
		  Long companyId=(Long) arg0.get("companyId");
		  Long taskId=(Long) arg0.get("taskId");
		  Date submitTime=(Date) arg0.get("submitTime");
		  String serialNo=(String) arg0.get("serialNo");
		  String taskName=(String) arg0.get("taskName");

		  /**
		   * 走异步消息
		   */
		  TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, accountId, submitTime, siteId, companyId);
		  working(taskContext);

		  List<AnswersDownVO> list=assignmentClient.exportAssignmentZip(vo);
		  String serverUrlName= FileConstant.SAVE_PATH;            //服务器的路径
		  SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");



		  /**
		   * 判断文件夹是否存在，如果不存在则创建
		   */
		  File serverPathDir=new File(serverUrlName);
		  if(!serverPathDir.exists()) {
			  serverPathDir.mkdir();
		  }

		  Long downLoadTimeMs=submitTime.getTime();
		  String downLoadTime=dateFormate.format(submitTime);
		  //异步消息

		  String assignmentName=fileReadUtil.getSpecialCharacter(list.get(0).getAssignmentName());
		  //父文件夹的名字

		  //毫秒_线程名字
		  String parentDirName=assignmentName+"_"+downLoadTimeMs+"_"+Thread.currentThread().getName();
		  //父文件夹的完整路径
		//  例子:/home/file/作业名字_毫秒_线程名字
		  String parentPathName=serverUrlName+File.separator+parentDirName;
		  //在服务器路径下创建父文件夹
		  File   parentPathDir = new File(parentPathName);
		  //在服务器路径下创建   作业名字_日期   文件夹（父文件夹）
		  parentPathDir.mkdir();
		  for (int i = 0; i < list.size(); i++) {
			AnswersDownVO answersDownVO=new AnswersDownVO();
			answersDownVO=list.get(i);
			String accountName=answersDownVO.getAccountName();   //用户名
			Date commitTime=answersDownVO.getCommitTime();       //提交时间
			Integer source=answersDownVO.getSource();            //来源为为本地上传
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			//子文件夹的路径
			String childPathNameUUID = UUID.randomUUID().toString().replaceAll("-","");
			String childPathName=parentPathName+File.separator+accountName+"-"+df.format(commitTime)+"_"+childPathNameUUID;
			//子文件夹这个文件夹
			File childDirFile=new File(childPathName);
			//创建子文件夹
			childDirFile.mkdir();
			if(source==1) {
			    List<AssignmentAnswerFile> listAssignmentAnswerFile=answersDownVO.getList();
			    for (int j = 0; j < listAssignmentAnswerFile.size(); j++) {
			    	String url=listAssignmentAnswerFile.get(j).getFileUrl();   //阿里云的地址
			    	String fileName=listAssignmentAnswerFile.get(j).getFileName();   //文件名字和后缀      111.docx
			    	String uuid = UUID.randomUUID().toString().replaceAll("-","");
			    	fileReadUtil.read(url, childPathName, fileName);  //1阿里云的文件流路径   2下载到服务器的存储路径  3文件名字    注释： 阿里云的文件下载到服务器的文件夹下
				}
			}
			//子文件夹的zip的名字
			 String uuid = UUID.randomUUID().toString().replaceAll("-","");
			 String childDirZip=childPathName+".zip";
			 try {
					ZipUtil.zip(childPathName, childDirZip);
					FileUtils.deleteDirectory(childDirFile);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					logger.error("关于作业中学生答案打包过程中发生错误",e);
				}
		  }
		  //父文件夹 压缩成 压缩包
		  String uuid = UUID.randomUUID().toString().replaceAll("-","");
		  String parentDirZipPath=parentPathName+".zip";
		  try {
			ZipUtil.zip(parentPathName, parentDirZipPath);
			FileUtils.deleteDirectory(parentPathDir);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("关于作业打包过程中发生错误",e);
		}
		  upload= OssUpload.upload(parentDirZipPath, assignmentName+"_"+downLoadTime+".zip");
		  success(taskContext,"成功", upload);
		  File pathZipFile=new File(parentDirZipPath);
		  try {
			pathZipFile.delete();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  return upload;
	}

}
