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 com.yizhi.sign.application.vo.domain.TrSign;
import com.yizhi.sign.application.vo.domain.TrSignTime;
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 org.springframework.util.CollectionUtils;

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 DownloadSignDetails extends AbstractDefaultTask<String, Map<String, Object>> {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DownloadSignDetails.class);
    @Autowired
    private ReportSignClient reportSignClient;

    @Override
    protected String execute(Map<String, Object> map) {
        RequestContext context = (RequestContext) map.get("context");
        TrSign trSign = (TrSign) map.get("trSign");
        String startDate = (String) map.get("startDate");
        String endDate = (String) map.get("endDate");
        Long projectId = (Long) map.get("signId");
        String orgNameOrCode = (String) map.get("orgNameOrCode");
        String accountName = (String) map.get("accountName");
        String taskName = (String) map.get("taskName");
        Long id = (Long) map.get("id");

        int pageNo = 1;
        int pageSize = 20;
        int total = reportSignClient.signViewCount(id, projectId, startDate, endDate, orgNameOrCode, accountName);
        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.signViewList(id, projectId, startDate, endDate, orgNameOrCode, accountName, pageNo, pageSize);
            statisticsSigns.addAll(listOne);
            pageNo++;
        }


        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("yyyyMMddHHmmss");
        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 {
            //excel生成：excel-sheet-row-cell
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(trSign.getTrainningProjectName() + "_" + df.format(submitTime));
            // 在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, 12); // 起始行, 终止行, 起始列, 终止列
            sheet.addMergedRegion(cra);
            HSSFCell cell = row.createCell((short) 0);
            cell.setCellValue("签到明细");

            row = sheet.createRow((int) 1);
            cra = new CellRangeAddress(1, 1, 0, 12); // 起始行, 终止行, 起始列, 终止列
            sheet.addMergedRegion(cra);
            if (startDate == null || startDate == "") {
                startDate = "xxxx";
            }
            if (endDate == null || endDate == "") {
                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) 6).setCellValue("所在部门");
            row.createCell((short) 4).setCellValue("是否签到");
            row.createCell((short) 5).setCellValue("签到时间");

            String[] parentNames;
            int index = 3;
            int s = 0;
            Date startTime = null;
            Date endTime = null;

            if (!CollectionUtils.isEmpty(statisticsSigns) && statisticsSigns.get(0).getSignStartTime() != null && statisticsSigns.get(0).getSignEndTime() != null) {
                startTime = statisticsSigns.get(0).getSignStartTime();
                endTime = statisticsSigns.get(0).getSignEndTime();
            } else {
                TrSignTime trSignTime = reportSignClient.getSignTime(projectId);
                if (null != trSignTime) {
                    startTime = trSignTime.getStartTime();
                    endTime = trSignTime.getEndTime();
                }
            }
            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 (startTime != null && endTime != null) {
                    cell.setCellValue(format.format(startTime) + "～" + format.format(endTime));
                }
                cell = row.createCell((short) 2);
                if (statisticsSign.getAccountName() != null) {
                    cell.setCellValue(statisticsSign.getAccountName());
                }
                cell = row.createCell((short) 3);
                if (statisticsSign.getAccountFullname() != null) {
                    cell.setCellValue(statisticsSign.getAccountFullname());
                }
                cell = row.createCell((short) 4);
                Integer state = statisticsSign.getJoinState();
                if (state != null) {
                    if (state == 1) {
                        cell.setCellValue("已签到");
                    } else {
                        cell.setCellValue("未签到");
                    }
                }
                cell = row.createCell((short) 5);
                if (statisticsSign.getSignTime() != null) {
                    cell.setCellValue(format.format(statisticsSign.getSignTime()));
                }
//                int location = 6;
//                if (statisticsSign.getOrgParentNames() != null) {
//                    parentNames = statisticsSign.getOrgParentNames().split("/");
//                    for (int j = 0; j < parentNames.length; j++) {
//                        row.createCell((short) location).setCellValue(parentNames[j]);
//                        location++;
//                    }
//                } else {
//                    row.createCell((short) 6);
//                }
                cell = row.createCell(6);
                cell.setCellValue(statisticsSign.getOrgName() == null ? "" : statisticsSign.getOrgName());
                index++;
                s++;
//                taskDetail(taskContext.getTaskId(), taskName + "签到统计导出数据第" + s + "行成功");
            }
            StringBuffer fileNameSb = new StringBuffer().append("签到明细统计_" + df.format(submitTime)).append(".xls");
            StringBuffer pathfileNameSb = new StringBuffer().append(df.format(submitTime)).append(".xls");
            String fileName = fileNameSb.toString();
            String path = new StringBuffer().append(requestPath).append(pathfileNameSb).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;
    }
}

