package com.dxhy.core.service.filedownload;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.util.SevenZFileUtil;
import com.dxhy.common.util.StringHelper;
import com.dxhy.core.entity.TDxExcelExportlog;
import com.dxhy.core.entity.TDxInvoiceImg;
import com.dxhy.core.service.singletable.IDxInvoiceImgService;
import com.dxhy.core.service.singletable.IExcelExportlogService;
import com.dxhy.oss.config.OssReturnConfig;
import com.dxhy.oss.model.FileModel;
import com.dxhy.oss.service.FileService;

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

/**
 * ftp文件下载实现类
 *
 * @author user
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "DuplicatedCode"})
@Service("downloadService")
@Slf4j

public class FileDownloadServiceImpl implements IFileDownloadService {

    /**
     * 扫描仪图片下载
     */
    private static final String DOWNLOAD_SCAN_IMG = "1";
    /**
     * excel导出文件下载
     */
    private static final String DOWNLOAD_EXCEL = "2";
    /**
     * 源文件下载
     */
    private static final String DOWNLOAD_FILE = "3";

    @Resource
    private FileService fileService;

    @Resource
    private IDxInvoiceImgService invoiceImgService;

    @Resource
    private IExcelExportlogService exportlogService;

    @Override
    public Map<String, String> downLoadFileFromFtp(Map<String, String> pramsMap) {
        String userName = pramsMap.get("userName");
        String dbName = pramsMap.get("dbName");
        String serviceType = pramsMap.get("serviceType");
        String downloadId = pramsMap.get("downloadId");
        String errmsg = null;
        Map<String, String> fileMap = new HashMap<>(4);

        DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
        try {
            if (DOWNLOAD_SCAN_IMG.equals(serviceType)) {
                // 根据传入的扫描id查询图片存储路径
                QueryWrapper<TDxInvoiceImg> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("scan_id", downloadId);
                TDxInvoiceImg invoiceImg = invoiceImgService.getOne(queryWrapper);
                if (invoiceImg != null) {
                    String imagePath = invoiceImg.getImagePath();
                    if (!StringHelper.isBlank(imagePath)) {
                        Map<String, String> ftpFileMap = this.getFtpFileMap(imagePath);
                        String fileName = ftpFileMap.get("fileName");
                        String localPath = fileService.getLocalPathDefault() + "img/" + DateUtil.today() + "/"
                            + userName + "/" + fileName;
                        FileModel fileModel = fileService.downFile(imagePath, localPath);
                        if (!OssReturnConfig.SUCCESS.equals(fileModel.getCode())) {
                            errmsg = "文件下载失败！";
                        } else {
                            // ftp下载后的图片路径
                            String localFile7z = localPath + fileName;
                            // OCR上传的为7z压缩图片，需要解压
                            SevenZFileUtil.unSevenZFile(localFile7z, localPath);
                            // 获取解压后的文件名
                            String fileNameDownLoad = SevenZFileUtil.getFirstFileName(fileModel.getFilePath());
                            fileMap.put("fileName", fileNameDownLoad);
                            fileMap.put("filePath", fileModel.getFilePath());
                        }
                    } else {
                        errmsg = "未从发票图片表获取到存储路径！";
                    }
                } else {
                    errmsg = "扫描图片记录已删除！";
                }
            } else if (DOWNLOAD_EXCEL.equals(serviceType)) {
                // 根据传入的id查询导出日志表存储路径
                QueryWrapper<TDxExcelExportlog> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", downloadId);
                TDxExcelExportlog exportlog = exportlogService.getOne(queryWrapper);
                if (exportlog != null) {
                    String filePath = exportlog.getFilepath();
                    if (!StringHelper.isBlank(filePath)) {
                        Map<String, String> ftpFileMap = this.getFtpFileMap(filePath);
                        String fileName = ftpFileMap.get("fileName");
                        String localPath =
                            fileService.getLocalPathDefault() + DateUtil.today() + "/" + userName + "/" + fileName;
                        FileModel fileModel = fileService.downFile(filePath, localPath);
                        if (!OssReturnConfig.SUCCESS.equals(fileModel.getCode())) {
                            errmsg = "文件下载失败！";
                        } else {
                            fileMap.put("fileName", fileName);
                            fileMap.put("filePath", fileModel.getFilePath());
                        }
                    } else {
                        errmsg = "未从发票图片表获取到存储路径！";
                    }
                } else {
                    errmsg = "导出记录已删除，请重新申请！";
                }
            } else if (DOWNLOAD_FILE.equals(serviceType)) {
                // 根据传入的扫描id查询图片存储路径
                QueryWrapper<TDxInvoiceImg> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("scan_id", downloadId);
                TDxInvoiceImg invoiceImg = invoiceImgService.getOne(queryWrapper);
                if (invoiceImg != null) {
                    String filePath = invoiceImg.getImage();
                    if (!StringHelper.isBlank(filePath)) {
                        Map<String, String> ftpFileMap = this.getFtpFileMap(filePath);
                        String ftpPath = ftpFileMap.get("filePath");
                        String fileName = ftpFileMap.get("fileName");
                        String localPath = fileService.getLocalPathDefault() + "file/" + DateUtil.today() + "/"
                            + userName + "/" + fileName;
                        FileModel fileModel = fileService.downFile(filePath, localPath);
                        if (!OssReturnConfig.SUCCESS.equals(fileModel.getCode())) {
                            errmsg = "文件下载失败！";
                        } else {
                            fileMap.put("fileName", fileName);
                            fileMap.put("filePath", fileModel.getFilePath());
                        }
                    } else {
                        errmsg = "未从附件表获取到存储路径！";
                    }
                } else {
                    errmsg = "无附件记录！";
                }
            } else {
                errmsg = "非法业务类型！";
            }
            if (!StringHelper.isBlank(errmsg)) {
                fileMap.put("errmsg", errmsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return fileMap;
    }

    /**
     * 根据存储的全路径获取，存储文件夹及文件名
     *
     * @param imagePath
     *            文件地址
     * @return 返回
     *
     */
    private Map<String, String> getFtpFileMap(String imagePath) {
        Map<String, String> ftpFileMap = new HashMap<>(2);
        StringBuilder filePath = new StringBuilder();
        // linux服务器
        if (!imagePath.contains(":")) {
            filePath.append("/");
        }
        String[] filePaths = imagePath.split("/");

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

}
