package com.yizhi.application.report.course;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
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.course.application.feign.CourseReportClient;
import com.yizhi.course.application.vo.ReportStudyCourseViewVo;
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;

/**
 * 按照课程统计-----详情---导出Excel
 * @author wangfeida
 *
 */
@Component
public class CourseGroupViewExportExcel extends AbstractDefaultTask<String, Map<String,Object>> {
	
	
	private static final Logger logger = LoggerFactory.getLogger(CourseGroupViewExportExcel.class);
	
	@Autowired
	private CourseReportClient courseReportClient;
	
	

	@Override
	protected String execute(Map<String, Object> map) {
		// TODO Auto-generated method stub
		
		
		SimpleDateFormat simFormate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		  String upLoadUrl=null;
		  Long accountId=(Long) map.get("accountId");
		  Long companyId=(Long) map.get("companyId");
		  Long siteId=(Long) map.get("siteId");
		  String startDate=(String) map.get("startDate");
		  String endDate=(String) map.get("endDate");
		  Long courseId=(Long) map.get("courseId");
		  String orgKwd=(String) map.get("orgKwd");
		  String accountKwd=(String) map.get("accountKwd");
		  Long taskId=(Long) map.get("taskId");
		  Date submitTime=(Date) map.get("submitTime");
		  String serialNo=(String) map.get("serialNo");
		  String taskName=(String) map.get("taskName");
		  logger.info("异步得到信息{}","accountId"+accountId+"--companyId"+companyId
				                  +"--siteId"+siteId+"--startDate"+startDate+"--endDate"+endDate
				                  +"--courseId"+courseId+"--orgKwd"+orgKwd+"--accountKwd"+accountKwd
				                  +"--taskId"+taskId+"--submitTime"+submitTime+"--serialNo"+serialNo
				                  +"--taskName"+taskName);
		  
		  
		  
		  logger.info("异步所需要的信息{}","taskId"+taskId+"--serialNo"+serialNo
                  +"--taskName"+taskName+"--accountId"+accountId+"--submitTime"+submitTime
                  +"--siteId"+siteId+"--companyId"+companyId);
		    TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, accountId, submitTime, siteId, companyId);
			working(taskContext);
		 
		  
		  List<LinkedHashMap<String, String>> listLinkedHashMap=new ArrayList<LinkedHashMap<String, String>>();
		  
		  Integer pageNo=2;
		  Integer pageSize=30;

		  Map<String,Object> mapRecord=new HashMap<String,Object>();
		  mapRecord=courseReportClient.courseGroupView(accountKwd, orgKwd, courseId, startDate, endDate, pageNo-1, pageSize);
		  Object object = mapRecord.get("list");
		  ArrayList<LinkedHashMap<String, String>> listRecord = (ArrayList<LinkedHashMap<String, String>>) object;
		  logger.info("第一次查询信息{}",listRecord);
		 
		  
		  Integer totalNum=(Integer) mapRecord.get("pageTotal");
		  String cname=(String) mapRecord.get("cname");
		  logger.info("第三步：携带的其他信息{}","totalNum"+totalNum+"--cname"+cname);
		  if(listRecord!=null&&listRecord.size()>0) {
			  
		  
			  listLinkedHashMap.addAll(listRecord);
			    int num=totalNum/pageSize+1;
				for (int  i= 2; i <= num; i++) {
					mapRecord=courseReportClient.courseGroupView(accountKwd, orgKwd, courseId, startDate, endDate, i, pageSize);
					
					object = mapRecord.get("list");
					listRecord = (ArrayList<LinkedHashMap<String, String>>) object;
					
					if(listRecord == null || listRecord.size()==0) {
						break;
					}
					listLinkedHashMap.addAll(listRecord);	
				}
		  }
		  logger.info("查询的信息{}",listLinkedHashMap);
		  
		  List<ReportStudyCourseViewVo> list=new ArrayList<ReportStudyCourseViewVo>();
		  ReportStudyCourseViewVo rscvv=null;
		  for (Map mapp:listLinkedHashMap) {
			rscvv=new ReportStudyCourseViewVo();
			String accountName= (mapp.get("accountName"))==null?null:(mapp.get("accountName").toString());
			String accountFullName= (mapp.get("accountFullName"))==null?null:(mapp.get("accountFullName").toString());
			String workNum= (mapp.get("workNum"))==null?null:(mapp.get("workNum").toString());
			String orgName= (mapp.get("orgName"))==null?null:(mapp.get("orgName").toString());
			Integer learnNum=Integer.valueOf((mapp.get("learnNum"))==null?"0":(mapp.get("learnNum").toString()));
			Date startTime=null;
			if(mapp.get("startTime")!=null) {
				Long startTimems=(Long) mapp.get("startTime");
				startTime=new Date(startTimems);
			}
			
			Date endTime=null;
			if(mapp.get("endTime")!=null) {
				Long endTimems=(Long) mapp.get("endTime");
				endTime=new Date(endTimems);
			}
			Integer state= Integer.valueOf((mapp.get("state"))==null?"0":(mapp.get("state").toString()));
			Integer learnScore= Integer.valueOf((mapp.get("learnScore"))==null?"0":(mapp.get("learnScore").toString()));
			Integer learnPoint= Integer.valueOf((mapp.get("learnPoint"))==null?"0":(mapp.get("learnPoint").toString()));
			Integer accountState=  Integer.valueOf((mapp.get("accountState"))==null?"0":(mapp.get("accountState").toString()));
			rscvv.setAccountName(accountName);
			rscvv.setAccountFullName(accountFullName);
			rscvv.setWorkNum(workNum);
			rscvv.setOrgName(orgName);
			rscvv.setTotalDuration(mapp.get("totalDuration").toString());
			rscvv.setStartTime(startTime);
			rscvv.setEndTime(endTime);
			rscvv.setState(state);
			rscvv.setLearnScore(learnScore);
			rscvv.setLearnPoint(learnPoint);
			rscvv.setAccountState(accountState);
			rscvv.setLearnNum(learnNum);
			list.add(rscvv);
			
			
		}
		  
		  
		  
		
		 

		 
			
			 
	    	
		    try {
				//excel生成过程: excel-->sheet-->row-->cell
				// 第一步，创建一个Excel文件
				HSSFWorkbook wb = new HSSFWorkbook();
				
				// 最大限度是50000
				
				// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
				HSSFSheet sheet = wb.createSheet(cname+"学习明细");
				
				// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
				HSSFRow row = sheet.createRow((int) 0);
				// 第四步，创建单元格，并设置值表头 设置表头居中
				HSSFCellStyle style = wb.createCellStyle();
				style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式

				// 合并单元格  
				CellRangeAddress cra=new CellRangeAddress(0,0,0,12); // 起始行, 终止行, 起始列, 终止列  
				sheet.addMergedRegion(cra);
				HSSFCell cell = row.createCell((short) 0);
				cell.setCellValue(cname+"学习明细");
				cell.setCellStyle(style);
				
				// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
				HSSFRow row2 = sheet.createRow((int) 1);
				// 第四步，创建单元格
				CellRangeAddress cra2=new CellRangeAddress(1,1,0,3);
				sheet.addMergedRegion(cra2);
				HSSFCell cell2 = row2.createCell((short) 0);
				cell2.setCellValue("统计周期： "+startDate+"~"+endDate);
					
				HSSFRow row3 = sheet.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("所在部门"); 
				
				
				

				ReportStudyCourseViewVo rscv =null;
				// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
				for (int i = 0; i < list.size(); i++){
					if(list!=null&&list.size()>0) {
				    row3 = sheet.createRow(i + 3);
				    rscv= list.get(i);
				    logger.info("开始写入Excel{}",rscv);
					// 第四步，创建单元格，并设置值
				    if(rscv!=null) {
				    	row3.createCell((short) 0).setCellValue(rscv.getAccountName());
						row3.createCell((short) 1).setCellValue(rscv.getAccountFullName());
						row3.createCell((short) 2).setCellValue(rscv.getWorkNum());
						row3.createCell((short) 3).setCellValue(rscv.getTotalDuration());
						row3.createCell((short) 4).setCellValue(rscv.getLearnNum());
						if(rscv.getStartTime()!=null) {
							row3.createCell((short) 5).setCellValue(simFormate.format(rscv.getStartTime()));
						}
						if(rscv.getEndTime()!=null) {
							row3.createCell((short) 6).setCellValue(simFormate.format(rscv.getEndTime()));
						}
						if(rscv.getState()==0) {
							row3.createCell((short) 7).setCellValue("未开始");
						}
						if(rscv.getState()==1) {
							row3.createCell((short) 7).setCellValue("进行中");
						}
						if(rscv.getState()==2) {
							row3.createCell((short) 7).setCellValue("已完成");
						}
						
						row3.createCell((short) 8).setCellValue(rscv.getLearnScore());
						row3.createCell((short) 9).setCellValue(rscv.getLearnPoint());
						row3.createCell((short) 10).setCellValue(rscv.getAccountState()==1?"启用":"禁用");
						row3.createCell((short) 11).setCellValue(rscv.getOrgName());
						//taskDetail(taskContext.getTaskId(), "按课程统计-详情-下载课程学习明细-"+cname+"-导出数据第+"+i+"+行成功");
				    }
				}
				}
				String fileName = mapRecord.get("cname")+"学习明细"+".xls";
                //String requestPath = "E:\\home";
				String requestPath= FileConstant.SAVE_PATH;
				File fileDir=new File(requestPath);
				if(!fileDir.exists()) {
					fileDir.mkdir();
				}
				String path = requestPath+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, "按课程统计---详情--- 下载课程学习明细导出过程中发生错误，请查看日志");	
				logger.error("按课程统计---详情--- 下载课程学习明细导出过程中发生错误，请查看日志");
			}
		return upLoadUrl;
	}

	}
	
