package com.yizhi.application.report.customproject;

import com.baomidou.mybatisplus.plugins.Page;
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.custom.api.feign.ExperiencePoolReportClient;
import com.yizhi.custom.api.vo.custom.ExperiencePoolReportExportVo;
import com.yizhi.system.application.system.remote.OrganizationClient;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
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.*;

/**
 * @author Ding
 * @className PoolReportExport
 * @description TODO
 * @date 2018/11/29
 **/
@Component
public class PoolReportExport extends AbstractDefaultTask<String, Map<String, Object>> {

    private static final Logger LOGGER = LoggerFactory.getLogger(PoolReportExport.class);

    @Autowired
    private ExperiencePoolReportClient poolReportClient;

    @Autowired
    private OrganizationClient organizationClient;

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

        RequestContext res = (RequestContext) map.get("res");
        Long taskId = (Long) map.get("taskId");
        String serialNo = (String) map.get("serialNo");
        String taskName = (String) map.get("taskName");
        Long poolId = (Long) map.get("poolId");
        String poolName = (String) map.get("poolName");
        String key = (String) map.get("key");
        String orgName = (String) map.get("orgName");
        Long accountId = res.getAccountId();
        Long companyId = res.getCompanyId();
        Long siteId = res.getSiteId();

        Date submitTime = new Date();

        TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, accountId, submitTime, siteId, companyId);
        working(taskContext);

        try {
            //分页请求获得数据,避免数据过多请求超时
            Integer pageNo = 1;
            Integer pageSize = 1000;
            Page<ExperiencePoolReportExportVo> page;
            page = poolReportClient.viewPoolReportList(poolId, key, orgName, pageNo, pageSize, null, null, null, siteId, res);
            Integer total = page.getTotal();
            LOGGER.info("########################total:" + total);
            List<ExperiencePoolReportExportVo> resultList = new ArrayList<>();
            if (null != page) {
                resultList.addAll(page.getRecords());
            }
            List<ExperiencePoolReportExportVo> list = null;
            if (total > pageSize) {
                Integer pageTotal = total / pageSize;
                if (pageTotal == 1) {
                    pageNo = 2;
                    page = poolReportClient.viewPoolReportList(poolId, key, orgName, pageNo, pageSize, null, null, null, siteId, res);
                    if (null != page) {
                        LOGGER.info("########################total,pageNo,pageSize:" + page.getTotal() + page.getCurrent() + page.getRecords().size());
                        resultList.addAll(page.getRecords());
                    }
                } else if (pageTotal > 1) {
                    for (int i = 2; i <= pageTotal; i++) {
                        pageNo = i;
                        page = poolReportClient.viewPoolReportList(poolId, key, orgName, pageNo, pageSize, null, null, null, siteId, res);
                        if (null != page) {
                            LOGGER.info("########################total,pageNo,pageSize:" + page.getTotal() + page.getCurrent() + page.getRecords().size());
                            resultList.addAll(page.getRecords());
                        }
                    }
                    if (total % pageSize > 0) {
                        pageNo = pageTotal + 1;
                        page = poolReportClient.viewPoolReportList(poolId, key, orgName, pageNo, pageSize, null, null, null, siteId, res);
                        if (null != page) {
                            LOGGER.info("########################total,pageNo,pageSize:" + page.getTotal() + page.getCurrent() + page.getRecords().size());
                            resultList.addAll(page.getRecords());
                        }
                    }
                }
            }


            //新建excel对象
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("经验排名统计");

            //设置格式(水平垂直居中,加粗,字体大小14号)
            XSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            XSSFFont font = workbook.createFont();
            font.setBold(true);
            font.setFontHeightInPoints((short) 14);
            style.setFont(font);

            XSSFRow row = sheet.createRow(0);

            CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 5);
            //表头合并单元格
            sheet.addMergedRegion(cra);
            XSSFCell cell = row.createCell(0);

            //填写表头名
            cell.setCellValue(poolName + "经验排名统计");

            //表头居中
            cell.setCellStyle(style);

            row = sheet.createRow(1);
            row.createCell(0).setCellValue("用户名");
            row.createCell(1).setCellValue("姓名");
            row.createCell(2).setCellValue("所在部门");
            row.createCell(3).setCellValue("邮箱");
            row.createCell(4).setCellValue("总经验值");
            row.createCell(5).setCellValue("等级");
            row.createCell(6).setCellValue("所在组织架构");

            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<Long, String> orgNamesMap = new HashMap<>(16);
            //数据写入excel
            if (CollectionUtils.isNotEmpty(resultList)) {
                LOGGER.info("########################resultList.size:" + resultList.size());
                for (int i = 0; i < resultList.size(); i++) {
                    ExperiencePoolReportExportVo reportExportVo = resultList.get(i);
                    if (null != reportExportVo) {
                        row = sheet.createRow(i + 2);
                        row.createCell(0).setCellValue(null == reportExportVo.getAccountName() ? "" : reportExportVo.getAccountName());
                        row.createCell(1).setCellValue(null == reportExportVo.getAccountFullName() ? "" : reportExportVo.getAccountFullName());
                        row.createCell(2).setCellValue(null == reportExportVo.getOrgName() ? "" : reportExportVo.getOrgName());
                        row.createCell(3).setCellValue(null == reportExportVo.getEmail() ? "" : reportExportVo.getEmail());
                        row.createCell(4).setCellValue(null == reportExportVo.getExperienceTotal() ? 0 : reportExportVo.getExperienceTotal());
                        row.createCell(5).setCellValue(null == reportExportVo.getExperienceLevel() ? "" : reportExportVo.getExperienceLevel());

                        if (null != orgNamesMap.get(reportExportVo.getOrgId())){
                            row.createCell(6).setCellValue(orgNamesMap.get(reportExportVo.getOrgId()));
                        }else {
                            String orgNames = "";
                            List<String> orgNameList = organizationClient.getChiefOrgNames(reportExportVo.getOrgId(), companyId);
                            if (CollectionUtils.isNotEmpty(orgNameList)){
                                for (String s : orgNameList){
                                    if (StringUtils.isNotBlank(orgNames)){
                                        orgNames = orgNames + "/" + s;
                                    }else {
                                        orgNames = orgNames + s;
                                    }
                                }
                                row.createCell(6).setCellValue(orgNames);
                                orgNamesMap.put(reportExportVo.getOrgId(), orgNames);
                            }else {
                                row.createCell(6).setCellValue("--");
                                orgNamesMap.put(reportExportVo.getOrgId(), "--");
                            }
                        }
                    }

                }
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = poolName + "-经验排名统计-" + sdf.format(new Date()) + ".xlsx";
//            String requestPath = "/Users/dingxiaowei/aaa";
            String requestPath = FileConstant.SAVE_PATH;
            //创建目标文件夹
            File fileDir = new File(requestPath);
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }

            String path = requestPath + "/" + fileName;
            String url = null;
            FileOutputStream os = null;
            File file = null;

            //创建文件并上传阿里云,删除本地文件
            try {
                os = new FileOutputStream(path);
                workbook.write(os);
                url = OssUpload.upload(path, fileName);
                file = new File(path);
                success(taskContext, "成功", url);
            } catch (Exception e1) {
                fail(taskContext, "经验统计明细写入过程中出现错误");
                LOGGER.error("经验统计明细写入过程中出现错误", e1);
            } finally {
                if (null != os) {
                    os.close();
                }
                if (null != workbook) {
                    workbook.close();
                }
                if (null != file) {
                    file.delete();
                }
            }
        } catch (Exception e) {
            fail(taskContext, "经验池报表查看下载过程中出现错误");
            LOGGER.error("经验池报表查看下载过程中出现错误", e);
        }
        return null;
    }
}
