package com.malk.ruisi.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.malk.ruisi.service.QysApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class QysApiServiceImpl implements QysApiService {
    @Value("${qiyuesuo.doman}")
    private String QYS_API_DOMAN;
    @Value("${qiyuesuo.token}")
    private String QYS_API_TOKEN;
    @Value("${qiyuesuo.secret}")
    private String QYS_API_SECRET;

    @Override
    public JSONObject sendPost(Map param, String url) throws Exception {
        return sendData(param, true, false, url);
    }

    @Override
    public JSONObject sendGet(Map param, String url) throws Exception {
        return sendData(param, false, false, url);
    }

    @Override
    public JSONObject sendGet(Map param, String url, Boolean isUniCode) throws Exception {
        return sendData(param, false, false, url, isUniCode);
    }

    @Override
    public JSONObject sendPostFile(Map param, String url) throws Exception {
        return sendData(param, true, true, url);
    }

    @Override
    public void getFile(Map param, String url, File file) throws Exception {
        try {
            HttpRequest httpRequest = createRequest(param, false, false, url);
            InputStream is = httpRequest.execute().bodyStream();
            byte[] buf = IoUtil.readBytes(is);
            FileUtil.writeBytes(buf, file);
        } catch (Exception e) {
            throw new Exception("请求契约锁接口异常", e);
        }
    }

    public JSONObject sendData(Map param, Boolean isPost, Boolean isBody, String url) throws Exception {
        JSONObject resultObj = null;
        try {
            HttpRequest httpRequest = createRequest(param, isPost, isBody, url);
            HttpResponse httpResponse = httpRequest.execute();
            log.info("httpResponse:{}", httpResponse);
            String result = httpResponse.body();
            if (ObjectUtil.isNull(result)) {
                throw new Exception("接口返回值为空");
            }
            result = UnicodeUtil.toString(result);
            log.info("result:{}", result);
            resultObj = JSONObject.parseObject(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("请求契约锁接口异常");
        }
        return resultObj;
    }

    public JSONObject sendData(Map param, Boolean isPost, Boolean isBody, String url, Boolean isUnicode) throws Exception {
        JSONObject resultObj = null;
        try {
            HttpRequest httpRequest = createRequest(param, isPost, isBody, url);
            HttpResponse httpResponse = httpRequest.execute();
            log.info("httpResponse:{}", httpResponse);
            String result = httpResponse.body();
            if (ObjectUtil.isNull(result)) {
                throw new Exception("接口返回值为空");
            }
            if (isUnicode) {
                result = UnicodeUtil.toString(result);
            }
            log.info("result:{}", result);
            resultObj = JSONObject.parseObject(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("请求契约锁接口异常");
        }
        return resultObj;
    }

    public HttpRequest createRequest(Map param, Boolean isPost, Boolean isBody, String url) throws Exception {
        String str = param == null || param.isEmpty() ? "" : JSONObject.toJSONString(param);
        log.info("请求地址：{}", url);
        log.info("请求参数：{}", str);
        HttpRequest httpRequest = null;
        if (isPost) {
            if (isBody) {
                httpRequest = HttpUtil.createPost(QYS_API_DOMAN + url).form(param).header("Content-Type", "multipart/form-data;charset=UTF-8");
            } else {
                httpRequest = HttpUtil.createPost(QYS_API_DOMAN + url).body(str).header("Content-Type", "application/json");
            }
        } else {
            httpRequest = HttpUtil.createGet(QYS_API_DOMAN + url).form(param);
        }
        String nowTimestamp = String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        String nonce = UUID.randomUUID().toString();
        log.debug("nowTimestamp:{},nonce:{}", nowTimestamp, nonce);
        httpRequest = httpRequest
                .header("x-qys-accesstoken", QYS_API_TOKEN)
                .header("x-qys-timestamp", nowTimestamp)
                .header("x-qys-nonce", nonce)
                .header("x-qys-signature", SecureUtil.md5(QYS_API_TOKEN + QYS_API_SECRET + nowTimestamp + nonce));
        return httpRequest;
    }

    public static void main(String[] args) {

        String nowTimestamp = String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        String nonce = UUID.randomUUID().toString();
        System.out.println(SecureUtil.md5("wSIHewkJqu" + "IS2QWwM7ktcYa80LzhpvQyHYhYfgBZ" + nowTimestamp + nonce));
        System.out.println(nonce);
        System.out.println(nowTimestamp);
        String config = "{\"daysDefine\":false,\"days\":30,\"noEnabled\":true,\"noDefine\":false,\"signDefine\":false,\"receiveType\":\"NONE\",\"signatories\":[{\"tenantType\":\"COMPANY\",\"serialNo\":1,\"actions\":[{\"type\":\"OPERATOR\",\"name\":\"经办人签字\",\"serialNo\":1},{\"type\":\"CORPORATE\",\"name\":\"企业签章\",\"serialNo\":1}]},{\"tenantType\":\"PERSONAL\",\"serialNo\":2,\"actions\":[{\"type\":\"PERSONAL\",\"name\":\"个人签字\",\"serialNo\":1}]},{\"serialNo\":3,\"actions\":[{\"type\":\"CORPORATE\",\"name\":\"企业签章\",\"serialNo\":1}]}],\"authMode\":\"DEFAULT\",\"personalAuthMode\":\"DEFAULT\",\"showFaceSign\":false,\"faceSign\":false,\"faceIdentificationSign\":false,\"waterMark\":false,\"downloadSwitch\":true,\"downloadPermission\":{\"allable\":false,\"operatorable\":true,\"auditable\":true,\"signable\":true,\"viewable\":true,\"lpable\":true,\"contractable\":true,\"operators\":[]},\"isNotAllowUpload\":false,\"receiverViewConfig\":{\"permissionType\":\"ALLOW\"},\"receiverDownloadConfig\":{\"permissionType\":\"ALLOW\"},\"viewAllContract\":false,\"printSwitch\":true,\"printControl\":false,\"messageNotice\":true,\"signPlatform\":\"PRIVATE\",\"userChoosePlatform\":false,\"extraSign\":true,\"changeSign\":true,\"signConsume\":false,\"signFee\":0,\"mustSign\":true,\"allowReceiverReject\":true,\"sweepCodeAddPersonReceiver\":false,\"checkPersonalSeal\":false,\"sendMessageToSponsor\":true,\"printPermission\":{\"allable\":false,\"operatorable\":true,\"auditable\":true,\"signable\":true,\"viewable\":true,\"lpable\":true,\"contractable\":true}}";

    }
}