package com.dxhy.core.thread;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxhy.api.model.excelExport.TDxExcelExportlog;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.api.model.sign.TDxInvoiceImg;
import com.dxhy.common.rabbitmq.RabbitMqSender;
import com.dxhy.common.service.impl.TabulateRedisServiceImpl;
import com.dxhy.common.util.ExceptionUtil;
import com.dxhy.common.util.FileUtil;
import com.dxhy.common.util.FileZip;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.core.dao.CoreTDxInvoiceImgDao;
import com.dxhy.core.feign.IFeginWebsocket;
import com.dxhy.core.job.dao.LqTdxInvoiceFileCoreDao;
import com.dxhy.core.job.dao.TDxRecordInvoiceJobDao;
import com.dxhy.core.job.dao.TDxSaleRecordInvoiceJobDao;
import com.dxhy.core.job.entity.TDxInvoiceFileEntity;
import com.dxhy.core.job.entity.TDxSaleRecordInvoiceJobEntity;
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 org.springframework.beans.BeanUtils;

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

/**
 * 票池下载电子源文件
 *
 * @author user
 */

@Slf4j

public class PcDownloadSourceThread extends BaseThread {

    /**
     * 默认要导出第几页的数据
     */
    private final int default_curr = 1;
    /**
     * 默认每页导出多少条数据
     */
    private final int default_size = 5000;
    /**
     * 文件名前缀
     */
    private final String fileNamePrefix = "bbfpzhcxList";
    /**
     * 文件名后缀
     */
    private final String fileNameSurfix = ".zip";
    /**
     * 文件名中间分隔符
     */
    private final String fileSplit = "_";
    /**
     * excel的标题
     */
    private final String title = "电子源文件信息";
    /**
     * 导出excel的列名
     */
    private final String[] titleColumns =
        { "开票日期", "发票代码", "发票号码", "税款所属期", "出口转内销证明编号", "勾选时间", "发票状态", "是否异常凭证","锁定状态"};

    private final IExcelExportlogService exportLogService;

    private final List<TDxExcelExportlog> exportLogs;

    private final LqTdxInvoiceFileCoreDao lqTdxInvoiceFileCoreDao;

    private final TDxRecordInvoiceJobDao tDxRecordInvoiceJobDao;


    private final CoreTDxInvoiceImgDao coreTDxInvoiceImgDao;

    private final TDxSaleRecordInvoiceJobDao tDxSaleRecordInvoiceJobDao;

    private final FileService fileService;

    private final RabbitMqSender sender;
    private final TabulateRedisServiceImpl tabulateRedisService;

    public PcDownloadSourceThread(IExcelExportlogService exportLogService, List<TDxExcelExportlog> exportLogs,
                                  LqTdxInvoiceFileCoreDao lqTdxInvoiceFileCoreDao,TDxRecordInvoiceJobDao tDxRecordInvoiceJobDao,CoreTDxInvoiceImgDao coreTDxInvoiceImgDao,TDxSaleRecordInvoiceJobDao tDxSaleRecordInvoiceJobDao, FileService fileService, RabbitMqSender sender, IFeginWebsocket feginWebsocket,
                                  TabulateRedisServiceImpl tabulateRedisService) {
        this.exportLogService = exportLogService;
        this.exportLogs = exportLogs;
        this.lqTdxInvoiceFileCoreDao = lqTdxInvoiceFileCoreDao;
        this.tDxRecordInvoiceJobDao = tDxRecordInvoiceJobDao;
        this.coreTDxInvoiceImgDao = coreTDxInvoiceImgDao;
        this.tDxSaleRecordInvoiceJobDao = tDxSaleRecordInvoiceJobDao;
        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();

            // 捕获异常，防止某一条日志导出出错，影响其它日志的导出
            String errShowName = "";
            try {
                exportLogService.updateStart(id, dbName);

                // 应该保存的参数
                JSONObject prams = JSONObject.parseObject(condition);
                String uuids = prams.getString("uuids");
                String sourceType = prams.getString("sourceType");
                // 0进项   1销项
                String pageType = prams.getString("pageType");

                // 导出文件名
                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);


                //下载打包源文件.获取压缩包所在ftp位置
                String ftpPath = downloadSourceFileZip(uuids,pageType);

                String pageJxXx = "";
                if("0".equals(pageType)){
                    pageJxXx = "进项";
                }else{
                    pageJxXx = "销项";
                }

                String showTitle = pageJxXx + "电子源文件"+ DateUtil.format(new Date(), "yyyyMMddHHmmss");
                errShowName = showTitle;

                msg.put("title", super.getSuccTitle(showTitle));
                msg.put("content", super.getSuccContent(createDate));
                msg.put("url", getZipUrl(id));
                msg.put("useraccount", userName);

                // 记录导出完成状态
                exportLogService.updateSucc(id, ftpPath, dbName);

            } catch (Exception e) {
                String errmsg = ExceptionUtil.getExceptionDeteil(e, 4000);
                // 设置失败消息内容
                if(StringUtils.isEmpty(errShowName)){
                    msg.put("title", super.getFailTitle(title));
                }else{
                    msg.put("title", super.getFailTitle(errShowName));
                }
                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);
            }
        }
    }

    private Object getZipUrl(Long id) {
        String downLoadurl = "/ftp/download";
        return downLoadurl + "?serviceType=4&downloadId=" + id;
    }

    /**
     * 下载源文件
     * pageType 0进项  1销项
     **/
    private String downloadSourceFileZip(String uuids, String pageType) {
        //查到的就是有源文件的
        List<TDxRecordInvoice> tDxInvoiceFileLists = new ArrayList<>();
        if("0".equals(pageType)){
            //进项
            tDxInvoiceFileLists = tDxRecordInvoiceJobDao.selectList(new LambdaQueryWrapper<TDxRecordInvoice>().in(TDxRecordInvoice::getUuid, uuids.split(",")));
        }else{
            //销项
            List<TDxSaleRecordInvoiceJobEntity> tDxSaleRecordInvoiceJobEntities = tDxSaleRecordInvoiceJobDao.selectList(new LambdaQueryWrapper<TDxSaleRecordInvoiceJobEntity>().in(TDxSaleRecordInvoiceJobEntity::getUuid, uuids.split(",")));
            for (TDxSaleRecordInvoiceJobEntity item:tDxSaleRecordInvoiceJobEntities) {
                TDxRecordInvoice newItem = new TDxRecordInvoice();
                BeanUtils.copyProperties(item, newItem);
                tDxInvoiceFileLists.add(newItem);
            }
        }

        if(tDxInvoiceFileLists.size()>0){
            try {
                // 本地临时文件夹路径
                String timeString = DateUtil.format(new Date(), "yyyyMMdd");
                String localTempDir = fileService.getLocalPathDefault() + timeString + File.separator;
                // 创建临时文件夹
                File dir = new File(localTempDir);
                dir.mkdirs();

                // 处理每个文件,下载到本地临时文件夹内
                for (int i = 0; i < tDxInvoiceFileLists.size(); i++) {
                    try {
                        TDxRecordInvoice tDxRecordInvoice = tDxInvoiceFileLists.get(i);
                        String uuid = tDxRecordInvoice.getUuid();
                        String xmlFlag = tDxRecordInvoice.getXmlFlag();
                        log.info("当前数据xml_flag:{}",xmlFlag);
                        //查询电子税局下载源文件表
                        TDxInvoiceFileEntity tDxInvoiceFileEntity = lqTdxInvoiceFileCoreDao.selectOne(new LambdaQueryWrapper<TDxInvoiceFileEntity>().eq(TDxInvoiceFileEntity::getUuid, uuid));
                        boolean sourceXml = false;
                        boolean sourcePdf = false;
                        boolean sourceOfd = false;
                        if(xmlFlag.contains("1")){
                            sourceXml = true;
                            //xml
                            fileService.downFile(tDxInvoiceFileEntity.getXmlPath(), localTempDir + uuid + ".xml");
                        }
                        if(xmlFlag.contains("2")){
                            sourcePdf = true;
                            //pdf
                            fileService.downFile(tDxInvoiceFileEntity.getPdfPath(), localTempDir + uuid + ".pdf");
                        }
                        if(xmlFlag.contains("3")){
                            sourceOfd = true;
                            //ofd
                            fileService.downFile(tDxInvoiceFileEntity.getOfdPath(), localTempDir + uuid + ".ofd");
                        }
                        //进项才查本地
                        if("0".equals(pageType)){
                            //如果有本地，且没税局源文件。就判断本地456，如果有，就去invoice_record查qs_status，如果是1(签收成功)，就用scan_id去img表查数据。
                            if(xmlFlag.contains("4")||xmlFlag.contains("5")||xmlFlag.contains("6")){
                                if(sourceXml){
                                    //已下载电子税局xml
                                }else{
                                    if(xmlFlag.contains("4")){
                                        if("1".equals(tDxRecordInvoice.getQsStatus())){
                                            //用scanid去img表获取源文件
                                            TDxInvoiceImg tDxInvoiceImg = coreTDxInvoiceImgDao.selectOne(new LambdaQueryWrapper<TDxInvoiceImg>().eq(TDxInvoiceImg::getScanId, tDxRecordInvoice.getScanId()));
                                            fileService.downFile(tDxInvoiceImg.getImage(), localTempDir + uuid + ".xml");
                                        }
                                    }
                                }

                                if(sourcePdf){
                                    //已下载电子税局pdf
                                }else{
                                    if(xmlFlag.contains("5")){
                                        if("1".equals(tDxRecordInvoice.getQsStatus())){
                                            //用scanid去img表获取源文件
                                            TDxInvoiceImg tDxInvoiceImg = coreTDxInvoiceImgDao.selectOne(new LambdaQueryWrapper<TDxInvoiceImg>().eq(TDxInvoiceImg::getScanId, tDxRecordInvoice.getScanId()));
                                            fileService.downFile(tDxInvoiceImg.getImage(), localTempDir + uuid + ".pdf");
                                        }
                                    }
                                }

                                if(sourceOfd){
                                    //已下载电子税局ofd
                                }else{
                                    if(xmlFlag.contains("6")){
                                        if("1".equals(tDxRecordInvoice.getQsStatus())){
                                            //用scanid去img表获取源文件
                                            TDxInvoiceImg tDxInvoiceImg = coreTDxInvoiceImgDao.selectOne(new LambdaQueryWrapper<TDxInvoiceImg>().eq(TDxInvoiceImg::getScanId, tDxRecordInvoice.getScanId()));
                                            fileService.downFile(tDxInvoiceImg.getImage(), localTempDir + uuid + ".ofd");
                                        }
                                    }
                                }

                            }
                        }

                    } catch (Exception e) {
                        log.info("业务处理异常：{}", e);
                    }
                }

                // 打包
                dir = new File(localTempDir);
                File[] files = dir.listFiles();

                String ftpFileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".zip";
                String zipName = localTempDir + ftpFileName;
                if (files != null) {

                    FileZip.zipFiles(files, new File(zipName));
                }

                //上传ftp，返回ftp路径
                // FTP文件存储路径
                String ftpFilePath = CommonUtil.getFtpFilePath(fileService.getPathPrefix(),DateUtil.format(new Date(), "yyyyMMdd"),ftpFileName);
                log.info("开始上传ftp,ftp存储路径:{}",ftpFilePath);
                fileService.uploadFile(ftpFilePath, zipName);
                log.info("上传ftp完成");

                // 删除临时文件夹
                FileUtil.deleteDirectory(localTempDir);

                return ftpFilePath;
            } catch (Exception e) {
                log.error("下载图片出错:" + e);
                log.info("业务处理异常：{}", e);
            }
        }else{
            log.info("没有找到源文件");
        }
        return "";
    }

    private void downloadLocalFile(String s) {
    }


}
