package com.yizhi.application.report.trainingproject;

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

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.training.application.feign.TrainingProjectReportClient;
import com.yizhi.training.application.vo.manage.TrainingProjectGroupViewExportVO3;
import com.yizhi.training.application.vo.manage.TrainingProjectGroupViewExportVO4;
import com.yizhi.training.application.vo.manage.TrainingProjectMainMessage;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



/**
 * 按照项目统计-查看-
 * @author wangfeida
 *
 */

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

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

	@Autowired
	private TrainingProjectReportClient trainingProjectReportClient;

	@Override
	protected String execute(Map<String, Object> map) {
		// TODO Auto-generated method stub
		String sheetName="按项目统计-查看-下载学员学习明细-导出记录";
		String upLoadUrl = null;
		Long projectId=(Long) map.get("projectId");
		Long accountId = (Long) map.get("accountId");
		Long companyId = (Long) map.get("companyId");
		List<Long> orgIds = (List<Long>) map.get("orgIds");
		Long siteId = (Long) map.get("siteId");
		
		Long taskId=(Long) map.get("taskId");
		Date submitTime=(Date) map.get("submitTime");
		String serialNo=(String) map.get("serialNo");
		String taskName=(String) map.get("taskName");
		Integer pageNo=1;
		Integer pageSize=20;
		Integer maxNumOneSheet=50000;   //一个sheet最多有多少数据量
		Integer numSheet=0;             //有多少个sheet
		Integer curSheet=1;
		List<TrainingProjectGroupViewExportVO3> list=new ArrayList<TrainingProjectGroupViewExportVO3>();
		
		

		
		TaskContext taskContext = new TaskContext(taskId, serialNo, taskName,accountId, submitTime, siteId, companyId);// 任务id  任务名字      操作人id   操作时间
		working(taskContext);
		
		
		/**
		 * 项目主体信息-表头
		 */
		TrainingProjectMainMessage trainingProjectMainMessaget=trainingProjectReportClient.mainMessage(projectId,0);
		String startDate=null;
		String endDate=null;
		
		if(trainingProjectMainMessaget!=null) {
			startDate=trainingProjectMainMessaget.getStartTime();
			endDate=trainingProjectMainMessaget.getEndTime();
		}
		
		
		
		TrainingProjectGroupViewExportVO4 trainingProjectGroupViewExportVO4=trainingProjectReportClient.trainingProjectGroupViewExport4(projectId);
		Integer listAllRecordNum=0; //总数据量
		if(trainingProjectGroupViewExportVO4!=null) {
			listAllRecordNum=trainingProjectGroupViewExportVO4.getTotalAskNum()*trainingProjectGroupViewExportVO4.getActivityNum();
		}
		//应该参加的人的账号
		//List<Long> accountIds=trainingProjectGroupViewExportVO4.getAccountIds();
		Integer totalAskNum=trainingProjectGroupViewExportVO4.getTotalAskNum();
		List<TrainingProjectGroupViewExportVO3> trainingProjectGroupViewExportVO3=null;
		if(totalAskNum>0) {
			for (int i = 1; i <= totalAskNum/pageSize+1; i++) {
				trainingProjectGroupViewExportVO3=trainingProjectReportClient.trainingProjectGroupViewExport3(projectId,i,pageSize);
				list.addAll(trainingProjectGroupViewExportVO3);
			}
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		
		
		try {
			// excel生成过程: excel-->sheet-->row-->cell
			// 第一步，创建一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
		
			   
				if(list!=null&&list.size()>0) {
					numSheet=list.size()/maxNumOneSheet+1;  //有这么多sheet
					for (int i = 1; i <= numSheet; i++) {
						// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
						HSSFSheet sheet1 = wb.createSheet("学员学习明细统计"+i);
						// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
						HSSFRow row = sheet1.createRow((int) 0);
						// 第四步，创建单元格，并设置值表头 设置表头居中
						HSSFCellStyle style = wb.createCellStyle();
						style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
						// 合并单元格
						CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 7); // 起始行, 终止行, 起始列, 终止列
						sheet1.addMergedRegion(cra);
						HSSFCell cell = row.createCell((short) 0);
						cell.setCellValue(trainingProjectGroupViewExportVO4.getProjectName()+"学员学习明细统计");
						cell.setCellStyle(style);

						// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
						HSSFRow row2 = sheet1.createRow((int) 1);
						// 第四步，创建单元格
						CellRangeAddress cra2 = new CellRangeAddress(1, 1, 0, 3);
						sheet1.addMergedRegion(cra2);
						HSSFCell cell2 = row2.createCell((short) 0);
						cell2.setCellValue("项目周期： " + startDate + "~" + endDate);

						HSSFRow row3 = sheet1.createRow((int) 2);
						row3.createCell((short) 0).setCellValue("用户名");
						row3.createCell((short) 1).setCellValue("姓名");
						row3.createCell((short) 2).setCellValue("学习计划名称");
						row3.createCell((short) 3).setCellValue("学习活动名称");
						row3.createCell((short) 4).setCellValue("学习活动类型");
						row3.createCell((short) 5).setCellValue("开始时间");
						row3.createCell((short) 6).setCellValue("最早完成时间");
						row3.createCell((short) 7).setCellValue("得分");
						row3.createCell((short) 8).setCellValue("所获积分");
						row3.createCell((short) 9).setCellValue("完成状态");
						row3.createCell((short) 10).setCellValue("用户当前状态");
						row3.createCell((short) 11).setCellValue("所在部门");
						// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
						if(list!=null&&list.size()>0) {
						TrainingProjectGroupViewExportVO3 rscv=null;
						for (int j = 0; j < maxNumOneSheet; j++) {
							row = sheet1.createRow(j + 3);
							int a=j+(i-1)*maxNumOneSheet;
							if(a>=list.size()) {
								break;
							}
							rscv = list.get(a);
							// 第四步，创建单元格，并设置值
							row.createCell((short) 0).setCellValue(rscv.getAccountName());
							row.createCell((short) 1).setCellValue(rscv.getAccountFullName());
							row.createCell((short) 2).setCellValue(rscv.getPlanName());
							row.createCell((short) 3).setCellValue(rscv.getActivityName());
							row.createCell((short) 4).setCellValue(rscv.getActivityType());
							if(rscv.getStartTime()!=null) {
								row.createCell((short) 5).setCellValue(df.format(rscv.getStartTime()));
							}
							if(rscv.getFirstFinishTime()!=null) {
								row.createCell((short) 6).setCellValue(df.format(rscv.getFirstFinishTime()));
							}
							
							if(rscv.getScore()!=null) {
								row.createCell((short) 7).setCellValue(rscv.getScore()+"");
							}
							if(rscv.getPoint()!=null) {
								row.createCell((short) 8).setCellValue(rscv.getPoint()+"");
							}
							String state=null;
							if(rscv.getState()==-1) {
								state="未开始";
							}
							if(rscv.getState()==0) {
								state="进行中";
							}
							if(rscv.getState()==1) {
								state="已完成";
							}
							row.createCell((short) 9).setCellValue(state);
							if(rscv.getAccountState()!=null) {
								row.createCell((short) 10).setCellValue(rscv.getAccountState()==0?"禁用":"启用");
							}
							row.createCell((short) 11).setCellValue(rscv.getOrgName());
							//taskDetail(taskContext.getTaskId(), sheetName+"导出数据第+" + (i+1) + "+行成功");
						}
						}
						
						
					
						
					}
					}
				
			

			String fileName = sheetName + df2.format(submitTime) + ".xls";
			String requestPath =  FileConstant.SAVE_PATH;
			File fileDir = new File(requestPath);
			if (!fileDir.exists()) {
				fileDir.mkdir();
			}
			String path = requestPath +File.separator+fileName;
			FileOutputStream os = null;
			File file = null;
			try {
				os = new FileOutputStream(path);
				wb.write(os);
				// 阿里云返回url
				upLoadUrl = OssUpload.upload(path, fileName);
				file = new File(path);
				success(taskContext, "成功", upLoadUrl);
			} catch (Exception e1) {
				e1.printStackTrace();
				fail(taskContext, "写入过程中发生错误");
				logger.error("上传过程中发生错误，请查看日志");
			} finally {
				if (os != null) {
					os.close();
				}
				if (wb != null) {
					wb.close();
				}
				if (file != null) {
					file.delete();
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			fail(taskContext, sheetName+"导出过程中发生错误，请查看日志"+e.getMessage());
			logger.error(sheetName+"导出过程中发生错误，请查看日志");
		}
		return upLoadUrl;
	}
}
