package com.yizhi.application.report.certificate;

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.certificate.application.feign.CertificateUserFeignClients;
import com.yizhi.certificate.application.vo.TrUserCertificateDetailsVo;
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.system.application.system.remote.OrganizationClient;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
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 CertificateListExport
 * @description TODO
 * @date 2019/3/20
 **/

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

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

    @Autowired
    private CertificateUserFeignClients userFeignClients;

    @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");
        String orgNameLike = (String) map.get("orgNameLike");
        String userName = (String) map.get("userName");
        String startDate = (String) map.get("startDate");
        String endDate = (String) map.get("endDate");
        Long companyId = res.getCompanyId();
        Long siteId = res.getSiteId();
        Long accountId = res.getAccountId();

        List<Long> orgIds = new ArrayList<>();


        Integer pageNo = 1;
        Integer pageSize = 30;


        Date submitTime = new Date();

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

        List<TrUserCertificateDetailsVo> resultList = new ArrayList<>();
        //获取下载数据
        try {
            Page<TrUserCertificateDetailsVo> page = userFeignClients.userDetails
                    (startDate, endDate, pageNo, pageSize, siteId, companyId, userName, orgNameLike, orgIds, res.isAdmin(), accountId);
            if (null != page) {
                resultList.addAll(page.getRecords());
            }
            Integer total = page.getTotal();
            if (total > pageSize) {
                Integer pageTotal = total / pageSize;
                if (pageTotal == 1) {
                    page = userFeignClients.userDetails(startDate, endDate, 2, pageSize, siteId, companyId, userName, orgNameLike, orgIds, res.isAdmin(), accountId);
                    if (null != page) {
                        resultList.addAll(page.getRecords());
                    }
                } else {
                    for (int i = 2; i <= pageTotal; i++) {
                        page = userFeignClients.userDetails(startDate, endDate, i, pageSize, siteId, companyId, userName, orgNameLike, orgIds, res.isAdmin(), accountId);
                        if (null != page) {
                            resultList.addAll(page.getRecords());
                        }
                    }
                    if (total % pageSize > 0) {
                        page = userFeignClients.userDetails(startDate, endDate, pageTotal + 1, pageSize, siteId, companyId, userName, orgNameLike, orgIds, res.isAdmin(), accountId);
                        if (null != page) {
                            resultList.addAll(page.getRecords());
                        }
                    }
                }
            }
        } catch (Exception e) {
            fail(taskContext, "积分报表明细下载获取数据出现错误");
            LOGGER.error("积分报表明细下载获取数据出现错误", e);
        }

        try {

            //新建excel对象
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("证书获取明细");
            XSSFRow row = sheet.createRow(0);

            CellStyle cellStyle = workbook.createCellStyle();
            XSSFFont font = workbook.createFont();
            font.setBold(true);
            cellStyle.setFont(font);

            CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 13);
            sheet.addMergedRegion(cra);
            XSSFCell cell = row.createCell(0);
            cell.setCellValue("证书获取明细");
            cell.setCellStyle(cellStyle);

            row = sheet.createRow(1);
            cell = row.createCell(0);
            cell.setCellValue("统计周期：");
            cell.setCellStyle(cellStyle);

            cra = new CellRangeAddress(1, 1, 1, 13);
            sheet.addMergedRegion(cra);


            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            cell = row.createCell(1);
            cell.setCellValue(null != startDate && null != endDate ? startDate + "~" + endDate : "");
            cell.setCellStyle(cellStyle);

            row = sheet.createRow(2);

            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("姓名");
            row.createCell(7).setCellValue("工号");
            row.createCell(8).setCellValue("职务");
            row.createCell(9).setCellValue("所在部门");
            row.createCell(10).setCellValue("是否启用");
            row.createCell(11).setCellValue("获取时间");
            row.createCell(12).setCellValue("到期日期");
            row.createCell(13).setCellValue("所在组织架构");


            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++) {
                    TrUserCertificateDetailsVo detailsVo = resultList.get(i);
                    if (null != detailsVo) {
                        row = sheet.createRow(i + 3);
                        row.createCell(0).setCellValue(detailsVo.getCertificateId().toString());
                        row.createCell(1).setCellValue(detailsVo.getCertificateTitle());
                        row.createCell(2).setCellValue(detailsVo.getIssuer());
                        if (detailsVo.getBizdType() == 0) {
                            row.createCell(3).setCellValue("培训项目");
                        } else if (detailsVo.getBizdType() == 1) {
                            row.createCell(3).setCellValue("课程");
                        }

                        if (detailsVo.getBizdType() == 0) {
                            row.createCell(4).setCellValue(detailsVo.getTrainingProjectName() + "/" + detailsVo.getTpPlanName());
                        } else {
                            row.createCell(4).setCellValue(detailsVo.getTpPlanName());
                        }
                        row.createCell(5).setCellValue(null == detailsVo.getUserName() ? "" : detailsVo.getUserName());
                        row.createCell(6).setCellValue(null == detailsVo.getFullName() ? "" : detailsVo.getFullName());
                        row.createCell(7).setCellValue(null == detailsVo.getWorkNum() ? "" : detailsVo.getWorkNum());
                        row.createCell(8).setCellValue(null == detailsVo.getPosition() ? "" : detailsVo.getPosition());
                        row.createCell(9).setCellValue(null == detailsVo.getOrgName() ? "" : detailsVo.getOrgName());
                        row.createCell(10).setCellValue(detailsVo.getAccountState() == 1 ? "启用" : "停用");

                        row.createCell(11).setCellValue(sdf.format(detailsVo.getCreateTime()));

                        if (null != detailsVo.getType() && detailsVo.getType() == 0) {
                            row.createCell(12).setCellValue("长期有效");
                        } else {
                            row.createCell(12).setCellValue(sdf.format(detailsVo.getEndTime()));
                        }

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

            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "证书获取明细" + sdf1.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, "成功导出" + resultList.size() + "条记录", 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, "证书获取明细创建excel出现错误");
            LOGGER.error("证书获取明细创建excel出现错误", e);
        }
        return "ok";
    }
}
