package com.bcxin.signature.config.yesign;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.signature.util.HttpClientUtilSsl;
import com.bcxin.signature.util.SM.SM3Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @author Administrator
 * @create 2024-10-30 16:26
 */
@Slf4j
@Service
public class YesignUtil {

    @Autowired
    private Environment cenv;
    @Value("${signature.usetest}")
    boolean usetest;

    /**
     * OFD位置签章
     */
    public void signPdf(MultipartFile file,String url, String fileName, HttpServletResponse response) throws IOException {
//        String params = handleSignParam(rootPath+tempPDF.replace("temp","in")+"/"+fileName,fileName);
        String params = handleSignParam(file,fileName);
        String res = HttpClientUtilSsl.doPostOfJson(url, params);
        log.error("====> 电子签章定时任务开始.signPdf.res："+res);
        PrintWriter out = response.getWriter();
        out.print(res);
        out.flush();
        out.close();
    }

    private String handleSignParam(MultipartFile file,String fileName) throws IOException {
        SxCertDn sxCertDn = SxCertDn.getByFileName(fileName);
        if(sxCertDn == null){
            return "";
        }
        HashMap m1 = new LinkedHashMap();
        HashMap content = new LinkedHashMap(); // 业务参数
        byte[] base = file.getBytes();
        content.put("fileData", org.apache.commons.codec.binary.Base64.encodeBase64String(base));
        content.put("appId", sxCertDn.getAppId()); // 第三方应用appid
        content.put("certId", sxCertDn.getCertId());
        content.put("fileName", fileName);// 文件名称，传实际签章文件名称

        // 位置签章参数
        List list = new ArrayList();
        HashMap data = new LinkedHashMap();
        data.put("sealId", sxCertDn.getSealId()); // 印章ID
        data.put("pageNum", "1"); // 签章页码 ofd从0开始，pdf从1开始
        data.put("zx", "150"); // 签章位置坐标 ofd以左上角为原点，pdf以左下角为原点
        data.put("zy", "193"); // 签章位置坐标
        data.put("certDN", sxCertDn.getCertDN());
        data.put("secretKey", sxCertDn.getSecretKey()); // 密钥
        data.put("keyPin", "");
        list.add(data);
        content.put("signList", list);

        m1.put("message_header", handleHeader1(content,sxCertDn.getAppKey()));
        m1.put("message_content", content);
        JSONObject o1 = new JSONObject(m1);
        String re = o1.toJSONString();
        return re;
    }

    private static HashMap handleHeader1(HashMap content,String appKey) {
        HashMap header = new LinkedHashMap();
        header.put("sign", "");
        header.put("ctime", DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
        header.put("version", "1.0");
        JSONObject o = new JSONObject(content);
        String re1 = o.toJSONString();
        String mac = null;
        try {
            mac = SM3Utils.hmac(appKey, re1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        header.put("hmac", mac);
        return header;
    }

    /**
     * 处理头参数
     */
    private static HashMap handleHeader(String re1, String key) {
        HashMap header = new LinkedHashMap();
        header.put("sign", "");
        header.put("ctime", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        header.put("version", "1.0");
        String mac = null;
        try {
            mac = SM3Utils.hmac(key, re1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        header.put("hmac", mac);
        return header;
    }
}
