package com.njcn.web.utils;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csb.sdk.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.web.enums.GWSendEnum;
import com.njcn.web.pojo.param.SendParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author wr
 * @description
 * @date 2023/12/6 13:59
 */
@Slf4j
public class GwSendUtil {

    public static final String GWURL = "dwzyywzt-pms3-proxy.com";
    public static final String CODE = "13B9B47F1E483324E05338297A0A0595";

    //最新的上送接口路径
    public static final String NEWGWURL = "http://pms.pms30.com.cn/pms-tech-seval";
    public static final String secretKey = "xQcEF+9hnekk2ZAD1+K1y3PS1d7e3wf0dmPXeeMKf/19qRhyP+4c0FTr70bGINpR";

    /**
     *
     * @param param 上报入参数据
     * @param sendEnum 上送接口枚举
     * @return
     */
    public static Map<String, String> send(SendParam param, GWSendEnum sendEnum) {
        Map<String, String> map = new LinkedHashMap<>();
        try {
            ContentBody cb;
            if (ObjectUtil.isNull(param)) {
                cb = new ContentBody("");
            } else {
                String s = JSONObject.toJSONStringWithDateFormat(param, JSON.DEFFAULT_DATE_FORMAT);
                log.info(Thread.currentThread().getName() + "1.上送网公司信息:" + s);
                cb = new ContentBody(s);
            }
            //ContentBody传递，要求使用post方式进行调用
            //如果需要传递请求参数 可以拼接到请求URL中，或者设置paramsMap参数由SDK内部进行拼接
            HttpParameters.Builder builder = HttpParameters.newBuilder();

            builder.requestURL(sendEnum.getUrl()) // 设置请求的URL,可以拼接URL请求参数
                    .api("zongbuSync") // 设置服务名
                    .version("1.0.0") // 设置版本号
                    .method("post") // 设置调用方式, 必须为 post
                    .contentType("application/json; charset=UTF-8") //设置请求content-type
                    .accessKey("7d4cb2c0afb5468ca56e0654b1a442ef").secretKey("lW2xr6zKjbaqVDOSgQpcGrM6Rg0=");// 设置accessKey 和 设置secretKey

            builder.contentBody(cb);
            String token = LoginToken();
            System.out.println("获取token------->"+token);
            builder.putHeaderParamsMap("x-token", token);
            builder.putHeaderParamsMap("serviceName", sendEnum.getServiceName());
            //进行调用，返回结果
            try {
                HttpReturn ret = HttpCaller.invokeReturn(builder.build());
                String responseStr = ret.getResponseStr();//获取响应的文本串
                if (responseStr.indexOf("\\\"") != -1) {
                    responseStr = responseStr.replace("\\\"", "\"");
                }
                Map mapData = JSON.parseObject(responseStr, Map.class);
                if(mapData.containsKey("error_msg")){
                    throw new BusinessException("国网上送接口超时，请重新上送");
                }
                map.put("succeed", responseStr);
            } catch (HttpCallerException e) {
                // error process
                log.info(Thread.currentThread().getName() + "错误信息:" + e);
                map.put("error", e.toString());
            }
        } catch (Exception e) {
            map.put("error", "当前时间段国网上送请求过多，请稍后再试");
        }
        return map;
    }

    /**
     * 获取token
     * @return
     */
    public static  String LoginToken() {
        String token;
        String clientId = "e512d3940a7d11eeae0cd6fb272b183c";
        String clientSecret = "k8cF9CgXsj/lnuP2C4Vhx8tuNsPwieBIU8n14vHL1EoWSadcX0we2wffjyTUYGsK";

        String userUrl = "http://" + GWURL + "/psr-auth/oauth/accessToken?grant_type={grant_type}&client_id={client_id}&client_secret={client_secret}";
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "credentials");
        map.put("client_id", clientId);
        map.put("client_secret", clientSecret);
        ResponseEntity<Map> userEntity = RestTemplateUtil.get(userUrl, Map.class, map);

        if (userEntity.getStatusCodeValue() == 200) {
            log.info(Thread.currentThread().getName() + "数据：" + userEntity.getBody() + "结束----！");
            //获取返回体
            Map body = userEntity.getBody();
            token = body.get("access_token").toString();
        } else {
            throw new BusinessException("获取数据token出现未知异常！请检查ip端口是否正确！");
        }
        return token;
    }


    /**
     * 新的上送方式
     * @param param
     * @param sendEnum
     * @return
     */
    public static Map<String, String> newSend(SendParam param, GWSendEnum sendEnum) {
        Map<String, String> map = new LinkedHashMap<>();
        try {
            ContentBody cb;
            if (ObjectUtil.isNull(param)) {
                cb = new ContentBody("");
            } else {
                String s = JSONObject.toJSONStringWithDateFormat(param, JSON.DEFFAULT_DATE_FORMAT);
                log.info(Thread.currentThread().getName() + "1.信息:" + s);
                cb = new ContentBody(s);
            }
            //ContentBody传递，要求使用post方式进行调用
            //如果需要传递请求参数 可以拼接到请求URL中，或者设置paramsMap参数由SDK内部进行拼接
            HttpParameters.Builder builder = HttpParameters.newBuilder();

            builder.requestURL(sendEnum.getNewUrl()) // 设置请求的URL,可以拼接URL请求参数
                    .method("post") // 设置调用方式, 必须为 post
                    .contentType("application/json; charset=UTF-8"); //设置请求content-type

            builder.contentBody(cb);

            //进行调用，返回结果
            try {
                HttpReturn ret = HttpCaller.invokeReturn(builder.build());
                String responseStr = ret.getResponseStr();//获取响应的文本串
                System.out.println("获取响应的文本串："+responseStr);
                if (responseStr.indexOf("\\\"") != -1) {
                    responseStr = responseStr.replace("\\\"", "\"");
                }
                Map mapData = JSON.parseObject(responseStr, Map.class);
                if(mapData.containsKey("error_msg")){
                    throw new BusinessException("国网上送接口超时，请重新上送");
                }
                map.put("succeed", responseStr);
            } catch (HttpCallerException e) {
                // error process
                log.info(Thread.currentThread().getName() + "错误信息:" + e);
                map.put("error", e.toString());
            }
        } catch (Exception e) {
            map.put("error", "当前时间段国网上送请求过多，请稍后再试");
        }
        return map;
    }


    /**
     * 用于单次调用的返回
     * @author cdf
     * @date 2024/6/18
     */
    public static Integer returnInfoMsg(List<String> ids, Map<String, String> res) {
        if (res.containsKey("succeed")) {
            String succeed = res.get("succeed");
            if (succeed.contains("\\\"")) {
                succeed = succeed.replace("\\\"", "\"");
            }
            Map mapData = JSON.parseObject(succeed, Map.class);
            String status = mapData.get("status").toString();
            if ("000000".equals(status)) {
                //修改数据上送状态
                String result = mapData.get("result").toString();
                Map mapCount = JSON.parseObject(result, Map.class);
                String count = mapCount.get("count").toString();
                return Integer.valueOf(count);
            } else {
                String errors = mapData.get("errors").toString();
                String errorMsg = " 上送" + ids.size()+"条数据失败,错误信息:" + status + "_" + errors + " ;";
                throw new BusinessException(errorMsg);
            }
        } else {
            throw new BusinessException("当前时间段国网上送请求过多，请稍后再试");
        }


    }
}
