package com.dxhy.core.thread;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
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.CustomCellWriteHandler;
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.PoolPaperService;
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.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

//import com.alibaba.excel.metadata.Sheet;
//import com.alibaba.excel.metadata.Table;

/**
 * 功能描述
 *
 * @author 陈刚扬
 * @date 2020/10/30
 */
@SuppressWarnings({"AlibabaMethodTooLong", "DuplicatedCode", "FieldCanBeLocal", "AlibabaUndefineMagicConstant"})

@Slf4j
public class PoolSaleThread extends BaseThread {

    /**
     * 默认要导出第几页的数据
     */
    private final int default_curr = 1;
    /**
     * 默认每页导出多少条数据
     */
    private final int default_size = 5000;
    /**
     * 文件名前缀
     */
    private final String fileNamePrefix = "销项票池";
    /**
     * 文件名后缀
     */
    private final String fileNameSurfix = ".xlsx";
    /**
     * 文件名中间分隔符
     */
    private final String fileSplit = "_";
    /**
     * excel的标题
     */
    private String title = "销项票池";
    /**
     * 导出excel的列名
     */
    private final String[] titleColumns =
        {"序号", "发票类型", "特定业务","发票代码", "发票号码","数电号码",  "发票状态", "开票日期", "源文件PDF", "源文件OFD", "源文件XML",  "购方名称", "购方税号", "金额", "税额", "价税合计", "清单标志", "备注", "优惠政策类型",
            "采集状态", "采集时间", "采集来源", "签收方式", "对接系统", "签收状态", "签收日期", "签收人", "财务入账月份", "财务入账状态", "凭证号", "业务单号", "入池时间"};

    /**
     * 导出excel的列名
     */
    private final String[] detailTitleColumns = {"序号", "发票代码", "发票号码", "货物或应税劳务名称", "规格型号", "单位", "数量", "单价", "金额",
        "税额", "税率", "车牌号", "类型", "通行日期起", "通行日期止", "优惠政策"};

    private WriteSheet writeSheet;
    private WriteTable writeTable;
    private ExcelWriter writer = null;

    private final IExcelExportlogService exportLogService;

    private final List<TDxExcelExportlog> exportLogs;

    private final PoolPaperService poolPaperService;

    private final FileService fileService;

    private final RabbitMqSender sender;

    private final IFeginWebsocket feginWebsocket;
    private final TabulateRedisServiceImpl tabulateRedisService;

    public PoolSaleThread(IExcelExportlogService exportLogService, List<TDxExcelExportlog> exportLogs,
        PoolPaperService poolPaperService, FileService fileService, RabbitMqSender sender, IFeginWebsocket feginWebsocket,
        TabulateRedisServiceImpl tabulateRedisService) {
        this.exportLogService = exportLogService;
        this.exportLogs = exportLogs;
        this.poolPaperService = poolPaperService;
        this.fileService = fileService;
        this.sender = sender;
        this.feginWebsocket = feginWebsocket;
        this.tabulateRedisService = tabulateRedisService;
    }

    @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 keyWord = prams.getString("keyWord");
                String gfsh = prams.getString("gfsh");
                String cjksyf = prams.getString("cjksyf");
                String cjjsyf = prams.getString("cjjsyf");
                String kpksrq = prams.getString("kpksrq");
                String kpjsrq = prams.getString("kpjsrq");
                String fplx = prams.getString("invoiceType");
                String fpzt = prams.getString("fpzt");
                String qsyf = prams.getString("qsyf");
                String qszt = prams.getString("qszt");
                String qsr = prams.getString("qsr");
                String qsfs = prams.getString("qsfs");
                String listMark = prams.getString("listMark");
                String remark = prams.getString("remark");
                String inAccountMonth = prams.getString("inAccountMonth");
                String inAccountStatus = prams.getString("inAccountStatus");
                String gfTaxNo = prams.getString("gfTaxNo");
                String company = prams.getString("company");
                String sourceXml = prams.getString("sourceXml");
                String sourcePdf = prams.getString("sourcePdf");
                String sourceOfd = prams.getString("sourceOfd");
                String tdyslxDm = prams.getString("tdyslxDm");
                // 参数转换为需要的形式
                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);
                }
                if (cjksyf != null && !"".equals(cjksyf)) {
                    pramsMap.put("cjksyf", DateUtils.getMorning(DateUtils.strToDate(cjksyf)));
                }
                if (cjjsyf != null && !"".equals(cjjsyf)) {
                    pramsMap.put("cjjsyf", DateUtils.getNight(DateUtils.strToDate(cjjsyf)));
                }
                if (kpksrq != null && !"".equals(kpksrq)) {
                    pramsMap.put("kpksrq", DateUtils.getMorning(DateUtils.strToDate(kpksrq)));
                }
                if (kpjsrq != null && !"".equals(kpjsrq)) {
                    pramsMap.put("kpjsrq", DateUtils.getNight(DateUtils.strToDate(kpjsrq)));
                }

                pramsMap.put("keyWord", keyWord);
                pramsMap.put("invoiceType", fplx);
                if (qsyf == null && "".equals(qsyf) && !"1".equals(qszt)) {
                    pramsMap.put("qsyf", "");
                }else {
                    pramsMap.put("qsyf", qsyf);
                }
                pramsMap.put("qszt", qszt);
                pramsMap.put("qsr", qsr);
                pramsMap.put("qsfs", qsfs);
                pramsMap.put("fpzt", fpzt);
                pramsMap.put("listMark", listMark);
                pramsMap.put("remark", remark);
                if (inAccountMonth == null && "".equals(inAccountMonth) && !"1".equals(inAccountMonth)) {
                    pramsMap.put("inAccountMonth", "");
                }else {
                    pramsMap.put("inAccountMonth", inAccountMonth);
                }
                pramsMap.put("inAccountStatus", inAccountStatus);
                pramsMap.put("company", company);
                pramsMap.put("tdyslxDm", tdyslxDm);
                pramsMap.put("incentiveFlag", prams.getString("incentiveFlag"));
                pramsMap.put("invoiceSource",prams.getString("invoiceSource"));
                if(StringUtils.isNotBlank(sourceXml)){
                    pramsMap.put("sourceXml", sourceXml);
                }
                if(StringUtils.isNotBlank(sourcePdf)){
                    pramsMap.put("sourcePdf", sourcePdf);
                }
                if(StringUtils.isNotBlank(sourceOfd)){
                    pramsMap.put("sourceOfd", sourceOfd);
                }
                // 导出文件名
                StringBuilder ftpFileName = new StringBuilder();
                ftpFileName.append(fileNamePrefix);
                ftpFileName.append(DateUtils.dateToMonthStr(new Date()));
                ftpFileName.append(fileSplit);
                if ("99".equals(gfTaxNo)) {
                    if (gfshList.size() > 0) {
                        if(ObjectUtil.isNotEmpty(poolPaperService.getblocName(gfshList.get(0)))){
                            ftpFileName.append(poolPaperService.getblocName(gfshList.get(0)));
                            ftpFileName.append(fileSplit);
                        }
                    }
                } else {
                    if (gfshList.size() > 0) {
                        for (String s : gfshList) {
                            ftpFileName.append(poolPaperService.getGfName(s));
                            ftpFileName.append(fileSplit);
                        }
                    }
                }

                ftpFileName.append(DateUtils.getNowTimeStamp());
                title = ftpFileName.toString();
                ftpFileName.append(fileNameSurfix);

                // 本地文件存储路径
                StringBuilder excelFile = new StringBuilder();
                excelFile.append(fileService.getLocalPathDefault());
                excelFile.append(ftpFileName.toString());
                File filePath = new File(getFilePath(excelFile.toString()));
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }

                File file = new File(excelFile.toString());
                if (!file.exists()) {
                    file.delete();
                }

                if (!file.exists()) {
                    file.createNewFile();
                }
                OutputStream out = new FileOutputStream(excelFile.toString());
                // writer = new ExcelWriter(null, out, ExcelTypeEnum.XLSX, true, new CellWriteHandler());
                ExcelWriterBuilder builder = EasyExcel.write(excelFile.toString());
                builder.registerWriteHandler(new CustomCellWriteHandler());
                writer = builder.build();
                // 递归导出数据到excel
                this.cicleExport(pramsMap, default_curr, excelFile.toString(), out, writer);

                this.detailCicleExport(pramsMap, default_curr, excelFile.toString(), out, writer);
                writer.finish();
                // 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, OutputStream out,
        ExcelWriter writer) throws Exception {
        // 查询指定页数的数据
        JSONObject pageData = poolPaperService.listSaleInvoice(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");
            // 写入当前页数据
            exportListArrayToExcel(excelFile, title, titleColumns, dataList, firstPage, false, 1, "发票信息", out, writer);
            // 更新页数
            return cicleExport(pramsMap, nextPage, excelFile, out, writer);
        } else {
            // 写入最后一页数据
            exportListArrayToExcel(excelFile, title, titleColumns, dataList, firstPage, true, 1, "发票信息", out, writer);
            return hasNext;
        }

    }

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

    private boolean detailCicleExport(Map<String, Object> pramsMap, int curr, String excelFile, OutputStream out,
        ExcelWriter writer) {
        // 查询指定页数的数据
        JSONObject pageData = poolPaperService.listSaleInvoiceDetail(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");
            // 写入当前页数据
            exportListArrayToExcel(excelFile, title, detailTitleColumns, dataList, firstPage, false, 2, "货物信息", out,
                writer);
            // 更新页数
            return detailCicleExport(pramsMap, nextPage, excelFile, out, writer);
        } else {
            // 写入最后一页数据
            exportListArrayToExcel(excelFile, title, detailTitleColumns, dataList, firstPage, true, 2, "货物信息", out,
                writer);
            return hasNext;
        }

    }

    public void exportListArrayToExcel(String excelFile, String title, String[] titleColumns, List<String[]> dataList,
        boolean firstPage, boolean lastPage, int sheetNo, String sheetName, OutputStream out, ExcelWriter writer) {

        String[] datas;
        if (firstPage) {
            writeSheet = new WriteSheet();
            writeSheet.setSheetNo(sheetNo);
            writeSheet.setSheetName(sheetName);
            writeTable = new WriteTable();
            writeTable.setTableNo(sheetNo);

            List<List<String>> titles = new ArrayList<>();
            datas = titleColumns;
            int var11 = titleColumns.length;

            for (int var12 = 0; var12 < var11; ++var12) {
                String titleColumn = datas[var12];
                titles.add(Collections.singletonList(titleColumn));
            }

            writeTable.setHead(titles);
            List<List<String>> list = new ArrayList<>();

            for (String[] strings : dataList) {
                datas = strings;
                list.add(Arrays.asList(datas));
            }

            this.writer.write(list, writeSheet, writeTable);
        } else {
            List<List<String>> list = new ArrayList<>();

            for (String[] strings : dataList) {
                datas = strings;
                list.add(Arrays.asList(datas));
            }

            this.writer.write(list, writeSheet, writeTable);
        }


    }

    private static String getFilePath(String fileName) {
        StringBuilder filePath = new StringBuilder();
        if (!fileName.contains(":")) {
            filePath.append("/");
        }

        String[] filePaths = fileName.split("/");

        for (int i = 0; i < filePaths.length - 1; ++i) {
            if (!StringHelper.isBlank(filePaths[i])) {
                filePath.append(filePaths[i]);
                filePath.append("/");
            }
        }

        return filePath.toString();
    }
}
