package com.dxhy.core.thread;


import com.dxhy.api.model.excelExport.TDxExcelExportlog;
import com.dxhy.core.service.singletable.IExcelExportlogService;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.api.model.config.Business;
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.CustomsRzcxVO;
import com.dxhy.common.rabbitmq.RabbitMqSender;
import com.dxhy.core.service.export.ICustomsCollectService;
import com.dxhy.core.util.JsonResponseUtils;
import com.dxhy.oss.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @author user
 */
@SuppressWarnings({"AlibabaMethodTooLong", "DuplicatedCode", "FieldCanBeLocal"})
@Slf4j

public class CustomsRzcxExportThread extends BaseThread {

    /**
     * 默认要导出第几页的数据
     */
    private final int default_curr = 1;
    /**
     * 默认每页导出多少条数据
     */
    private final int default_size = 5000;
    /**
     * 文件名前缀
     */
    private String fileNamePrefix = "customsRzcxList";
    /**
     * 文件名后缀
     */
    private final String fileNameSurfix = ".xlsx";
    /**
     * 文件名中间分隔符
     */
    private final String fileSplit = "_";
    /**
     * excel的标题
     */
    private String title = "缴款书认证查询";
    /**
     * 导出excel的列名
     */
    private final String[] titleColumns = {"序号", "缴款书号码", "填发日期", "缴款单位名称", "缴款单位税号", "税款金额", "抵扣税款金额", "管理状态", "来源",
        "签收状态", "签收日期", "签收方式", "签收人", "认证时间", "认证状态", "认证处理状态", "认证类型", "认证人", "税款所属期", "撤销认证处理状态", "业务单元"};

    /**
     * 缓存合计数量
     */
    private static String hjsl = "0";
    /**
     * 缓存合计金额
     */
    private static String hjje = "0";
    /**
     * 缓存合计税额
     */
    private static String hjse = "0";

    private final IExcelExportlogService exportLogService;

    private final List<TDxExcelExportlog> exportLogs;

    private final ICustomsCollectService customsCollectService;

    private final FileService fileService;

    private final RabbitMqSender sender;

    private final IFeginWebsocket feginWebsocket;
    private final TabulateRedisServiceImpl tabulateRedisService;

    public CustomsRzcxExportThread(IExcelExportlogService exportLogService, List<TDxExcelExportlog> exportLogs,
        ICustomsCollectService customsCollectService, FileService fileService, RabbitMqSender sender,
        IFeginWebsocket feginWebsocket, TabulateRedisServiceImpl tabulateRedisService) {
        this.tabulateRedisService = tabulateRedisService;
        this.exportLogService = exportLogService;
        this.exportLogs = exportLogs;
        this.customsCollectService = customsCollectService;
        this.fileService = fileService;
        this.sender = sender;
        this.feginWebsocket = 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 customsCode = prams.getString("customsCode");
                String fillInDateStart = prams.getString("fillInDateStart");
                String fillInDateEnd = prams.getString("fillInDateEnd");
                String taxAmountMin = prams.getString("taxAmountMin");
                String taxAmountMax = prams.getString("taxAmountMax");
                String glzt = prams.getString("glzt");
                String qsStatus = prams.getString("qsStatus");
                String rzhYesorno = prams.getString("rzhYesorno");
                String rzlx = prams.getString("rzlx");
                String confirmUser = prams.getString("confirmUser");
                String authStatus = prams.getString("authStatus");
                String qsDateStart = prams.getString("qsDateStart");
                String qsDateEnd = prams.getString("qsDateEnd");
                String rzhDateStart = prams.getString("rzhDateStart");
                String rzhDateEnd = prams.getString("rzhDateEnd");
                String rzhBelongDate = prams.getString("rzhBelongDate");
                List<Business> businesses = (List<Business>)prams.get("business");
                String businessCode = prams.getString("businessCode");
                int ycpbz = prams.getIntValue("ycpbz");
                String company = prams.getString("company");
                String menuId = prams.getString("menuId");
                JSONObject jsonObject = tabulateRedisService.getTabulateExcel(company, menuId);
                // 参数转换为需要的形式
                Map<String, Object> pramsMap = new HashMap<>(30);

                pramsMap.put("dbName", dbName);
                pramsMap.put("business", businesses);
                List<String> gfTaxNoList = new ArrayList<>();
                if (!StringHelper.isBlank(gfsh)) {
                    gfTaxNoList = StringHelper.stringToList(gfsh);
                    pramsMap.put("gfTaxNo", gfTaxNoList);
                    gfsh = null;
                } else {
                    pramsMap.put("gfTaxNo", gfTaxNoList);
                }

                if ("99".equals(glzt)) {
                    glzt = null;
                }
                if (!"1".equals(qsStatus)) {
                    if ("99".equals(qsStatus)) {
                        qsStatus = null;
                    }
                    qsDateStart = null;
                    qsDateEnd = null;
                    pramsMap.put("businessCode", "99");
                }
                pramsMap.put("businessCode", businessCode);
                if (!"1".equals(rzhYesorno) && !"2".equals(rzhYesorno)) {
                    if ("99".equals(rzhYesorno)) {
                        rzhYesorno = null;
                    }
                    rzhBelongDate = null;
                    rzhDateEnd = null;
                    rzhDateStart = null;
                }
                if ("99".equals(rzlx)) {
                    rzlx = null;
                }
                if ("99".equals(authStatus)) {
                    authStatus = null;
                }

                pramsMap.put("gfsh", gfsh);
                pramsMap.put("customsCode", customsCode);
                pramsMap.put("fillInDateStart", DateUtils.getMorning(DateUtils.strToDate(fillInDateStart)));
                pramsMap.put("fillInDateEnd", DateUtils.getNight(DateUtils.strToDate(fillInDateEnd)));
                pramsMap.put("taxAmountMin", taxAmountMin);
                pramsMap.put("taxAmountMax", taxAmountMax);
                pramsMap.put("glzt", glzt);
                pramsMap.put("qsStatus", qsStatus);
                pramsMap.put("rzhYesorno", rzhYesorno);
                pramsMap.put("rzlx", rzlx);
                if(StringUtils.isNotBlank(confirmUser)){
                    pramsMap.put("confirmUser", confirmUser);
                }

                pramsMap.put("authStatus", authStatus);
                pramsMap.put("qsDateStart",
                    StringUtils.isBlank(qsDateStart) ? "" : DateUtils.getMorning(DateUtils.strToDate(qsDateStart)));
                pramsMap.put("qsDateEnd",
                    StringUtils.isBlank(qsDateEnd) ? "" : DateUtils.getNight(DateUtils.strToDate(qsDateEnd)));
                pramsMap.put("rzhDateStart",
                    StringUtils.isBlank(rzhDateStart) ? "" : DateUtils.getMorning(DateUtils.strToDate(rzhDateStart)));
                pramsMap.put("rzhDateEnd",
                    StringUtils.isBlank(rzhDateEnd) ? "" : DateUtils.getNight(DateUtils.strToDate(rzhDateEnd)));
                pramsMap.put("rzhBelongDate", rzhBelongDate);
                pramsMap.put("company", company);
                if (ycpbz == 1) {
                    pramsMap.put("ycpbz", String.valueOf(ycpbz));
                    title = "异常发票采集";
                    fileNamePrefix = "abnormalInvoiceCollectionList";
                }

                // 导出文件名
                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());

                // 设置成功消息内容
                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);
            }
        }
    }

    /**
     * 递归导出数据到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 = customsCollectService.queryRzcxByPage(pramsMap, curr, default_size);
        boolean hasNext = pageData.getBooleanValue("hasNext");
        List<CustomsRzcxVO> dataList = (List<CustomsRzcxVO>)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 false;
        }
    }
}
