package com.yizhi.application.report.trainingproject;

import com.yizhi.core.application.context.RequestContext;
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.sign.application.feign.ReportSignClient;
import com.yizhi.sign.application.vo.domain.StatisticsSign;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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;

@Component
public class DownloadSign extends AbstractDefaultTask<String, Map<String, Object>> {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DownloadSign.class);


    @Autowired
    private ReportSignClient reportSignClient;


    @Override
    protected String execute(Map<String, Object> map) {

        RequestContext context = (RequestContext) map.get("context");
        Long projectId = (Long) map.get("projectId");
        String startDate = (String) map.get("startDate");
        String endDate = (String) map.get("endDate");
        String taskName = (String)map.get("taskName");

        String upLoadUrl = null;
        String requestPath = FileConstant.SAVE_PATH;
        //String requestPath= "E\\";
        File fileDir = new File(requestPath);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        Date submitTime = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TaskContext taskContext = new TaskContext(submitTime.getTime(), taskName , context.getAccountId(), submitTime, context.getSiteId(), context.getCompanyId());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        taskContext.setSerialNo((String)map.get("serialNo"));
        working(taskContext);
        try {
            int pageNo = 1;
            int pageSize = 20;
            int total = reportSignClient.signPageCount(projectId, startDate, endDate, context.getCompanyId(), context.getOrgIds(), context.getSiteId());
            List<StatisticsSign> statisticsSigns = new ArrayList<>();
            List<StatisticsSign> listOne;
            int pageCount = (int) Math.ceil(Double.valueOf(total) / pageSize);
            for (int i = 0; i < pageCount; i++) {
                listOne = reportSignClient.signPageList(projectId, startDate, endDate, context.getCompanyId(), context.getOrgIds(), context.getSiteId(), pageNo, pageSize);
                statisticsSigns.addAll(listOne);
                pageNo++;
            }
            //excel生成：excel-sheet-row-cell
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet( "SIGN-EXPORT-" + submitTime.getTime());
            // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short,
            // 创建第1行
            //创建单元格格式
            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.LEFT);//创建居左格式
            HSSFRow row = sheet.createRow((int) 0);
            //合并单元格
            CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 4); // 起始行, 终止行, 起始列, 终止列
            sheet.addMergedRegion(cra);
            HSSFCell cell = row.createCell((short) 0);
            cell.setCellValue("签到统计");

            row = sheet.createRow((int) 1);
            cra = new CellRangeAddress(1, 1, 0, 4); // 起始行, 终止行, 起始列, 终止列
            sheet.addMergedRegion(cra);
            if(startDate == null){
                startDate = "xxxx";
            }
            if(endDate == null){
                endDate = "xxxx";
            }
            row.createCell((short) 0).setCellValue("统计周期:" + startDate + "～" + endDate);

            row = sheet.createRow((int) 2);
            row.createCell((short) 0).setCellValue("项目名称");
            row.createCell((short) 1).setCellValue("签到时间");
            row.createCell((short) 2).setCellValue("可签人数");
            row.createCell((short) 3).setCellValue("已签人数");
            row.createCell((short) 4).setCellValue("未签人数");

            int index = 3;
            int s = 0;
            for (StatisticsSign statisticsSign : statisticsSigns) {
                if (statisticsSign == null) {
                    continue;
                }
                row = sheet.createRow((int) index);
                cell = row.createCell((short) 0);
                if (statisticsSign.getSignName() != null) {
                    cell.setCellValue(statisticsSign.getSignName());
                }
                cell = row.createCell((short) 1);
                if (statisticsSign.getSignStartTime() != null && statisticsSign.getSignEndTime() != null) {
                    cell.setCellValue(df.format(statisticsSign.getSignStartTime()) + "～" + df.format(statisticsSign.getSignEndTime()));
                }
                cell = row.createCell((short) 2);
                if (statisticsSign.getCanStateCount() != null) {
                    cell.setCellValue(statisticsSign.getCanStateCount());
                }
                cell = row.createCell((short) 3);
                if (statisticsSign.getJoinStateCount() != null) {
                    cell.setCellValue(statisticsSign.getJoinStateCount());
                }
                cell = row.createCell((short) 4);
                if (statisticsSign.getCanStateCount() != null && statisticsSign.getJoinStateCount() != null) {
                    cell.setCellValue(statisticsSign.getCanStateCount() - statisticsSign.getJoinStateCount());
                }
                index++;
                s ++ ;
//                taskDetail(taskContext.getTaskId(),  "签到统计导出数据第" + s + "行成功");
            }
            StringBuffer fileNameSb = new StringBuffer().append("签到统计").append(System.currentTimeMillis()).append(".xls");
            String fileName = fileNameSb.toString();
            String path = new StringBuffer().append(requestPath).append(fileNameSb).toString();
            FileOutputStream os = null;
            File file = null;
            try {
                os = new FileOutputStream(path);
                workbook.write(os);
                //阿里云返回url
                upLoadUrl = OssUpload.upload(path, fileName);
                file = new File(path);
                success(taskContext, "成功", upLoadUrl);
            } catch (Exception e1) {
                e1.printStackTrace();
                fail(taskContext, "写入过程中发生错误");
                logger.error("写入数据到Excel的过程中或者上传到阿里云中发生错误");
            } finally {
                if (os != null) {
                    os.close();
                }
                if (workbook != null) {
                    workbook.close();
                }
                if (file != null) {
                    file.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            fail(taskContext, "签到统计导出过程中发生错误，请查看日志");
            logger.error("创建Excel的过程中发生错误");
        }
        return upLoadUrl;
    }
}
