package com.yizhi.application.report.research;

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.research.application.feign.ResearchReportClient;
import com.yizhi.research.application.vo.domain.ResearchVo;
import com.yizhi.research.application.vo.domain.StatisticsResearchVo;
import com.yizhi.statistics.application.entity.StatisticsResearch;
import org.apache.poi.hssf.usermodel.*;
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 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 DownloadResearch extends AbstractDefaultTask<String, Map<String, Object>> {

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

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    @Autowired
    private ResearchReportClient researchReportClient;

    @Override
    protected String execute(Map<String, Object> map) {
        ResearchVo research = (ResearchVo) map.get("research");
        RequestContext context = (RequestContext) map.get("context");
        String startDate = (String) map.get("startDate");
        String endDate = (String) map.get("endDate");
        String orgNameorOrgCode = (String) map.get("orgNameorOrgCode");
        String accountName = (String) map.get("accountName");
        Integer joinState = (Integer) map.get("joinState");
        String taskName = (String) map.get("taskName");
        String serialNo = (String) map.get("serialNo");
        Long taskId = (Long) map.get("taskId");

        Date submitTime = new Date();
        TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, context.getAccountId(), submitTime, context.getSiteId(), context.getCompanyId());
        working(taskContext);

        int pageNo = 1;
        int pageSize = 20;
        Integer pageTotal = researchReportClient.researchViewCount(startDate, endDate, research.getId(), orgNameorOrgCode, accountName, joinState);
        int pageCount = (int) Math.ceil(Double.valueOf(pageTotal) / pageSize);
        List<StatisticsResearchVo> list = new ArrayList<>();
        List<StatisticsResearchVo> listOne;
        for (int i = 0; i < pageCount; i++) {
            listOne = researchReportClient.researchViews(startDate, endDate, research.getId(), orgNameorOrgCode, accountName, joinState, pageNo, pageSize);
            list.addAll(listOne);
            pageNo++;
        }

        String upLoadUrl = null;
        String requestPath = FileConstant.SAVE_PATH;
        //String requestPath= "E\\";
        File fileDir = new File(requestPath);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }

        //excel生成：excel-sheet-row-cell
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(research.getName() + "_" + dateFormat.format(submitTime));
        // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short,
        // 创建第1行
        HSSFRow row = sheet.createRow((int) 0);
        //创建单元格格式
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.LEFT);//创建居左格式

        //合并单元格
        CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 12); // 起始行, 终止行, 起始列, 终止列
        sheet.addMergedRegion(cra);
        //合并前6列当做第0行的第0列
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("调研参与人员清单");
        cell.setCellStyle(style);

        //创建第2行
        row = sheet.createRow((int) 1);
        CellRangeAddress cra1 = new CellRangeAddress(1, 1, 0, 12); // 起始行, 终止行, 起始列, 终止列
        sheet.addMergedRegion(cra1);
        cell = row.createCell((short) 0);
        cell.setCellValue("统计周期:" + startDate + "～" + endDate);
        cell.setCellStyle(style);

        //创建第三行
        row = sheet.createRow((int) 2);
        row.createCell((short) 0).setCellValue("用户名");
        row.createCell((short) 1).setCellValue("姓名");
        row.createCell((short) 5).setCellValue("所在部门");
        row.createCell((short) 2).setCellValue("是否完成");
        row.createCell((short) 3).setCellValue("提交时间");
        row.createCell((short) 4).setCellValue("用户状态");
        Integer state;
        String finish = "";
        String accountState = "";
        StatisticsResearchVo statisticsResearch;
        String[] parentNames;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        try {
            //for循环为每一行设值
            int size;
            int s = 0;
            for (int i = 0; i < list.size(); i++) {
                size = 0;
                statisticsResearch = list.get(i);
                if (statisticsResearch == null) {
                    i--;
                    continue;
                }
                row = sheet.createRow((int) i + 3);
                cell = row.createCell((short) size);
                if (statisticsResearch.getAccountName() != null) {
                    cell.setCellValue(statisticsResearch.getAccountName());
                }
                size++;
                cell = row.createCell((short) size);
                if (statisticsResearch.getAccountFullName() != null) {
                    cell.setCellValue(statisticsResearch.getAccountFullName());
                }
                state = statisticsResearch.getJoinState();
                if (state == null || state == 0) {
                    finish = "否";
                } else {
                    finish = "是";
                }
                size++;
                row.createCell((short) size).setCellValue(finish);
                size++;
                row.createCell((short) size);
                if (statisticsResearch.getFinishTime() != null) {
                    row.getCell((short) size).setCellValue(sdf.format(statisticsResearch.getFinishTime()));
                }

                if (statisticsResearch.getAccountState() != null && statisticsResearch.getAccountState() == 1) {
                    accountState = "启用";
                } else {
                    accountState = "禁用";
                }
                size++;
                row.createCell((short) size).setCellValue(accountState);
                size++;

                if (statisticsResearch.getOrgName() != null) {
                    cell = row.createCell((short) size);
                    cell.setCellValue(statisticsResearch.getOrgName());
                } else {
                    row.createCell((short) size);
                }
                s++;
//                taskDetail(taskContext.getTaskId(), research.getName() + "导出数据第" + s + "行成功");
            }
            //导出

            StringBuffer fileNameSb = new StringBuffer().append(research.getName() + "参与人员统计_" + dateFormat.format(submitTime)).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, research.getName() + "导出过程中发生错误，请查看日志");
            logger.error("创建Excel的过程中发生错误");
        }
        return upLoadUrl;
    }

}
