package com.seeyon.apps.esign.service;

import com.seeyon.aicloud.common.JsonUtils;
import com.seeyon.apps.esign.config.EsignConfigProvider;
import com.seeyon.apps.esign.constants.EsignApiUrl;
import com.seeyon.apps.esign.constants.EsignConfigConstants;
import com.seeyon.apps.esign.po.esignapi.EsignApiHeader;
import com.seeyon.apps.esign.po.esignapi.EsignBaseResp;
import com.seeyon.apps.esign.po.upload.EsignFileUploadParams;
import com.seeyon.apps.esign.po.esignapi.EsignHttpResponse;
import com.seeyon.apps.esign.po.upload.GetUploadUrlResp;
import com.seeyon.apps.esign.utils.EsignHttpHelper;
import com.seeyon.apps.esign.utils.EsignRequestType;
import com.seeyon.apps.esign.utils.FileUtil;
import com.seeyon.apps.esign.utils.HttpClient;
import com.seeyon.apps.mplus.util.Base64;
import com.seeyon.ctp.common.AppContext;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class EsignUploadFileService {

    private EsignConfigProvider configProvider = EsignConfigProvider.getInstance();
    protected TokenCacheManager tokenCacheManager = (TokenCacheManager) AppContext.getBean("tokenCacheManager");


    public Object[] getDownloadFileInfo(String appId,String flowId) throws Exception {
        String reqPath = EsignApiUrl.CONTRACT_DOWNLOAD_URL.replace("{signFlowId}", flowId);
        String getDownloadUrl = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + reqPath;
        EsignApiHeader esignApiHeader = EsignApiHeader.build().appId(appId).token(tokenCacheManager.getToken(appId));
        String respStr = HttpClient.httpGet(getDownloadUrl, esignApiHeader.convert2Headers(), null);
        EsignBaseResp esignBaseResp = JsonUtils.parseObject(respStr, EsignBaseResp.class);
        if(esignBaseResp.getCode() != 0 || esignBaseResp.getData() == null){
            throw new RuntimeException("下载合同文件失败");
        }
        Map<String,Object> data  = (Map<String, Object>) esignBaseResp.getData();
        Object[] files = (Object[]) data.get("files");
        if(files.length <= 0) {
            throw new RuntimeException("下载合同文件失败");
        }
       return files;
    }

    public GetUploadUrlResp getUploadFileUrl(String appId,String fileName,String fileMd5,Long fileSize,boolean convert2Pdf) throws Exception {
        String url = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + EsignApiUrl.GET_UPLOAD_FILE_URL;
        GetUploadUrlResp resp = new GetUploadUrlResp();
        EsignApiHeader esignApiHeader = EsignApiHeader.build().appId(appId);
        esignApiHeader.token(tokenCacheManager.getToken(appId));
        EsignFileUploadParams params = new EsignFileUploadParams();
        params.setFileName(fileName);
        params.setContentMd5(fileMd5);
        params.setFileSize(fileSize);
        params.setConvertToPDF(convert2Pdf);
        params.setContentType("application/octet-stream");
        String respStr = HttpClient.httpPostRaw(url, JsonUtils.toJSONString(params),esignApiHeader.convert2Headers(), null);
        EsignBaseResp esignBaseResp = JsonUtils.parseObject(respStr, EsignBaseResp.class);
        Object data = esignBaseResp.getData();
        if (data != null) {
            Map<String,Object> map = (Map<String, Object>) data;
            resp.setFileUploadUrl((String) map.get("fileUploadUrl"));
            resp.setFileId((String) map.get("fileId"));
            return resp;
        }else {
            throw new RuntimeException("获取合同上传地址失败: " + esignBaseResp.getMessage());
        }
    }


    public List<Object> getSignPosition(String appId,String fileId,List<String> keywords) {
        try {
            String reqPath = EsignApiUrl.SIGN_POSITION_URL.replace("{fileId}", fileId);
            String url = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + reqPath;
            EsignApiHeader esignApiHeader = EsignApiHeader.build().appId(appId);
            Map<String,Object> params = new HashMap<>();
            params.put("keywords",keywords);
            esignApiHeader.token(tokenCacheManager.getToken(appId));
            String respStr = HttpClient.httpPostRaw(url,JsonUtils.toJSONString(params),esignApiHeader.convert2Headers(),null);
            Map map = JsonUtils.parseObject(respStr, Map.class);
            Map<String,Object> data = (Map<String,Object>) map.get("data");
            Object[] keywordPositions = (Object[]) data.get("keywordPositions");
            List<Object> resList = new ArrayList<>();
            for (Object position : keywordPositions) {
                resList.add(position);
            }
            return resList;
        }catch (Exception e){

        }
        return new ArrayList<>();
    }

    public List<String> uploadFileToEsign(String appId,String refId) throws Exception {
        String tempDir = System.getProperty("java.io.tmpdir");
        List<String> fileIds = new ArrayList<>();
        File file = null;
        FileUtil fileUtil = new FileUtil();
        try {
            List<String> paths = fileUtil.fieldFileDownload(Long.parseLong(refId), tempDir + File.separator + "oafile" + File.separator);
            for (String path : paths) {
                file = new File(path);
                String contentMD5 = EsignUploadFileService.getFileContentMD5(path);
                GetUploadUrlResp uploadResp = getUploadFileUrl(appId,file.getName(), contentMD5, file.length(),true);
                uploadFile(uploadResp.getFileUploadUrl(), contentMD5, file.getName(), path);
                fileIds.add(uploadResp.getFileId());
            }
            return fileIds;
        }finally {
            if(file != null) {
                file.delete();
            }
        }
    }

    public static String getFileContentMD5(String filePath) throws Exception {
        // 获取文件MD5的二进制数组（128位）
        byte[] bytes = getFileMD5Bytes128(filePath);
        // 对文件MD5的二进制数组进行base64编码
        return new String(Base64.encodeBase64(bytes));
    }

    /***
     * 获取文件MD5-二进制数组（128位）
     *
     * @return
     * @throws IOException
     */
    public static byte[] getFileMD5Bytes128(String filePath) throws Exception {
        byte[] md5Bytes = null;
        File file = new File(filePath);
        try (FileInputStream fis = new FileInputStream(file)) {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) != -1) {
                md5.update(buffer, 0, length);
            }
            md5Bytes = md5.digest();
        }
        return md5Bytes;
    }


    public String uploadFile(String uploadUrl,String contentMD5,String fileName,String filePath) throws Exception {
//        EsignApiHeader esignApiHeader = EsignApiHeader.build();
//        esignApiHeader.setContentType("application/octet-stream");
//        esignApiHeader.setContentMd5(contentMD5);
        EsignHttpResponse esignHttpResponse = EsignHttpHelper.doUploadHttp(uploadUrl, EsignRequestType.PUT, getBytes(filePath), contentMD5, "application/octet-stream", false);
//        return HttpClient.uploadBinaryFile(uploadUrl,esignApiHeader.convert2Headers(),new FileInputStream(file),fileName);
        return esignHttpResponse.getBody();
    }

    public static byte[] getBytes(String filePath) throws Exception {
        File file = new File(filePath);
        FileInputStream fis = null;
        byte[] buffer = null;
        try {
            fis = new FileInputStream(file);
            buffer = new byte[(int) file.length()];
            fis.read(buffer);
        } catch (Exception e) {
            Exception ex = new Exception("获取文件字节流失败", e);
            ex.initCause(e);
            throw ex;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    Exception ex = new Exception("关闭文件字节流失败", e);
                    ex.initCause(e);
                    throw ex;
                }
            }
        }
        return buffer;
    }

}

