package com.yizhi.application.point.util;

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.course.util.OssUpload;
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.point.application.feign.PointUserFeignClients;
import com.yizhi.point.application.vo.PointUserListVO;
import com.yizhi.point.application.vo.PointUserParamVO;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.OrganizationClient;
import com.yizhi.system.application.system.remote.ReportClient;
import com.yizhi.system.application.vo.ReportAccountRespVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

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

    private static final Logger LOG = LoggerFactory.getLogger(PointUserExport.class);

    @Value("${ACTIVE}")
    public String active;

    @Autowired
    private PointUserFeignClients pointUserClients;
    @Autowired
    AccountClient accountClient;
    @Autowired
    private ReportClient reportClient;
    @Autowired
    private OrganizationClient organizationClient;

    @Override
    protected String execute(Map<String, Object> paramMap) {
        String upload = null;
        PointUserParamVO vo = (PointUserParamVO) paramMap.get("vo");
        Long taskId = (Long) paramMap.get("taskId");
        String serialNo = (String) paramMap.get("serialNo");
        String taskName = (String) paramMap.get("taskName");
        Date startAt = (Date) paramMap.get("startAt");
        Date endAt = (Date) paramMap.get("endAt");
        Long accountId = vo.getAccountId();
        Long siteId = vo.getSiteId();
        Long companyId = vo.getCompanyId();
        Date submitTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

        Timestamp timestamp = pointUserClients.getStartDate();
        String startTime = sdf.format(timestamp);
        String endTime = sdf.format(submitTime);

        if (startAt != null && endAt != null) {
            startTime = sdf.format(startAt);
            endTime = sdf.format(endAt);
        }
        //创建任务
        TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, accountId, submitTime, siteId, companyId);//任务id   任务名字   操作人id  操作时间
        working(taskContext);

        List<ReportAccountRespVO> accountVOList = null;
        Integer pageNo = 1;
        Integer pageSize = 30;
        vo.setPageSize(pageSize);
        vo.setPageNo(pageNo);
        vo.setStartAt(startAt);
        vo.setEndAt(endAt);
        Page<PointUserListVO> page = pointUserClients.userRankList(vo);
        List<PointUserListVO> list = new ArrayList<>();
        //分页查询
        if (page != null && page.getRecords().size() > 0) {
            list.addAll(page.getRecords());
        }
        Integer total = page.getTotal();
        if (total > pageSize) {
            Integer pageCount = total / pageSize;
            if (pageCount == 1) {
                pageNo = 2;
                vo.setPageNo(2);
                page = pointUserClients.userRankList(vo);
                list.addAll(page.getRecords());
            } else {
                for (int i = 2; i <= pageCount; i++) {
                    vo.setPageNo(i);
                    page = pointUserClients.userRankList(vo);
                    list.addAll(page.getRecords());
                }
                if ((total % pageSize) > 0) {
                    vo.setPageNo(pageCount + 1);
                    page = pointUserClients.userRankList(vo);
                    list.addAll(page.getRecords());
                }
            }
        }
        String title = "积分排名统计";
        String[] headers = new String[]{"用户名", "姓名", "邮箱", "总积分", "用户当前状态", "所在部门", "所在组织架构"};
        StringBuffer fileNameSb = new StringBuffer().append(title).append(sdf1.format(System.currentTimeMillis())).append(".xls");
        String fileName = fileNameSb.toString();
        StringBuffer pathSb = new StringBuffer().append(FileConstant.SAVE_PATH).append("/point/");
//         StringBuffer pathSb = new StringBuffer().append("/Users/dingxiaowei/aaa").append("/point/");
        File fileDir = new File(pathSb.toString());
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        String path = pathSb.append(fileNameSb).toString();

        HSSFWorkbook workBook = null;
        FileOutputStream os = null;
        File file = null;
        try {
            os = new FileOutputStream(path);
            // 创建新的Excel 工作簿
            workBook = new HSSFWorkbook();

            // 在Excel工作簿中建一工作表，其名为缺省值
            HSSFSheet sheet = workBook.createSheet(title);
            sheet.setDefaultColumnWidth(15);
            CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 6);
            sheet.addMergedRegion(cellRangeAddress);

            // 第一行
            HSSFRow row = sheet.createRow(0);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue(new HSSFRichTextString(title));

            //第二行
            row = sheet.createRow(1);
            cell = row.createCell(0);
            cell.setCellValue("统计周期: " + startTime + "~" + endTime);
            // 第三行
            row = sheet.createRow(2);
            for (int i = 0; i < headers.length; i++) {
                row.createCell(i).setCellValue(headers[i]);
            }

            PointUserListVO puvo = null;
            Map<Long, String> orgNamesMap = new HashMap<>(16);
            // 填充数据
            if (CollectionUtils.isNotEmpty(list)) {
                for (int i = 0; i < list.size(); i++) {
                    puvo = list.get(i);
                    row = sheet.createRow(3 + i);
                    row.createCell(0).setCellValue(puvo.getUserName());
                    row.createCell(1).setCellValue(puvo.getName());
                    row.createCell(2).setCellValue(puvo.getEmail());
                    row.createCell(3).setCellValue(puvo.getTotalPoint());
                    boolean state = false;
                    state = puvo.isAccountState();
                    if (state) {
                        row.createCell(4).setCellValue("启用");
                    } else {
                        row.createCell(4).setCellValue("停用");
                    }
                    row.createCell(5).setCellValue(puvo.getOrgName());

                    if (null!=puvo.getOrgId()){
                        if (null != orgNamesMap.get(puvo.getOrgId())) {
                            row.createCell(6).setCellValue(orgNamesMap.get(puvo.getOrgId()));
                        }else {
                            String orgNames = "";
                            List<String> orgNamesList = organizationClient.getChiefOrgNames(puvo.getOrgId(), companyId);
                            if (CollectionUtils.isNotEmpty(orgNamesList)){
                                for (String s : orgNamesList){
                                    if (StringUtils.isNotBlank(orgNames)){
                                        orgNames = orgNames + "/" + s;
                                    }else {
                                        orgNames = orgNames + s;
                                    }
                                }
                                row.createCell(6).setCellValue(orgNames);
                                orgNamesMap.put(puvo.getOrgId(), orgNames);
                            }else {
                                row.createCell(6).setCellValue("--");
                                orgNamesMap.put(puvo.getOrgId(), "--");
                            }
                    }
                    }else {
                        row.createCell(6).setCellValue("--");
                    }
                    int n = i + 4;
                    taskDetail(taskId, "导出数据第" + n + "行成功");
                }
            }
            workBook.write(os);
            upload = OssUpload.upload(path, fileName, active);
            file = new File(path);
            success(taskContext, upload);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("写入过程中发生错误");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (workBook != null) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (file != null) {
                file.delete();
            }
        }
        return upload;
    }

}
