package com.dxhy.core.thread;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.api.model.excelExport.TDxExcelExportlog;
import com.dxhy.common.rabbitmq.RabbitMqSender;
import com.dxhy.common.service.impl.TabulateRedisServiceImpl;
import com.dxhy.common.util.ExcelPoiUtil;
import com.dxhy.common.util.ExceptionUtil;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.core.feign.IFeginWebsocket;
import com.dxhy.core.model.FpRzRespVO;
import com.dxhy.core.service.export.CpyGxCustomsExportService;
import com.dxhy.core.service.singletable.IExcelExportlogService;
import com.dxhy.core.util.JsonResponseUtils;
import com.dxhy.oss.service.FileService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @Description 成品油勾选页面导出--缴款书
* @Author wangruwei
* @Date 2024/7/17 14:43
**/

@SuppressWarnings("AlibabaMethodTooLong")
@Slf4j

public class CpyGxCustomsExportThread extends BaseThread {

    /**
     * 默认要导出第几页的数据
     */
    private final int default_curr = 1;
    /**
     * 默认每页导出多少条数据
     */
    private final int default_size = 5000;
    /**
     * 文件名前缀
     */
    private final String fileNamePrefix = "cpygxCustomsExport";
    /**
     * 文件名后缀
     */
    private final String fileNameSurfix = ".xlsx";
    /**
     * 文件名中间分隔符
     */
    private final String fileSplit = "_";
    /**
     * excel的标题
     */
    private final String title = "缴款书库存勾选";
    /**
     * 导出excel的列名
     */

    private final IExcelExportlogService exportLogService;

    private final List<TDxExcelExportlog> exportLogs;

    private final CpyGxCustomsExportService cpyGxCustomsExportService;

    private final FileService fileService;

    private final RabbitMqSender sender;
    private final TabulateRedisServiceImpl tabulateRedisService;

    public CpyGxCustomsExportThread(IExcelExportlogService exportLogService, List<TDxExcelExportlog> exportLogs,
                                    CpyGxCustomsExportService cpyGxCustomsExportService, FileService fileService, RabbitMqSender sender, IFeginWebsocket feginWebsocket,
                                    TabulateRedisServiceImpl tabulateRedisService) {

        this.exportLogService = exportLogService;
        this.exportLogs = exportLogs;
        this.cpyGxCustomsExportService = cpyGxCustomsExportService;
        this.fileService = fileService;
        this.sender = sender;
        this.feginWebsocket = feginWebsocket;
        this.tabulateRedisService = tabulateRedisService;
    }

    private final IFeginWebsocket feginWebsocket;

    @Override
    public void run() {
        for (TDxExcelExportlog exportLog : exportLogs) {
            // 日志表主键
            Long id = exportLog.getId();
            String userid = exportLog.getUserAccount();
            String userName = exportLog.getUserName();
            // 导出条件
            String condition = exportLog.getConditions();
            // 数据源名称
            String dbName = exportLog.getDbName();
            if (StringHelper.isBlank(dbName)) {
                dbName = "";
            }
            String createDate = DateUtils.dateToStrLong(exportLog.getCreateDate());

            JSONObject msg = new JSONObject();

            // 捕获异常，防止某一条日志导出出错，影响其它日志的导出
            try {
                exportLogService.updateStart(id, dbName);

                // 应该保存的参数
                Map<String,Object> map = JSONObject.parseObject(condition,Map.class);
                Map<String,Object> pramsMap = selConditionDeal(map);

                String company = (String)map.get("company");
                String menuId = (String)map.get("menuId");

                pramsMap.put("company", company);
                pramsMap.put("menuId", menuId);

                JSONObject jsonObject = tabulateRedisService.getTabulateExcel(company, menuId);

                // 导出文件名
                StringBuilder ftpFileName = new StringBuilder();
                ftpFileName.append(userid);
                ftpFileName.append(fileSplit);
                ftpFileName.append(fileNamePrefix);
                ftpFileName.append(fileSplit);
                ftpFileName.append(DateUtils.getStringDateShort());
                ftpFileName.append(fileSplit);
                ftpFileName.append((new Date()).getTime());
                ftpFileName.append(fileNameSurfix);

                // 本地文件存储路径
                StringBuilder excelFile = new StringBuilder();
                excelFile.append(fileService.getLocalPathDefault());
                excelFile.append(ftpFileName.toString());

                // 递归导出数据到excel
                this.cicleExport(pramsMap, default_curr, excelFile.toString(), jsonObject);

                // FTP文件存储路径
                String[] toDay = DateUtil.today().split("-");
                String ftpFilePath = fileService.getPathPrefix() + userName + "/" + "excelFile/" + toDay[0] + "/"
                    + toDay[1] + "/" + toDay[2] + "/" + ftpFileName.toString();
                // 文件上传ftp
                fileService.uploadFile(ftpFilePath, excelFile.toString());

                String titleEnd = "";
                String tabNum = pramsMap.get("tabNum").toString();
                if("0".equals(tabNum)){
                    titleEnd = "(未勾选)";
                }
                if("1".equals(tabNum)){
                    titleEnd = "(勾选中)";
                }
                if("2".equals(tabNum)){
                    titleEnd = "(已勾选)";
                }
                if("3".equals(tabNum)){
                    titleEnd = "(勾选失败)";
                }
                if("4".equals(tabNum)){
                    titleEnd = "(全部)";
                }

                // 设置成功消息内容
                msg.put("title", super.getSuccTitle(title+titleEnd));
                msg.put("content", super.getSuccContent(createDate));
                msg.put("url", super.getUrl(id));
                msg.put("useraccount", userName);

                // 记录导出完成状态
                exportLogService.updateSucc(id, ftpFilePath, dbName);

            } catch (Exception e) {
                String errmsg = ExceptionUtil.getExceptionDeteil(e, 4000);
                // 设置失败消息内容
                msg.put("title", super.getFailTitle(title));
                msg.put("content", super.getFailContent(createDate, errmsg));
                msg.put("url", "");
                msg.put("useraccount", userName);

                log.error("", e);
                // 记录导出出错状态
                exportLogService.updateFail(id, errmsg, dbName);
            } finally {
                // 发送导出消息到mq
                String responseResult = JsonResponseUtils.responseResult(msg);
                sender.sendToMsg(responseResult);

                // 申请成功后像websocket发送申请信息
                feginWebsocket.setMessageToWebsocket(userName);
            }
        }
    }

    /**
     * @Description 处理勾选条件
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     * @Author wangruwei
     * @Date 2024/7/16 19:23
     **/
    private Map<String, Object> selConditionDeal(Map<String, Object> pramsMap) {
        //tab选择 tabNum 未勾选0  勾选中1  已勾选2  勾选失败3  全部4
        if(ObjectUtil.isNotEmpty(pramsMap.get("tabNum"))){
            pramsMap.put("tabNum", pramsMap.get("tabNum").toString());
        }

        String gfsh = (String)pramsMap.get("gfsh");
        List<String> gfshList = new ArrayList<>();
        if (!StringHelper.isBlank(gfsh)) {
            gfshList = StringHelper.stringToList(gfsh);
            pramsMap.put("gfsh", gfshList);
        } else {
            pramsMap.put("gfsh", gfshList);
        }
        //缴款书号码 customsCode
        //填发日期起 fillInStartDate
        if (pramsMap.get("fillInStartDate") != null && !"".equals(pramsMap.get("fillInStartDate"))) {
            pramsMap.put("fillInStartDate",
                    DateUtils.getMorning(DateUtils.strToDate(pramsMap.get("fillInStartDate").toString())));
        }
        //填发日期止 fillInEndDate
        if (pramsMap.get("fillInEndDate") != null && !"".equals(pramsMap.get("fillInEndDate"))) {
            pramsMap.put("fillInEndDate",
                    DateUtils.getNight(DateUtils.strToDate(pramsMap.get("fillInEndDate").toString())));
        }

        //重号锁定 sfchsd
        if(ObjectUtil.isNotEmpty(pramsMap.get("sfchsd"))&&!"99".equals(pramsMap.get("sfchsd"))){
            pramsMap.put("sfchsd", pramsMap.get("sfchsd").toString());
        }else{
            pramsMap.put("sfchsd", "");
        }

        return pramsMap;
    }


    /**
     * 递归导出数据到excel文件，防止jvm oom
     *
     * @param pramsMap
     *            查询数据参数集合
     * @param curr
     *            当前第几页
     * @param excelFile
     *            导出的文件
     * @throws Exception
     *
     */

    private boolean cicleExport(Map<String, Object> pramsMap, int curr, String excelFile, JSONObject jsonObject)
        throws Exception {
        // 查询指定页数的数据
        JSONObject pageData = cpyGxCustomsExportService.selectByPramsMap(pramsMap, curr, default_size);
        boolean hasNext = pageData.getBooleanValue("hasNext");
        List<FpRzRespVO> dataList = (List<FpRzRespVO>)pageData.get("datalist");
        boolean firstPage = false;
        if (curr == default_curr) {
            firstPage = true;
        }

        // 数据不是最后一页
        if (hasNext) {
            int nextPage = pageData.getIntValue("nextPage");
            // 写入当前页数据
            ExcelPoiUtil.exportListArrayToExcel1(excelFile, title, jsonObject, dataList, firstPage, false);
            // 更新页数
            return cicleExport(pramsMap, nextPage, excelFile, jsonObject);
        } else {
            // 写入最后一页数据
            ExcelPoiUtil.exportListArrayToExcel1(excelFile, title, jsonObject, dataList, firstPage, true);
            return hasNext;
        }

    }
}
