package com.bcxin.backend.domain.signature.service.impls;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.backend.domain.models.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @create 2024-11-14 15:42
 */
@Slf4j
public class HuNanECUtil {
    private static final Logger logger = LoggerFactory.getLogger(HuNanECUtil.class);

    //
    private static final String client_id = "linewell-oauth";
    //
    private static final String client_secret = "linewell-mobile";
    //
    private static final String grant_type = "password";
    //
    private static final String scope = "readwrite";
    //
    private static final String username = "dzzz_bajgxxxt";
    //
    private static final String password = "Bajgxxxt_6777";

    //token获取接口
    private static final String TOKEN = "/oauth/token";
    //获取文件base64
    private static final String DOWNLOADFILE = "/license/national/downloadfile";
    //token获取接口
    private static final String LICENSEINFOSAVE = "/m/v2/license/license_info/save";

    public static String getToken(String cgiApi){
        String accessToken= "false";
        String getTokenUrl= cgiApi+TOKEN;
        Map<String, Object> formDataMap = new HashMap<>();
        formDataMap.put("client_id",client_id);
        formDataMap.put("client_secret",client_secret);
        formDataMap.put("grant_type",grant_type);
        formDataMap.put("scope",scope);
        formDataMap.put("username",username);
        formDataMap.put("password",password);
        HttpResponse execute = HttpUtil.createPost(getTokenUrl).header("Content-Type", "application/x-www-form-urlencoded")
                .form(formDataMap).execute();
        String responseBody = execute.body();
        if (execute.isOk()){
            Map<String, String> resMap = JSON.parseObject(execute.body(), Map.class);
            accessToken = resMap.get("access_token");
            log.error("获取电子证照token响应体:{}",responseBody);
        }
        return accessToken;
    }

    public static Result xmlDataSend(String cgiApi, String xmlData, String unId, String eCToken){
        Map<String ,String > map = new HashMap<>();
        String xmlDataSendUrl = cgiApi+LICENSEINFOSAVE;
        StringBuilder param = new StringBuilder();

        try {
            param.append(String.format("=========> 资格证签章提交请求地址:%s;", xmlDataSendUrl));
            Map<String, Object> formDataMap = new HashMap<>();
            formDataMap.put("access_token", eCToken);
            formDataMap.put("xml", xmlData);
            formDataMap.put("unid", unId);
            formDataMap.put("state", "2");

            param.append(String.format("=========> 资格证签章提交请求报文:xmlData=%s", xmlData));
            HttpResponse execute = HttpUtil.createPost(xmlDataSendUrl).header("Content-Type", "application/x-www-form-urlencoded")
                    .form(formDataMap).execute();
            int status = execute.getStatus();

            param.append(String.format("=========> 资格证签章提交请求状态码:status=%s", status));
            String responseBody = execute.body();
            if (status == 200) {
                JSONObject jsonObject = JSON.parseObject(responseBody);
                String head = jsonObject.getString("head");
                JSONObject jsonHead = JSON.parseObject(head);
                String headStatus = jsonHead.getString("status");
                String message = jsonHead.getString("message");

                param.append(String.format("=========> 资格证签章返回报文:responseBody=%s", responseBody));
                if (headStatus.equals("0")) {    //若果报错了就不要保存了
                    String data = jsonObject.getString("data");
                    JSONObject jsonData = JSON.parseObject(data);
                    String fileNumber = jsonData.getString("fileNumber");
                    String licenseId = jsonData.getString("licenseId");
                    map.put("fileNumber", fileNumber);
                    map.put("licenseId", licenseId);
                    return new Result().success(message, fileNumber);
                }
                return Result.fail(message);
            }
            return Result.fail("接口请求异常");
        }
        finally {
            logger.error("资格证签章处理跟踪:{}", param);
        }
    }

    //获取证照的base64编码
    public static String getFileRequest(String cgiApi,String fileNumber) {
        String url = cgiApi + DOWNLOADFILE;
        Map<String, Map<String, String>> requestMap = new HashMap<>();
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("certificateIdentifier", fileNumber);
        requestMap.put("head", new HashMap<>());
        requestMap.put("data", dataMap);
        String requestJson = JSON.toJSONString(requestMap);

        logger.warn("=========> 资格证签章获取文件流请求地址：{}", url);
        logger.warn("=========> 资格证签章获取文件流请求报文：{}", requestJson);
        String fileStr = "";
        HttpResponse response = HttpUtil.createPost(url).body(requestJson).execute();
        String responseBody = response.body();
        logger.warn("=========> 资格证签章获取文件流返回报文：{}", responseBody);
        //解析响应体
        Map<String, Map<String, Object>> responseMap = JSON.parseObject(responseBody, Map.class);
        Map<String, Object> head = responseMap.get("head");
        String status = head.get("status").toString();
        if (status.equals("0")) {  //状态为0 说明文件已经盖章完成 、为其它值说明文件还没生成。
            Map<String, Object> data = responseMap.get("data");
            fileStr = data.get("content").toString();
        }

        return fileStr;
    }
}
