package com.yizhi.application.report.exam;

import com.baomidou.mybatisplus.plugins.Page;
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.exam.application.feign.ExamReportClient;
import com.yizhi.exam.application.vo.ExamCountByUserVO;
import com.yizhi.exam.application.vo.report.ReportExamAccountVO;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;

/**
 * @Auther: dingxiaowei
 * @Date: 2018/8/10 15:56
 * @Description:按用户统计报表导出excel
 */
@Component
public class AccountGroupExport extends AbstractDefaultTask<String, Map<String, Object>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccountGroupExport.class);

    @Autowired
    ExamReportClient examReportClient;


    @Override
    protected String execute(Map<String, Object> map) {
        String uploadUrl = null;
        Long accountId = (Long) map.get("accountId");
        Long siteId = (Long) map.get("siteId");
        Long companyId = (Long) map.get("companyId");
        Date comitTime = new Date();
        Long taskId = (Long) map.get("taskId");
        String serialNo = (String) map.get("serialNo");
        String taskName = (String) map.get("taskName");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
        TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, accountId, comitTime, siteId, companyId);
        working(taskContext);
        Integer pageNo = 1;
        Integer pageSize = 30;
        ExamCountByUserVO vo = (ExamCountByUserVO) map.get("vo");
        vo.setSiteId(siteId);
        vo.setPageNo(pageNo);
        vo.setPageSize(pageSize);
        Page<ReportExamAccountVO> page = examReportClient.getExamAccountGroup(vo);
        List<ReportExamAccountVO> list = new ArrayList<>();
        //分页查询
        if (page != null) {
            list.addAll(page.getRecords());
        }
        Integer total = page.getTotal();
        if (total > pageSize) {
            Integer pageCount = total / pageSize;
            if (pageCount.equals(1)) {
                vo.setPageNo(2);
                page = examReportClient.getExamAccountGroup(vo);
                list.addAll(page.getRecords());
            } else {
                for (int i = 2; i <= pageCount; i++) {
                    vo.setPageNo(i);
                    page = examReportClient.getExamAccountGroup(vo);
                    list.addAll(page.getRecords());
                }
                if ((pageCount * pageSize) < total) {
                    vo.setPageNo(pageCount + 1);
                    page = examReportClient.getExamAccountGroup(vo);
                    list.addAll(page.getRecords());
                }
            }
        }


        try {
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("按用户统计报表");
            HSSFRow row = sheet.createRow(0);

//            HSSFCellStyle style = wb.createCellStyle();
//            style.setAlignment(HorizontalAlignment.CENTER);

            CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 7);
            sheet.addMergedRegion(cra);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("按用户统计报表结果");
//            cell.setCellStyle(style);

            row = sheet.createRow(1);
            cra = new CellRangeAddress(1, 1, 0, 7);
            sheet.addMergedRegion(cra);
            cell = row.createCell(0);
            cell.setCellValue("统计周期:" + vo.getStartTime()
                    + "~" + vo.getEndTime());

            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("所在部门");

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    row = sheet.createRow(i + 3);
                    row.createCell(0).setCellValue(list.get(i).getAccountName());
                    row.createCell(1).setCellValue(list.get(i).getAccountFullName());
                    row.createCell(2).setCellValue(list.get(i).getTotalAsk());
                    row.createCell(3).setCellValue(list.get(i).getTotalIn());
                    row.createCell(4).setCellValue(list.get(i).getTotalPass());
                    row.createCell(5).setCellValue(list.get(i).getTotalFail());
                    if (list.get(i).getAccountState() != null) {
                        if (list.get(i).getAccountState() == 1) {
                            row.createCell(6).setCellValue("启用");
                        } else {
                            row.createCell(6).setCellValue("停用");
                        }
                    }
                    row.createCell(7).setCellValue(list.get(i).getPassRate() + "%");
                    row.createCell(8).setCellValue(list.get(i).getOrgName());

                }
            }


            String fileName = "按用户统计报表" + sdf2.format(comitTime) + ".xls";
//            String requestPath = "/Users/dingxiaowei/aaa";
            String requestPath = FileConstant.SAVE_PATH;
            File fileDir = new File(requestPath);
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }
            String path = requestPath + "/" + fileName;
            FileOutputStream os = null;
            File file = null;
            try {
                os = new FileOutputStream(path);
                wb.write(os);
                uploadUrl = OssUpload.upload(path, fileName);
                file = new File(path);
                success(taskContext, "成功", uploadUrl);
            } catch (Exception e1) {
                e1.printStackTrace();
                fail(taskContext, "按用户统计报表下载写入过程发生错误");
                LOGGER.error("按用户统计报表下载写入过程发生错误");
            } finally {
                if (os != null) {
                    os.close();
                }
                if (wb != null) {
                    wb.close();
                }
                if (file != null) {
                    file.delete();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            fail(taskContext, "按用户统计报表下载出现错误");
            LOGGER.error("按用户统计报表下载出现错误");
        }

        return uploadUrl;
    }
}
