package com.dxhy.core.thread;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxhy.api.model.excelExport.TDxExcelExportlog;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.rabbitmq.RabbitMqSender;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.impl.TabulateRedisServiceImpl;
import com.dxhy.common.util.ExcelPoiUtil;
import com.dxhy.common.util.ExceptionUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.core.feign.IFeginWebsocket;
import com.dxhy.core.model.CautionAbnormalReqVO;
import com.dxhy.core.model.ExceptionInvoiceVo;
import com.dxhy.core.service.export.IExportCautionService;
import com.dxhy.core.service.singletable.IExcelExportlogService;
import com.dxhy.core.util.JsonResponseUtils;
import com.dxhy.oss.service.FileService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author user
 * @date 2019-05-20
 */
@SuppressWarnings({"DuplicatedCode", "FieldCanBeLocal"})
@Slf4j

public class CautionExportAnomalyThread extends BaseThread {
    /**
     * 默认要导出第几页的数据
     */
    private final int default_curr = 1;
    /**
     * 默认每页导出多少条数据
     */
    private final int default_size = 5000;
    /**
     * 文件名前缀
     */
    private final String fileNamePrefix = "cautionAbnormal";
    /**
     * 文件名后缀
     */
    private final String fileNameSurfix = ".xlsx";
    /**
     * 文件名中间分隔符
     */
    private final String fileSplit = "_";
    /**
     * excel的标题
     */
    private final String title = "异常发票预警";
    /**
     * 导出excel的列名
     */
    private final String[] titleColumns =
        {"序号", "异常日期", "发票类型", "发票代码", "发票号码", "开票日期", "异常状态", "购方名称", "购方税号", "销方名称", "销方税号", "金额", "税额"};

    private final List<TDxExcelExportlog> exportLogs;

    private final IExcelExportlogService exportLogService;

    private final IExportCautionService cautionService;

    private final FileService fileService;

    private final RabbitMqSender sender;
    private final TabulateRedisServiceImpl tabulateRedisService;
    private final DictdetaServcice dictdetaServcice;

    public CautionExportAnomalyThread(IExcelExportlogService exportLogService, List<TDxExcelExportlog> exportLogs,
        IExportCautionService cautionService, FileService fileService, RabbitMqSender sender, IFeginWebsocket feginWebsocket,
        TabulateRedisServiceImpl tabulateRedisService, DictdetaServcice dictdetaServcice) {
        this.exportLogService = exportLogService;
        this.exportLogs = exportLogs;
        this.cautionService = cautionService;
        this.fileService = fileService;
        this.sender = sender;
        this.feginWebsocket = feginWebsocket;
        this.tabulateRedisService = tabulateRedisService;
        this.dictdetaServcice = dictdetaServcice;
    }

    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 params = JSONObject.parseObject(condition);

                CautionAbnormalReqVO reqVO = JSONObject.parseObject(params.toJSONString(), CautionAbnormalReqVO.class);
                //处理号码
                if(StringUtils.isNotBlank(reqVO.getInvoiceNo())){
                    if(reqVO.getInvoiceNo().length()==8){

                    }else {
                        reqVO.setEleInvoiceNo(reqVO.getInvoiceNo());
                        reqVO.setInvoiceNo("");
                    }
                }
                JSONObject jsonObject = tabulateRedisService.getTabulateExcel(reqVO.getCompany(), reqVO.getMenuId());
                // 导出文件名
                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
                DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
                log.debug("导出文件路径--" + excelFile.toString());
                this.cicleExport(reqVO, default_curr, excelFile.toString(), exportLog, 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);
            }
        }
    }

    /**
     * @param reqVO
     *            发票信息
     * @param defaultCurr
     *            页数
     * @param excelFile
     *            文件信息
     * @param exportLog
     *            导出日志
     * @throws Exception
     *             异常
     */
    private void cicleExport(CautionAbnormalReqVO reqVO, int defaultCurr, String excelFile, TDxExcelExportlog exportLog,
        JSONObject jsonObject) throws Exception {
        List<String> allTaxNo = new ArrayList<>();
        if (!StringHelper.isBlank(reqVO.getGfsh())) {
            allTaxNo = StringHelper.stringToList(reqVO.getGfsh());
        }
        reqVO.setAllTaxNo(allTaxNo);
        Page<TDxRecordInvoice> page = new Page<>(defaultCurr, default_size);
        PageInfo<TDxRecordInvoice> pageList = cautionService.listAnomaly(page, reqVO, allTaxNo);
        List<ExceptionInvoiceVo> dataList = convertToAbnormalData(pageList.getList());

        boolean firstPage = false;
        if (pageList.isIsFirstPage()) {
            firstPage = true;
        }

        // 已经是最后一页
        if (!pageList.isIsLastPage()) {
            // 写入数据
            ExcelPoiUtil.exportListArrayToExcel1(excelFile, title, jsonObject, dataList, firstPage, false);
        } else if (pageList.isIsLastPage()) {
            ExcelPoiUtil.exportListArrayToExcel1(excelFile, title, jsonObject, dataList, firstPage, true);
            return;
        }
        // 更新页数
        defaultCurr++;
        cicleExport(reqVO, defaultCurr, excelFile, exportLog, jsonObject);
    }

    /**
     * 异常发票预警view
     *
     * @param list
     *            抵账信息
     * @return 返回
     */
    private List<ExceptionInvoiceVo> convertToAbnormalData(List<TDxRecordInvoice> list) {
        List<ExceptionInvoiceVo> dataList = new ArrayList<>();
        int xh = 1;
        String zjje = "0";
        String zjse = "0";
        for (TDxRecordInvoice record : list) {
            ExceptionInvoiceVo vo = new ExceptionInvoiceVo();
            vo.setXh(xh + "");
            xh++;
            // 异常日期 取状态修改时间
            vo.setYcDate(DateUtils.dateToStr(record.getStatusUpdateDate()));
            // 发票类型
            vo.setInvoiceType(dictdetaServcice.queryDictName(DictConstant.INVOICE_TYPEALL, record.getInvoiceType()));
            // 开票日期
            vo.setInvoiceDate(DateUtils.dateToStr(record.getInvoiceDate()));
            // 发票状态
            vo.setInvoiceStatusName(
                dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, record.getInvoiceStatus()));
            vo.setInvoiceCode(record.getInvoiceCode());
            vo.setInvoiceNo(record.getInvoiceNo());
            vo.setEleInvoiceNo(record.getEleInvoiceNo());
            vo.setBuyerName(record.getGfName());
            vo.setSellerName(record.getXfName());

            // 金额
            if(ObjectUtil.isNotEmpty(record.getInvoiceAmount())){
                vo.setAmount(MathUtil.round(record.getInvoiceAmount().toPlainString()));
            }

            // 税额
            if(ObjectUtil.isNotEmpty(record.getTaxAmount())){
                vo.setTaxAmount(MathUtil.round(record.getTaxAmount().toPlainString()));
            }

            dataList.add(vo);
        }

        return dataList;
    }
}
