package com.dxhy.core.service.poolInvoiceDownload.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.sign.TDxInvoiceImg;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.util.StringHelper;
import com.dxhy.core.job.dao.DataPlatformDao;
import com.dxhy.core.job.entity.TAcOrg;
import com.dxhy.core.service.poolInvoiceDownload.CompanyPoolService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述
 *
 * @author 陈刚扬
 * @date 2020/10/28
 * @return
 */

@Service("companyPoolService")
@Slf4j
@SuppressWarnings("AlibabaUndefineMagicConstant")
public class CompanyPoolServiceImpl implements CompanyPoolService {
    @Resource
    private FileService fileService;

    @Resource
    private IDxInvoiceImgService invoiceImgService;

    @Resource
    private IExcelExportlogService exportlogService;

    @Resource
    private DataPlatformDao dataPlatformDao;

    @Override
    public void getFilePath(HttpServletRequest request, HttpServletResponse response) {

        String downloadId = request.getParameter("scanId") + "";
        String taxno = request.getParameter("taxno") + "";
        String errmsg = null;
        JSONObject fileMap = new JSONObject();
        try {
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            TAcOrg dept = dataPlatformDao.getDeptByTaxno(taxno);
            DynamicContextHolder.push(dept.getDbName() + DbConstant.BUSINESS_READ);
            // 根据传入的扫描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"+ File.separator + DateUtil.today() +  File.separator
                        + "companyPool" +  File.separator ;

                    FileModel fileModel = fileService.downFile(imagePath, localPath);
                    if (!OssReturnConfig.SUCCESS.equals(fileModel.getCode())) {
                        errmsg = "文件下载失败！";
                    } else {
                        // ftp下载后的图片路径
                        String localFile7z = localPath + fileName;
                        File downLoadFile = new File(localFile7z);
                        // 获取文件的长度
                        long fileLength = downLoadFile.length();

                        BufferedInputStream bis = null;
                        BufferedOutputStream bos = null;

                        // 设置文件输出类型

                        response.setContentType(this.getContentType(fileName));

                        response.setHeader("Content-disposition", "attachment; filename="
                            + new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
                        // 设置输出长度
                        response.setHeader("Content-Length", String.valueOf(fileLength));

                        // 获取输入流
                        bis = new BufferedInputStream(new FileInputStream(downLoadFile));
                        // 输出流
                        bos = new BufferedOutputStream(response.getOutputStream());
                        byte[] buff = new byte[2048];
                        int bytesRead;
                        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                            bos.write(buff, 0, bytesRead);
                        }
                        bos.flush();
                        // 关闭流
                        bis.close();
                        bos.close();

                        // 删除本地文件，防止服务器空间不足
                        downLoadFile.delete();

                    }
                } else {
                    errmsg = "未从发票图片表获取到存储路径！";
                }
            } else {
                errmsg = "扫描图片记录已删除！";
            }
            if (!StringHelper.isBlank(errmsg)) {
                fileMap.put("errmsg", errmsg);
            }

        } catch (Exception e) {
            log.error("从ftp获取图片出错:{}",e);
        }

    }

    /**
     * 根据图片后缀，获取mime类型
     *
     * @param fileName
     * @return
     *
     */

    private String getContentType(String fileName) {
        String mime = "application/octet-stream";
        if (fileName.indexOf(".gif") > 0) {
            mime = "image/gif";
        } else if (fileName.indexOf(".jpg") > 0 || fileName.indexOf(".jpeg") > 0) {
            mime = "image/jpeg";
        } else if (fileName.indexOf(".png") > 0) {
            mime = "image/png";
        } else if (fileName.indexOf(".bmp") > 0) {
            mime = "image/bmp";
        } else if (fileName.indexOf(".svg") > 0) {
            mime = "image/svg";
        }
        return mime;
    }

    /**
     * 根据存储的全路径获取，存储文件夹及文件名
     *
     * @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;
    }
}
