package com.qmth.jkserver.util;

import com.qmth.jkserver.constant.SpringContextHolder;
import com.qmth.jkserver.constant.SystemConstant;
import com.qmth.jkserver.model.SysConfig;
import com.qmth.jkserver.service.CommonCacheService;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

public class WpsUtil {
    private static final Logger log = LoggerFactory.getLogger(WpsUtil.class);

    private static String getGMTDateString() {
        SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss ", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        return format.format(new Date()) + " GMT";
    }

    private static String sha1(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes(StandardCharsets.UTF_8));
            byte[] messageDigest = digest.digest();
            return bytesToString(messageDigest);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String bytesToString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        byte[] var2 = bytes;
        int var3 = bytes.length;

        for (int var4 = 0; var4 < var3; ++var4) {
            byte aByte = var2[var4];
            String shaHex = Integer.toHexString(255 & aByte);
            if (shaHex.length() == 1) {
                hexString.append(0);
            }
            hexString.append(shaHex);
        }
        return hexString.toString();
    }

    /**
     * 执行数据方法
     *
     * @param content
     * @param api
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String exection(String content, String api) throws NoSuchAlgorithmException, IOException {
        Objects.requireNonNull(content, "内容不能为空");
        CommonCacheService commonCacheService = SpringContextHolder.getBean(CommonCacheService.class);

        SysConfig sysConfigWpsDomain = commonCacheService.addSysConfigCache(SystemConstant.WPS_DOMAIN);
        Objects.requireNonNull(sysConfigWpsDomain, "wps域名不能为空");
        Objects.requireNonNull(sysConfigWpsDomain.getConfigValue(), "wps域名值不能为空");

        SysConfig sysConfigWpsAccessKey = commonCacheService.addSysConfigCache(SystemConstant.WPS_ACCESS_KEY);
        Objects.requireNonNull(sysConfigWpsAccessKey, "wps access key不能为空");
        Objects.requireNonNull(sysConfigWpsAccessKey.getConfigValue(), "wps access key值不能为空");

        SysConfig sysConfigWpsSecretKey = commonCacheService.addSysConfigCache(SystemConstant.WPS_SECRET_KEY);
        Objects.requireNonNull(sysConfigWpsSecretKey, "wps secret key不能为空");
        Objects.requireNonNull(sysConfigWpsSecretKey.getConfigValue(), "wps secret key值不能为空");

        Map<String, String> headers = new HashMap<>();
        String contentMd5 = MD5Util.encoder(content);
        headers.put("Content-Md5", contentMd5);
        String date = getGMTDateString();
        String signature = String.format(Locale.US, "WPS-3:%s:%s", sysConfigWpsAccessKey.getConfigValue(), sha1(sysConfigWpsSecretKey.getConfigValue() + contentMd5 + api + SystemConstant.CONTENT_TYPE_JSON + date));
        headers.put("X-Auth", signature);
        headers.put("DATE", date);
        headers.put(HTTP.CONTENT_TYPE, SystemConstant.CONTENT_TYPE_JSON);

        String result = HttpUtil.postJson(sysConfigWpsDomain.getConfigValue() + api, content, headers);
        if (Objects.nonNull(result) && !Objects.equals(result.trim(), "")) {
            log.info("result:{}", JacksonUtil.parseJson(result));
        }
        return result;
    }

    /**
     * 执行数据方法
     *
     * @param content
     * @param params
     * @param api
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String exection(String content, Map<String, Object> params, String api) throws NoSuchAlgorithmException, IOException {
        Objects.requireNonNull(content, "内容不能为空");
        CommonCacheService commonCacheService = SpringContextHolder.getBean(CommonCacheService.class);

        SysConfig sysConfigWpsDomain = commonCacheService.addSysConfigCache(SystemConstant.WPS_DOMAIN);
        Objects.requireNonNull(sysConfigWpsDomain, "wps域名不能为空");
        Objects.requireNonNull(sysConfigWpsDomain.getConfigValue(), "wps域名值不能为空");

        SysConfig sysConfigWpsAccessKey = commonCacheService.addSysConfigCache(SystemConstant.WPS_ACCESS_KEY);
        Objects.requireNonNull(sysConfigWpsAccessKey, "wps access key不能为空");
        Objects.requireNonNull(sysConfigWpsAccessKey.getConfigValue(), "wps access key值不能为空");

        SysConfig sysConfigWpsSecretKey = commonCacheService.addSysConfigCache(SystemConstant.WPS_SECRET_KEY);
        Objects.requireNonNull(sysConfigWpsSecretKey, "wps secret key不能为空");
        Objects.requireNonNull(sysConfigWpsSecretKey.getConfigValue(), "wps secret key值不能为空");

        Map<String, String> headers = new HashMap<>();
        String contentMd5 = MD5Util.encoder(content);
        headers.put("Content-Md5", contentMd5);
        String date = getGMTDateString();
        String signature = String.format(Locale.US, "WPS-3:%s:%s", sysConfigWpsAccessKey.getConfigValue(), sha1(sysConfigWpsSecretKey.getConfigValue() + contentMd5 + api + SystemConstant.CONTENT_TYPE_FORM_DATA + date));
        headers.put("X-Auth", signature);
        headers.put("DATE", date);
//        headers.put(HTTP.CONTENT_TYPE, SystemConstant.CONTENT_TYPE_FORM_DATA);

        String result = HttpUtil.postFile(sysConfigWpsDomain.getConfigValue() + api, params, headers);
        if (Objects.nonNull(result) && !Objects.equals(result.trim(), "")) {
            log.info("result:{}", JacksonUtil.parseJson(result));
        }
        return result;
    }
}
