package com.dxhy.customs.service.impl;

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

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.FileUtils;
import com.dxhy.common.utils.R;
import com.dxhy.common.vo.UserInfo;
import com.dxhy.customs.dao.CustomsFileDao;
import com.dxhy.customs.entity.TdxCustomsFile;
import com.dxhy.customs.entity.TdxCustomsImg;
import com.dxhy.customs.entity.TdxInvoiceImg;
import com.dxhy.customs.service.CustomsCollectService;
import com.dxhy.customs.service.CustomsFileService;
import com.dxhy.customs.service.CustomsImgService;
import com.dxhy.customs.service.CustomsInvoiceImgService;
import com.dxhy.ofd.service.OfdService;
import com.dxhy.oss.config.OssReturnConfig;
import com.dxhy.oss.model.FileModel;
import com.dxhy.oss.service.FileService;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;

/**
 * @author dxhy
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Service("customsCollectService")
@Slf4j
public class CustomsCollectServiceImpl extends MpBaseServiceImpl<CustomsFileDao, TdxCustomsFile>
    implements CustomsCollectService {

    @Resource
    private CustomsFileService customsFileService;

    @Resource
    private CustomsImgService customsImgService;

    @Resource
    private CustomsInvoiceImgService invoiceImgService;

    @Resource
    private FileService fileService;

    @Resource
    private OfdService ofdService;

    /**
     * 获取图片及附件流
     *
     * @author 陈刚扬
     * @date 2020/8/10
     * @param customsScanId
     *            缴款书扫描流水号
     * @param imgOrFile
     *            1图片 2源文件
     * @param userInfo
     *            用户信息
     * @param localPath
     *            本地路径
     */
    @Override
    public Object getImgByCustomsScanId(String customsScanId, String imgOrFile, UserInfo userInfo, String localPath) {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        JSONObject json = new JSONObject();
        JSONArray imgList = null;
        String file = "";
        String fileType = "1";
        try {
            // 海关缴款书图片查看多张
            if ("1".equals(imgOrFile)) {
                List<TdxCustomsImg> customsImgList = customsImgService.selectByCustomsScanId(customsScanId);
                if (customsImgList == null || customsImgList.size() <= 0) {
                    return ResponseEntity.ok(R.error("该缴款书没有图片！"));
                }
                imgList = new JSONArray();
                for (TdxCustomsImg customsImg : customsImgList) {
                    TdxInvoiceImg invoiceImg = invoiceImgService.selectByScanId(customsImg.getScanId());
                    // 下载文件，返回base64文件流
                    String img = download(localPath, fileType, invoiceImg.getImagePath());
                    if (StringUtils.isNotBlank(img)) {
                        imgList.add(img);
                    }
                }
            }
            // 海关缴款书原始凭证文件单张
            if ("2".equals(imgOrFile)) {
                TdxCustomsFile customsFile = customsFileService.selectByCustomsScanId(customsScanId);
                if (customsFile == null || StringUtils.isBlank(customsFile.getImagePath())) {
                    return ResponseEntity.ok(R.error("该缴款书没有原始凭证！"));
                }
                // 获取文件类型
                String fileName = customsFile.getImagePath();
                String fileNameType = fileName.substring(fileName.lastIndexOf("."));
                if (".pdf".equals(fileNameType)) {
                    fileType = "2";
                }
                if (".ofd".equals(fileNameType)) {
                    fileType = "3";
                }
                // 下载文件，返回base64文件流
                file = download(localPath, fileType, customsFile.getImagePath());
            }
            json.put("imgList", imgList);
            json.put("file", file);
            json.put("fileType", fileType);
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
            return ResponseEntity.ok(json);
        }
        return ResponseEntity.ok(R.ok().put("data", super.responseResult(json)));
    }

    public String download(String localPath, String fileType, String downloadPath) {
        try {
            // 获取图片/文件在ftp上的全路径
            File file = new File(downloadPath);
            String fileName = file.getName();
            String remoteZipDir = downloadPath.substring(0, downloadPath.lastIndexOf("/"));
            log.debug("--- localPath=" + localPath);
            log.debug("---- remoteZipDir=" + remoteZipDir);
            log.debug("---- fileName=" + fileName);
            FileModel fileModel = fileService.downFile(downloadPath, localPath + fileName);
            if (!OssReturnConfig.SUCCESS.equals(fileModel.getCode())) {
                log.debug("------ 文件下载失败！----");
                return "";
            }
            return Base64.encode(new File(fileModel.getFilePath()));
        } catch (Exception e) {
            return "";
        } finally {
            // 删除临时文件
            FileUtils.deleteDir(new File(localPath));
        }

    }
}
