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.CertificateUserListVO;
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.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
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.*;

/**
 * @author Ding
 * @className CertificateListExport
 * @description TODO
 * @date 2019/3/20
 **/

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

    private static final Logger LOGGER = LoggerFactory.getLogger(CertificateListExport.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<>();
        if (!res.isAdmin()) {
            orgIds = res.getOrgIds();
        }


        Integer pageNo = 1;
        Integer pageSize = 30;


        Date submitTime = new Date();

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

        List<CertificateUserListVO> resultList = new ArrayList<>();
        //获取下载数据
        try {
            Page<CertificateUserListVO> page = userFeignClients.userRankList
                    (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.userRankList(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.userRankList(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.userRankList(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对象
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("按用户维度获取统计数据");
            HSSFRow row = sheet.createRow(0);

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

            CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 7);
            sheet.addMergedRegion(cra);
            HSSFCell 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, 7);
            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("所在组织架构");

            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++) {
                    CertificateUserListVO certificateUserListVO = resultList.get(i);
                    if (null != certificateUserListVO) {
                        row = sheet.createRow(i + 3);
                        row.createCell(0).setCellValue(null == certificateUserListVO.getUserName() ? "" : certificateUserListVO.getUserName());
                        row.createCell(1).setCellValue(null == certificateUserListVO.getName() ? "" : certificateUserListVO.getName());

                        row.createCell(2).setCellValue(certificateUserListVO.getWorkNum());
                        row.createCell(3).setCellValue(certificateUserListVO.getPosition());

                        row.createCell(4).setCellValue(null == certificateUserListVO.getOrgName() ? "" : certificateUserListVO.getOrgName());
                        row.createCell(5).setCellValue(certificateUserListVO.isAccountState() ? "启用" : "停用");
                        row.createCell(6).setCellValue(null == certificateUserListVO.getTotalCertificate() ? "0" : certificateUserListVO.getTotalCertificate());
                        if (orgNamesMap.get(certificateUserListVO.getOrgId()) != null) {
                            row.createCell(7).setCellValue(orgNamesMap.get(certificateUserListVO.getOrgId()));
                        } else {
                            String orgNames = "";
                            List<String> orgNameList = organizationClient.getChiefOrgNames(certificateUserListVO.getOrgId(), companyId);
                            if (CollectionUtils.isNotEmpty(orgNameList)) {
                                for (String s : orgNameList) {
                                    if (StringUtils.isBlank(orgNames)) {
                                        orgNames = orgNames + s;
                                    } else {
                                        orgNames = orgNames + "/" + s;
                                    }
                                }
                                row.createCell(7).setCellValue(orgNames);
                                orgNamesMap.put(certificateUserListVO.getOrgId(), orgNames);
                            } else {
                                row.createCell(7).setCellValue("--");
                                orgNamesMap.put(certificateUserListVO.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";
    }
}
