package com.dxhy.core.thread;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.api.model.config.Business;
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.service.export.FpzhcxslService;
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 org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 报表发票综合查询导出
 *
 * @author aa
 */
@SuppressWarnings({"AlibabaMethodTooLong", "DuplicatedCode", "FieldCanBeLocal"})
@Slf4j

public class FpzhcxslExportThread extends BaseThread {

    /**
     * 默认要导出第几页的数据
     */
    private final int default_curr = 1;
    /**
     * 默认每页导出多少条数据
     */
    private final int default_size = 5000;
    /**
     * 文件名前缀
     */
    private final String fileNamePrefix = "bbfpzhcxslList";
    /**
     * 文件名后缀
     */
    private final String fileNameSurfix = ".xlsx";
    /**
     * 文件名中间分隔符
     */
    private final String fileSplit = "_";
    /**
     * excel的标题
     */
    private final String title = "发票税率查询税率";
    /**
     * 导出excel的列名
     */
    private String[] titleColumns = {"序号", "发票代码", "发票号码", "数电号码", "发票类型","特定类型", "金额", "税额", "税率"};

    private final IExcelExportlogService exportLogService;

    private final List<TDxExcelExportlog> exportLogs;

    private final FpzhcxslService fpzhcxslService;

    private final FileService fileService;

    private final RabbitMqSender sender;
    private final TabulateRedisServiceImpl tabulateRedisService;

    public FpzhcxslExportThread(IExcelExportlogService exportLogService, List<TDxExcelExportlog> exportLogs,
        FpzhcxslService fpzhcxslService, FileService fileService, RabbitMqSender sender, IFeginWebsocket feginWebsocket,
        TabulateRedisServiceImpl tabulateRedisService) {
        this.exportLogService = exportLogService;
        this.exportLogs = exportLogs;
        this.fpzhcxslService = fpzhcxslService;
        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 kpksrq = prams.getString("kpksrq");
                String kpjsrq = prams.getString("kpjsrq");
                String invoiceType = prams.getString("invoiceType");
                String invoiceSource = prams.getString("invoiceSource");
                String qszt = prams.getString("qszt");
                String rzzt = prams.getString("rzzt");
                String invoiceStatus = prams.getString("invoiceStatus");
                String invoiceNo = prams.getString("invoiceNo");
                String xfmc = prams.getString("xfmc");
                String skssq = prams.getString("skssq");
                String rzksrq = prams.getString("rzksrq");
                String rzjsrq = prams.getString("rzjsrq");
                String qsfs = prams.getString("qsfs");
                String qsksrq = prams.getString("qsksrq");
                String qsjsrq = prams.getString("qsjsrq");
                String rzhr = prams.getString("rzhr");
                String qsr = prams.getString("qsr");
                String glzt = prams.getString("glzt");
                String rzlx = prams.getString("rzlx");
                String company = prams.getString("company");
                List<Business> businesses = (List<Business>)prams.get("business");
                String inAccountStatus = prams.getString("inAccountStatus");
                // 参数转换为需要的形式
                Map<String, Object> pramsMap = new HashMap<>(31);
                pramsMap.put("dbName", dbName);
                pramsMap.put("business", businesses);
                List<String> gfshList = new ArrayList<>();
                if (!StringHelper.isBlank(gfsh)) {
                    gfshList = StringHelper.stringToList(gfsh);
                    pramsMap.put("gfsh", gfshList);
                } else {
                    pramsMap.put("gfsh", gfshList);
                }
                if (!StringHelper.isBlank(invoiceType)) {
                    if (!"99".equals(invoiceType)) {
                        pramsMap.put("invoiceType", invoiceType);
                    }
                }
                if (invoiceSource != null) {
                    if (!"99".equals(invoiceSource)) {
                        pramsMap.put("invoiceSource", invoiceSource);
                    }
                }
                if (!StringHelper.isBlank(qszt)) {
                    if (!"99".equals(qszt)) {
                        pramsMap.put("qszt", qszt);
                    }
                }
                if (!StringHelper.isBlank(rzzt)) {
                    if (!"99".equals(rzzt)) {
                        pramsMap.put("rzzt", rzzt);
                    }
                }
                if (!StringHelper.isBlank(invoiceStatus)) {
                    if (!"99".equals(invoiceStatus)) {
                        pramsMap.put("invoiceStatus", invoiceStatus);
                    }
                }
                if ("1".equals(rzzt) || "2".equals(rzzt) || "3".equals(rzzt)) {
                    if (!StringHelper.isBlank(skssq)) {
                        pramsMap.put("skssq", skssq.replace("-", ""));
                    }
                    if (!StringHelper.isBlank(rzksrq)) {
                        pramsMap.put("rzksrq", DateUtils.getMorning(DateUtils.strToDate(rzksrq)));
                    }
                    if (!StringHelper.isBlank(rzjsrq)) {
                        pramsMap.put("rzjsrq", DateUtils.getNight(DateUtils.strToDate(rzjsrq)));
                    }

                }
                if ("1".equals(qszt)) {
                    if (!"99".equals(qsfs)) {
                        pramsMap.put("qsfs", qsfs);
                    }
                    if (!StringHelper.isBlank(qsjsrq)) {
                        pramsMap.put("qsksrq", DateUtils.getMorning(DateUtils.strToDate(qsksrq)));
                    }
                    if (!StringHelper.isBlank(qsjsrq)) {
                        pramsMap.put("qsjsrq", DateUtils.getNight(DateUtils.strToDate(qsjsrq)));
                    }
                    if (!"99".equals(prams.getString("businessCode"))) {
                        pramsMap.put("businessCode", prams.getString("businessCode"));
                    }
                }
                pramsMap.put("kpksrq", DateUtils.getMorning(DateUtils.strToDate(kpksrq)));
                pramsMap.put("kpjsrq", DateUtils.getNight(DateUtils.strToDate(kpjsrq)));

                if (!StringHelper.isBlank(invoiceNo)) {
                    if(invoiceNo.length()==8){
                        pramsMap.put("invoiceNo", invoiceNo);
                    }else {
                        pramsMap.put("eleInvoiceNo", invoiceNo);
                    }
                }

                //入账属期
                if(ObjectUtils.isNotEmpty(prams.get("fprzsq"))){
                    pramsMap.put("fprzsq", prams.get("fprzsq").toString().replace("-", ""));
                }
                //tdyslxDm直接用
                if(StringUtils.isNotBlank(prams.get("tdyslxDm").toString())){
                    pramsMap.put("tdyslxDm", prams.get("tdyslxDm"));
                }

                //fprzAuthStatus 局端入账状态   未入账0 已入账1
                if(StringUtils.isNotBlank(prams.get("fprzAuthStatus").toString())){
                    pramsMap.put("fprzAuthStatus", prams.get("fprzAuthStatus"));
                }


                pramsMap.put("rzhr", rzhr);
                pramsMap.put("xfmc", xfmc);
                pramsMap.put("qsr", qsr);
                pramsMap.put("xfsh", prams.getString("xfsh"));
                pramsMap.put("amountMin", prams.getString("amountMin"));
                pramsMap.put("amountMax", prams.getString("amountMax"));
                pramsMap.put("taxAmountMin", prams.getString("taxAmountMin"));
                pramsMap.put("taxAmountMax", prams.getString("taxAmountMax"));
                pramsMap.put("voucherNumber", prams.getString("voucherNumber"));
                if (!StringHelper.isBlank(rzlx) && !"99".equals(rzlx)) {
                    pramsMap.put("rzlx", rzlx);
                }
                if (!StringHelper.isBlank(glzt)) {
                    if (!"99".equals(glzt)) {
                        pramsMap.put("glzt", glzt);
                    }
                }
                pramsMap.put("company", company);
                if (StringUtils.isNotBlank(inAccountStatus)) {
                    pramsMap.put("inAccountStatus", inAccountStatus);
                    titleColumns = new String[] {"序号", "打款状态", "发票代码", "发票号码","数电号码", "发票类型","业务类型", "金额", "税额", "税率"};
                }
                // 导出文件名
                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());

                // 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) throws Exception {
        // 查询指定页数的数据
        JSONObject pageData = fpzhcxslService.selectByPramsMap(pramsMap, curr, default_size);
        boolean hasNext = pageData.getBooleanValue("hasNext");
        List<String[]> dataList = (List<String[]>)pageData.get("datalist");
        boolean firstPage = false;
        if (curr == default_curr) {
            firstPage = true;
        }

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

    }
}
