package com.dxhy.core.thread;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
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.entity.TDxExcelExportlog;
import com.dxhy.core.feign.IFeginWebsocket;
import com.dxhy.core.rabbitmq.Sender;
import com.dxhy.core.service.export.LqFpycxxService;
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.*;

/**
 * 报表发票综合查询导出
 *
 * @author user
 */

@Slf4j

public class LqFpycxxExportThread extends BaseThread {

    /**
     * 默认要导出第几页的数据
     */
    private final int default_curr = 1;
    /**
     * 默认每页导出多少条数据
     */
    private final int default_size = 5000;
    /**
     * 文件名前缀
     */
    private final String fileNamePrefix = "bbfpzhcxList";
    /**
     * 文件名后缀
     */
    private final String fileNameSurfix = ".xls";
    /**
     * 文件名中间分隔符
     */
    private final String fileSplit = "_";
    /**
     * excel的标题
     */
    private final String title = "异常发票信息";
    /**
     * 导出excel的列名
     */
    private final String[] titleColumns =
        { "开票日期", "发票代码", "发票号码", "税款所属期", "出口转内销证明编号", "勾选时间", "发票状态", "是否异常凭证","锁定状态"};

    private final IExcelExportlogService exportLogService;

    private final List<TDxExcelExportlog> exportLogs;

    private final LqFpycxxService lqFpycxxService;

    private final FileService fileService;

    private final Sender sender;
    private final TabulateRedisServiceImpl tabulateRedisService;

    public LqFpycxxExportThread(IExcelExportlogService exportLogService, List<TDxExcelExportlog> exportLogs,
                                LqFpycxxService lqFpycxxService, FileService fileService, Sender sender, IFeginWebsocket feginWebsocket,
                                TabulateRedisServiceImpl tabulateRedisService) {
        this.exportLogService = exportLogService;
        this.exportLogs = exportLogs;
        this.lqFpycxxService = lqFpycxxService;
        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);

                // 应该保存的参数
                JSONObject prams = JSONObject.parseObject(condition);
                String gfsh = prams.getString("gfsh");
                String skssq = prams.getString("skssq");
                String company = prams.getString("company");
                // 参数转换为需要的形式
                Map<String, Object> pramsMap = new HashMap<>(16);
                pramsMap.put("dbName", dbName);
                List<String> gfshList = new ArrayList<>();
                if (!StringHelper.isBlank(gfsh)) {
                    gfshList = StringHelper.stringToList(gfsh);
                    pramsMap.put("gfsh", gfshList);
                } else {
                    pramsMap.put("gfsh", gfshList);
                }
                pramsMap.put("skssq", skssq);
                pramsMap.put("company", company);
                // 导出文件名
                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());

                List<Map<String,Object>> listAllSheetData = new ArrayList<>();
                Map<String,Object> ycxxMap = new HashMap<String,Object>();
                List<String[]> ycxxlist = new LinkedList();
                // 递归导出数据到excel, 第一个sheet，异常发票信息
                this.cicleExport(pramsMap, default_curr, excelFile.toString(),1,ycxxlist);
                ycxxMap.put("title", title);
                ycxxMap.put("titleColumns",titleColumns);
                ycxxMap.put("data", ycxxlist);
                listAllSheetData.add(ycxxMap);

                Map<String,Object> customYcxxMap = new HashMap<String,Object>();
                List<String[]> customYcxxlist = new LinkedList();
                // 递归导出数据到excel, 第二个sheet，异常发票信息
                this.cicleCusomExport(pramsMap, default_curr, excelFile.toString(),2,customYcxxlist);
                String customTitle = "海关缴款书异常发票";
                String[] customTitleColumns =
                        { "缴款书号码", "填发日期", "出口转内销证明编号", "税款所属期", "勾选时间", "异常状态"};
                customYcxxMap.put("title", customTitle);
                customYcxxMap.put("titleColumns",customTitleColumns);
                customYcxxMap.put("data", customYcxxlist);
                listAllSheetData.add(customYcxxMap);

                ExcelPoiUtil.exportListArrayToExcelBySheetNum(excelFile.toString(), listAllSheetData);

                // 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());

                // 设置成功消息内容
                msg.put("title", super.getSuccTitle(title));
                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 海关缴款书异常信息导出
    * @Author wangruwei
    * @Date 2022/11/30 11:24
    **/
    private boolean cicleCusomExport(Map<String, Object> pramsMap, int curr, String excelFile, int sheetNum, List<String[]> customYcxxlist) throws Exception {
        // 查询指定页数的数据
        JSONObject pageData = lqFpycxxService.selectCustomYcxxByPramsMap(pramsMap, curr, default_size);
        boolean hasNext = pageData.getBooleanValue("hasNext");
        List<String[]> dataList = (List<String[]>)pageData.get("datalist");
        customYcxxlist.addAll(dataList);
        // 数据不是最后一页
        if (hasNext) {
            int nextPage = pageData.getIntValue("nextPage");
            // 更新页数
            return cicleCusomExport(pramsMap, nextPage, excelFile,sheetNum, customYcxxlist);
        } else {
            return hasNext;
        }
    }

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

    private boolean cicleExport(Map<String, Object> pramsMap, int curr, String excelFile, int sheetNum, List<String[]> list) throws Exception {
        // 查询指定页数的数据
        JSONObject pageData = lqFpycxxService.selectByPramsMap(pramsMap, curr, default_size);
        boolean hasNext = pageData.getBooleanValue("hasNext");
        List<String[]> dataList = (List<String[]>)pageData.get("datalist");

        list.addAll(dataList);

        // 数据不是最后一页
        if (hasNext) {
            int nextPage = pageData.getIntValue("nextPage");
            // 更新页数
            return cicleExport(pramsMap, nextPage, excelFile,sheetNum, list);
        } else {
            // 写入最后一页数据
            return hasNext;
        }

    }
}
