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.report.ReportExamAccountViewVo;
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/12 10:09
 * @Description:按用户统计-查看excel导出
 */
@Component
public class AccountGroupViewExport extends AbstractDefaultTask<String, Map<String, Object>> {

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

    @Autowired
    ExamReportClient examReportClient;

    @Override
    protected String execute(Map<String, Object> map) {
        String uploadUrl = null;

        Long accountId = (Long) map.get("accountId");
        String startTime = (String) map.get("startTime");
        String endTime = (String) map.get("endTime");
        Integer pageNo = 1;
        Integer pageSize = 30;
        Long ACCOUNTID = (Long) map.get("ACCOUNTID");
        Long siteId = (Long) map.get("siteId");
        Long companyId = (Long) map.get("companyId");
        String examNameLike = (String) map.get("examNameLike");
        Date comitTime = new Date();
        Long taskId = (Long) map.get("taskId");
        String serialNo = (String) map.get("serialNo");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String taskName = (String) map.get("taskName");
        TaskContext taskContext = new TaskContext(taskId, serialNo, taskName,
                ACCOUNTID, comitTime, siteId, companyId);
        working(taskContext);
        Page<ReportExamAccountViewVo> page = examReportClient.getExamAccountGroupView(accountId, startTime, endTime, examNameLike, pageNo, pageSize);
        List<ReportExamAccountViewVo> 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)) {
                pageNo = 2;
                page = examReportClient.getExamAccountGroupView(accountId, startTime, endTime, examNameLike, pageNo, pageSize);
                list.addAll(page.getRecords());
            } else {
                for (int i = 2; i <= pageCount; i++) {
                    pageNo = i;
                    page = examReportClient.getExamAccountGroupView(accountId, startTime, endTime, examNameLike, pageNo, pageSize);
                    list.addAll(page.getRecords());
                }
                if ((pageCount * pageSize) < total) {
                    pageNo = pageCount + 1;
                    page = examReportClient.getExamAccountGroupView(accountId, startTime, endTime, examNameLike, pageNo, pageSize);
                    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("统计周期:" + startTime + "~" + endTime);
//            cell.setCellStyle(style);

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

            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).getExamName());
                if (list.get(i).getState().equals("1")) {
                    row.createCell(3).setCellValue("已参加");
                } else {
                    row.createCell(3).setCellValue("未参加");
                }
                row.createCell(4).setCellValue(list.get(i).getScore().doubleValue());
                if (list.get(i).getResult().equals("1")) {
                    row.createCell(5).setCellValue("通过");
                } else if (list.get(i).getResult().equals("0")) {
                    row.createCell(5).setCellValue("不通过");
                } else {
                    row.createCell(5).setCellValue("--");
                }
                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).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 e2) {
                e2.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;
    }
}
