package com.yizhi.application.report.course;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
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.course.application.feign.CourseReportClient;
import com.yizhi.course.application.vo.ReportStudyCourseVo;
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;
import com.baomidou.mybatisplus.plugins.Page;


/**
 * 按照课程统计导出Excel
 *
 * @author wangfeida
 */


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

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

    @Autowired
    private CourseReportClient courseReportClient;

    @Override
    protected String execute(Map<String, Object> map) {
        // TODO Auto-generated method stub
        logger.info("第一步：进入异步程序。");
        System.out.println(map);
        logger.info("123--"+map);
        String upLoadUrl = null;
        Long accountId = (Long) map.get("accountId");
        Long companyId = (Long) map.get("companyId");
        Long orgId = (Long) map.get("orgId");
        Long siteId = (Long) map.get("siteId");
        String startDate = (String) map.get("startDate");
        String endDate = (String) map.get("endDate");
        String kwd = (String) map.get("kwd");
        Long taskId = (Long) map.get("taskId");
        Date submitTime = (Date) map.get("submitTime");
        String serialNo = (String) map.get("serialNo");
        String taskName = (String) map.get("taskName");
        
        
        TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, accountId, submitTime, siteId, companyId);
        working(taskContext);
        
        
        Integer pageNo = 2;
        Integer pageSize = 30;
        Page<ReportStudyCourseVo> page = new Page<ReportStudyCourseVo>();
        logger.info("第二步：进入微服务程序查找数据。");

        List<ReportStudyCourseVo> tmpList = new ArrayList<ReportStudyCourseVo>();

        Page<ReportStudyCourseVo> tmpPage = new Page<ReportStudyCourseVo>();


        tmpPage = courseReportClient.courseGroup(kwd, startDate, endDate, companyId, orgId, siteId, pageNo - 1, pageSize);
        if (tmpPage != null) {
            tmpList.addAll(tmpPage.getRecords());

            int num = tmpPage.getTotal() / pageSize + 1;
            for (int i = 2; i <= num; i++) {
                tmpPage = courseReportClient.courseGroup(kwd, startDate, endDate, companyId, orgId, siteId, i, pageSize);
                if (tmpPage == null || tmpPage.getRecords().size() == 0) {
                    break;
                }
                tmpList.addAll(tmpPage.getRecords());

            }
        }
		
		
		
		/*int startIndex = (pageNo - 1) * pageSize;
		int endIndex = pageSize + startIndex;
		int total = tmpPage.getTotal();
		endIndex = endIndex > total ? total : endIndex; 
		if(endIndex == 0) {
			endIndex = 1;
		}
		for (; startIndex < endIndex; startIndex++) {
			tmpPage = courseReportClient.courseGroup(kwd, startDate, endDate, companyId, orgId, siteId, startIndex, pageSize);
			if(tmpPage == null || tmpPage.getRecords().size() == 0) {
				break;
			}
			tmpList.addAll(tmpPage.getRecords());
		}*/
        page.setRecords(tmpList);

        logger.info("第三步：数据--" + page);
        if (page != null) {
            logger.info("第四步：数据不为空，展示数据：" + page.getRecords());
        }
        List<ReportStudyCourseVo> list = new ArrayList<ReportStudyCourseVo>();
        if (page != null) {
            list = page.getRecords();
        }

        //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
       
        
        try {
            logger.info("第六步：开始创建Excel");
            // excel生成过程: excel-->sheet-->row-->cell
            // 第一步，创建一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 最大限度是50000
            // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("在线课程学习统计");
            // 第三步，在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("在线课程学习统计");
            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("课程当前状态");
            // 第五步，写入实体数据 实际应用中这些数据从数据库得到，
            BigDecimal b;
            BigDecimal big;
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    row = sheet.createRow(i + 3);
                    ReportStudyCourseVo rscv = new ReportStudyCourseVo();
                    rscv = list.get(i);
                    // 第四步，创建单元格，并设置值
                    if(rscv!=null) {
                    	 row.createCell((short) 0).setCellValue(rscv.getCourseNo());
                         row.createCell((short) 1).setCellValue(rscv.getCourseName());
                         if (rscv.getTotalAskAccount() != null) {
                             row.createCell((short) 2).setCellValue(rscv.getTotalAskAccount());
                         } else {
                             row.createCell((short) 2).setCellValue(0);
                         }
                         if (rscv.getTotalInAccount() != null) {
                             row.createCell((short) 3).setCellValue(rscv.getTotalInAccount());
                         } else {
                             row.createCell((short) 3).setCellValue(0);
                         }
                         if (rscv.getTotalCount() != null) {
                             row.createCell((short) 4).setCellValue(rscv.getTotalCount());
                         } else {
                             row.createCell((short) 4).setCellValue(0);
                         }
                         row.createCell((short) 5).setCellValue(rscv.getTotalCourseTime());
                         if(rscv.getTotalDuration() == null){
                             row.createCell((short) 6).setCellValue("0.0");
                         }else{
                             row.createCell((short) 6).setCellValue(rscv.getTotalDuration());
                         }

                         if(rscv.getTotalDuration() == null){
                             row.createCell((short) 7).setCellValue("0.0");
                         }else if (rscv.getTotalCount() != 0){
                             b=new BigDecimal(Double.valueOf(rscv.getTotalDuration()));
                             big = new BigDecimal(rscv.getTotalCount());
                             row.createCell((short) 7).setCellValue(b.divide(big,1,BigDecimal.ROUND_HALF_UP).toString());
                         }else {
                             row.createCell((short) 7).setCellValue(rscv.getTotalDuration());
                         }
                         row.createCell((short) 8).setCellValue(rscv.getCommentAccountCount());
                         if (rscv.getCourseScore() != null) {
                             row.createCell((short) 9).setCellValue(rscv.getCourseScore() + "");
                         } else {
                             row.createCell((short) 9).setCellValue(0);
                         }
                         if (rscv.getNumComment() != null) {
                             row.createCell((short) 10).setCellValue(rscv.getNumComment());
                         }else {
                             row.createCell((short) 10).setCellValue(0);
                         }
                         row.createCell((short) 11).setCellValue(rscv.getState() == 1 ? "已上架" : "未上架");
                         //taskDetail(taskContext.getTaskId(), "按课程统计---下载结果数据导出数据第+" + i + "+行成功");
                    }
                }
            }

            logger.info("第七步：给Excel命名");
            String fileName = "按课程统计---下载结果数据" + df2.format(submitTime) + ".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);
                logger.info("第八步：成功上传到阿里云");
            } 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("按课程统计---下载结果数据导出过程中发生错误，请查看日志{}", e);
        }
        logger.info("第九步：返回阿里云地址:" + upLoadUrl);
        return upLoadUrl;
    }
}
