package com.dxhy.core.thread;


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

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

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.service.impl.TabulateRedisServiceImpl;
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.JxsemxbbRespVO;
import com.dxhy.common.rabbitmq.RabbitMqSender;
import com.dxhy.core.service.export.JxsemxbbcxService;
import com.dxhy.core.util.JsonResponseUtils;
import com.dxhy.oss.service.FileService;

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

/**
 * 进项税额报表查询导出
 *
 * @author 陈刚扬
 * @date 2020/10/28
 * @return
 */

@Slf4j
@SuppressWarnings("AlibabaUndefineMagicConstant")
public class JxsemxbbExportThread extends BaseThread {

    /**
     * 默认要导出第几页的数据
     */
    private final int default_curr = 1;

    /**
     * 文件名前缀
     */
    private final String fileNamePrefix = "bbfpzhcxList";
    /**
     * 文件名后缀
     */
    private final String fileNameSurfix = ".xlsx";
    /**
     * 文件名中间分隔符
     */
    private final String fileSplit = "_";
    /**
     * excel的标题
     */
    private final String title = "进项税额明细报表";

    private final IExcelExportlogService exportLogService;

    private final List<TDxExcelExportlog> exportLogs;

    private final JxsemxbbcxService jxsemxbbcxService;

    private final FileService fileService;

    private final RabbitMqSender sender;
    private final TabulateRedisServiceImpl tabulateRedisService;

    public JxsemxbbExportThread(IExcelExportlogService exportLogService, List<TDxExcelExportlog> exportLogs,
        JxsemxbbcxService jxsemxbbcxService, FileService fileService, RabbitMqSender sender, IFeginWebsocket feginWebsocket,
        TabulateRedisServiceImpl tabulateRedisService) {
        this.exportLogService = exportLogService;
        this.exportLogs = exportLogs;
        this.jxsemxbbcxService = jxsemxbbcxService;
        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());

                // 递归导出数据到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
     *
     * @param pramsMap
     * @param curr
     * @param excelFile
     * @throws Exception
     */
    private void cicleExport(Map<String, Object> pramsMap, int curr, String excelFile) throws Exception {
        // 查询数据
        JSONObject pageData = jxsemxbbcxService.selectByPramsMap(pramsMap);
        JxsemxbbRespVO jxsemxbbRespVO = (JxsemxbbRespVO)pageData.get("datalist");
        exportListArrayToExcel(excelFile, title, jxsemxbbRespVO, pageData);

    }

    public static void exportListArrayToExcel(String excelFile, String title, JxsemxbbRespVO jxsemxbbRespVO,
        JSONObject pageData) throws Exception {
        // 文件存储路径是否存在
        File filePath = new File(getFilePath(excelFile));
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        File file = new File(excelFile);
        // excel不存在则创建
        if (!file.exists()) {
            file.createNewFile();
        }

        String filePaht = "/template/inputTaxReport.xlsx";
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(filePaht));
        XSSFSheet sheet = wb.getSheet("sheet1");
        sheet.getRow(1).getCell(0).setCellValue("税款所属期: " + pageData.get("skssq"));
        sheet.getRow(2).getCell(0).setCellValue(jxsemxbbRespVO.getGfmc());
        sheet.getRow(4).getCell(2).setCellValue(jxsemxbbRespVO.getTotalAmount());
        sheet.getRow(4).getCell(3).setCellValue(jxsemxbbRespVO.getTotalTax());
        sheet.getRow(6).getCell(2).setCellValue(jxsemxbbRespVO.getAmount17());
        sheet.getRow(6).getCell(3).setCellValue(jxsemxbbRespVO.getTax17());
        sheet.getRow(8).getCell(2).setCellValue(jxsemxbbRespVO.getAmount13());
        sheet.getRow(8).getCell(3).setCellValue(jxsemxbbRespVO.getTax13());
        sheet.getRow(9).getCell(2).setCellValue(jxsemxbbRespVO.getAmount10());
        sheet.getRow(9).getCell(3).setCellValue(jxsemxbbRespVO.getTax10());
        sheet.getRow(15).getCell(2).setCellValue(jxsemxbbRespVO.getAmount5());
        sheet.getRow(15).getCell(3).setCellValue(jxsemxbbRespVO.getTax5());
        sheet.getRow(20).getCell(2).setCellValue(jxsemxbbRespVO.getAmount3());
        sheet.getRow(20).getCell(3).setCellValue(jxsemxbbRespVO.getTax3());

        FileOutputStream outStream = new FileOutputStream(file);
        wb.write(outStream);
        outStream.flush();
        outStream.close();
        wb.close();
    }

    /**
     * 根据全路径获取存储路径
     *
     * @param fileName
     * @return
     *
     */
    private static String getFilePath(String fileName) {
        StringBuilder filePath = new StringBuilder();
        // linux服务器
        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();
    }

}
