package org.dromara.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.log.annotation.Log;

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

@Slf4j
public class SPlatUtils {
    public final static String SPLAT_URL = "http://express-api.fjkhy.cn";

    public static String gettoken() {
        String url = SPLAT_URL+"/outerService/login";
        String param = "?username=khy_baiwei&password="+ SecureUtil.md5("Khy_Baiwei#199$^");
        HttpResponse response = HttpUtil.createGet(url+param)
            .execute();
        for (String cookie : response.headers().get("Set-Cookie")){
            Map<String, String> cookieMap = parseCookie( cookie);
            if(cookieMap.containsKey("satoken"))
                return cookieMap.get("satoken");
        }
        return "";
    }

    public static void SysDevice(List<JSONObject> devices) {
       String token =  gettoken();

        for (JSONObject i :devices) {
            String url = SPLAT_URL+"/outerService/deviceInfo";
            Map<String, String> params = new HashMap<>();
            params.put("deviceId",i.getStr("deviceId"));
            params.put("stationId",i.getStr("stationId"));
            params.put("vid","baiwei");
            params.put("coordinateName","WGS-84");
            params.put("deviceLongitude",i.getStr("location").split(",")[0]);
            params.put("deviceLatitude",i.getStr("location").split(",")[1]);
            log.info(url);
            log.info(JSONUtil.toJsonStr( params));
            HttpResponse response = HttpUtil.createPost(url).header("satoken",token).body(JSONUtil.toJsonStr( params))
                .execute();
            log.info(response.body());
        }

    }

   /**
     * 推送快件信息接口
    *
    *
    */
   public static void pushExpressInfo(List<JSONObject> jsonObjectList){
       String token =  gettoken();
       String url = SPLAT_URL+"/outerService/deviceExpressRegist";
       for (JSONObject jsonObject : jsonObjectList) {
           Map<String,Object> params = new HashMap<>();
           params.put("deviceId",jsonObject.get("deviceId"));
           params.put("vid","baiwei");
           params.put("cpCode",jsonObject.get("cpCode"));
           params.put("scType",jsonObject.get("scType"));
           params.put("scTime", DateUtil.format(jsonObject.getDate("scTime"),"yyyy-MM-dd HH:mm:ss"));
           params.put("waybillNo",jsonObject.get("waybillNo"));
           log.info(url);
           log.info(JSONUtil.toJsonStr( params));
           HttpResponse response = HttpUtil.createPost(url).header("satoken",token).body(JSONUtil.toJsonStr( params))
               .execute();
           log.info(response.body());
       }


   }


    /**
     * 解析 Set-Cookie 字符串为键值对
     *
     * @param setCookie Set-Cookie 字符串
     * @return 包含键值对的 Map
     */
    public static Map<String, String> parseCookie(String setCookie) {
        Map<String, String> cookieMap = new HashMap<>();
        // 按 ";" 将 Cookie 拆分成多个部分
        String[] attributes = setCookie.split(";");
        for (String attribute : attributes) {
            // 按 "=" 分离键和值（注意去掉多余空格）
            String[] keyValue = attribute.trim().split("=", 2); // 限制最多分割成两个部分
            if (keyValue.length == 2) {
                // 如果有键和值，存入 Map
                cookieMap.put(keyValue[0], keyValue[1]);
            } else {
                // 如果只有键（例如 HttpOnly、Secure 没有值），存入 Map，值为 null
                cookieMap.put(keyValue[0], null);
            }
        }
        return cookieMap;
    }
}
