package com.dxhy.core.thread;

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

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
//import com.alibaba.excel.metadata.Sheet;
//import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.dxhy.common.util.*;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
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.ViolationSearchService;
import com.dxhy.core.service.singletable.IExcelExportlogService;
import com.dxhy.core.util.JsonResponseUtils;
import com.dxhy.oss.service.FileService;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

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

public class RiskInvoiceThread extends BaseThread {

    /**
     * 默认要导出第几页的数据
     */
    private final int default_curr = 1;
    /**
     * 默认每页导出多少条数据
     */
    private final int default_size = 5000;
    /**
     * 文件名前缀
     */
    private final String fileNamePrefix = "riskInvoice";
    /**
     * 文件名后缀
     */
    private final String fileNameSurfix = ".xls";
    /**
     * 文件名中间分隔符
     */
    private final String fileSplit = "_";
    /**
     * 导出excel的列名
     */
    private final String[] titleColumns = {"序号", "风险类别", "发票类型", "发票代码", "发票号码", "发票状态", "管理状态", "开票日期", "销方名称", "销方税号",
        "金额", "税额", "价税合计", "备注", "抵扣税额", "认证状态", "认证类型"};
    /**
     * 导出excel的列名
     */
    private final String[] riskTitleColumns =
            {"序号", "发票类型", "发票代码", "发票号码", "发票违规信息","控制方式"};
    /**
     * excel的标题
     */
    private final String title = "风险发票";

    /**
     * 缓存合计数量
     */
    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 ViolationSearchService violationSearchService;

    private final FileService fileService;

    private final Sender sender;

    private final IFeginWebsocket feginWebsocket;
    private WriteSheet writeSheet;
    private WriteTable writeTable;
    private ExcelWriter writer = null;

    public RiskInvoiceThread(IExcelExportlogService exportLogService, List<TDxExcelExportlog> exportLogs,
        ViolationSearchService violationSearchService, FileService fileService, Sender sender,
        IFeginWebsocket feginWebsocket) {
        this.exportLogService = exportLogService;
        this.exportLogs = exportLogs;
        this.violationSearchService = violationSearchService;
        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 taxNo = prams.getString("taxNo");
                String invoiceDateStart = prams.getString("invoiceDateStart");
                String invoiceDateEnd = prams.getString("invoiceDateEnd");
                String invoiceType = prams.getString("invoiceType");
                String invoiceStatus = prams.getString("invoiceStatus");
                String glzt = prams.getString("glzt");
                String rzzt = prams.getString("rzzt");
                String rzlx = prams.getString("rzlx");
                String fxlx = prams.getString("fxlx");
                String searchKey = prams.getString("searchKey");

                // 参数转换为需要的形式
                Map<String, Object> pramsMap = new HashMap<String, Object>(16);
                pramsMap.put("dbName", dbName);
                pramsMap.put("userid", userid);
                pramsMap.put("searchKey", searchKey);
                List<String> gfshList = new ArrayList<String>();
                if (!StringHelper.isBlank(gfsh)) {
                    gfshList = StringHelper.stringToList(gfsh);
                    pramsMap.put("gfsh", gfshList);
                } else {
                    pramsMap.put("gfsh", gfshList);
                }
                if (invoiceDateStart != null && !"".equals(invoiceDateStart)) {
                    pramsMap.put("invoiceDateStart", DateUtils.getMorning(DateUtils.strToDate(invoiceDateStart)));
                }
                if (invoiceDateEnd != null && !"".equals(invoiceDateEnd)) {
                    pramsMap.put("invoiceDateEnd", DateUtils.getNight(DateUtils.strToDate(invoiceDateEnd)));
                }
                if (StringUtils.isNotBlank(invoiceType) && !"99".equals(invoiceType)) {
                    pramsMap.put("invoiceType", invoiceType);
                }
                if (StringUtils.isNotBlank(invoiceStatus) && !"99".equals(invoiceStatus)) {
                    pramsMap.put("invoiceStatus", invoiceStatus);
                }
                if (StringUtils.isNotBlank(glzt) && !"99".equals(glzt)) {
                    pramsMap.put("glzt", glzt);
                }
                if (StringUtils.isNotBlank(rzzt) && !"99".equals(rzzt)) {
                    pramsMap.put("rzzt", rzzt);
                }
                if (StringUtils.isNotBlank(rzlx) && !"99".equals(rzlx)) {
                    pramsMap.put("rzlx", rzlx);
                }
                if (StringUtils.isNotBlank(fxlx) && !"99".equals(fxlx)) {
                    pramsMap.put("fxlx", fxlx);
                }

                pramsMap.put("invoiceSource",prams.getString("invoiceSource"));
                // 导出文件名
                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());
                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);
                //风险票据信息导出excle
                this.riskCicleExport(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 =  violationSearchService.riskInvoice(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
     * @throws Exception
     *
     */

    private boolean riskCicleExport(Map<String, Object> pramsMap, int curr, String excelFile, OutputStream out,
                                      ExcelWriter writer) throws Exception {
        // 查询指定页数的数据
        JSONObject pageData = violationSearchService.riskEnterpriseInvoice(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, riskTitleColumns, dataList, firstPage, false, 2, "违反企业管控信息", out,
                    writer);
            // 更新页数
            return riskCicleExport(pramsMap, nextPage, excelFile, out, writer);
        } else {
            // 写入最后一页数据
            exportListArrayToExcel(excelFile, title, riskTitleColumns, 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);
        }

    }
}
