package com.sckw.slope.detection.service.api;

import com.alibaba.fastjson2.JSONObject;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.OkHttpUtils;
import com.sckw.core.utils.UUIDUtils;
import com.sckw.core.web.response.HttpResult;
import com.sckw.core.web.response.PhpResult;
import com.sckw.slope.detection.model.dto.SystemDict;
import com.sckw.slope.detection.model.param.SmsMessageParam;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.utils.MD5Utils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * @author lfdc
 * @description 对外请求接口地址
 * @date 2023-10-30 08:10:40
 */
@Slf4j
@Service
@Component
public class DetectionApiService {

    private String okHttpClientUrl = "http://10.10.10.220";
    private String okHttpClientUrlTest = "http://10.10.10.185:9501";

    public HttpResult toSaasPostDemo() {
        OkHttpUtils okHttpUtils = OkHttpUtils.builder().url(okHttpClientUrl + "/api/menu/getMenu");
        okHttpUtils.addHeader("adminid", "4f98414ac8411d85b45146659780c4aa6e104347");
        Map<String, Object> para = new HashMap<>();
        if (!CollectionUtils.isEmpty(para)) {
            for (Map.Entry<String, Object> p : para.entrySet()) {
                //跳过非空参数
                Object v = p.getValue();
                String k = p.getKey();
                if (Objects.isNull(v)) {
                    continue;
                }
                okHttpUtils.addBodyPara(k, JSONObject.toJSONString(v));
            }
        }
        String sync;
        try {
            sync = okHttpUtils.post(true).sync();
        } catch (Exception e) {
            log.error("http post error ", e.getCause());
            throw new RuntimeException("http post error异常!");
        }
        JSONObject parse = new JSONObject();
        if (StringUtils.isNotBlank(sync)) {
            parse = JSONObject.parse(sync);
        }
        log.info("返回值->{}", sync);
        return HttpResult.ok(parse);
    }


    public HttpResult toSaasGetDemo() {
        OkHttpUtils okHttpUtils = OkHttpUtils.builder().url(okHttpClientUrl);
        Map<String, Object> para = new HashMap<>();
        if (!CollectionUtils.isEmpty(para)) {
            for (Map.Entry<String, Object> p : para.entrySet()) {
                //跳过非空参数
                Object v = p.getValue();
                String k = p.getKey();
                if (Objects.isNull(v)) {
                    continue;
                }
                okHttpUtils.addBodyPara(k, JSONObject.toJSONString(v));
            }
        }
        String sync;
        try {
            sync = OkHttpUtils.builder().url(okHttpClientUrl + "/api/admin/getUserInfo").addHeader("adminid", "4f98414ac8411d85b45146659780c4aa6e104347").get().sync();
        } catch (Exception e) {
            log.error("http get error ", e.getCause());
            throw new RuntimeException("http get error 异常!");
        }
        JSONObject parse = new JSONObject();
        if (StringUtils.isNotBlank(sync)) {
            parse = JSONObject.parse(sync);
        }
        log.info("返回值->{}", sync);
        return HttpResult.ok(parse);
    }

    public PhpResult toSaasGetDict(String okHttpClientUrl, String address, Map<String, Object> paraBody, Map<String, String> paraPara) {
        OkHttpUtils okHttpUtils = OkHttpUtils.builder().url(okHttpClientUrl + address);
//        Map<String, Object> para = new HashMap<>();
        if (!CollectionUtils.isEmpty(paraBody)) {
            for (Map.Entry<String, Object> p : paraBody.entrySet()) {
                //跳过非空参数
                Object v = p.getValue();
                String k = p.getKey();
                if (Objects.isNull(v)) {
                    continue;
                }
//                okHttpUtils.addBodyPara(k, JSONObject.toJSONString(v));
                okHttpUtils.addBodyPara(k, v.toString());
            }
        }
        if (!CollectionUtils.isEmpty(paraPara)) {
            paraPara.forEach(okHttpUtils::addPara);
//            for (Map.Entry<String, Object> p : paraPara.entrySet()) {
//                //跳过非空参数
//                Object v = p.getValue();
//                String k = p.getKey();
//                if (Objects.isNull(v)) {
//                    continue;
//                }
//                okHttpUtils.addPara(k, v.toString());
//            }
        }
        String sync;
        try {
            sync = okHttpUtils.addHeader("adminid", "4f98414ac8411d85b45146659780c4aa6e104347").get().sync();
        } catch (Exception e) {
            log.error("http get error ", e.getCause());
            throw new RuntimeException("http get error 异常!");
        }
        PhpResult result = new PhpResult();
        Map<String, SystemDict> map = new HashMap(NumberConstant.SIXTEEN);
        if (StringUtils.isNotBlank(sync)) {
            result = JSONObject.parseObject(sync, PhpResult.class);
            if (result.isStatus()) {
                HashMap hashMap = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), HashMap.class);
                for (Object value : hashMap.values()) {
                    SystemDict systemDict = JSONObject.parseObject(value.toString(), SystemDict.class);
                    map.put(systemDict.getValue(), systemDict);
                }
            }
        }
        log.info("返回值->{}", sync);

        return result;
    }

    public static void main(String[] args) throws Exception {
        SmsMessageParam param = new SmsMessageParam();
        param.setCode("");
        param.setType(2);
        List<String> stringList = new ArrayList<>();
        stringList.add("18215677925");
        param.setPushTo(stringList);
        SmsMessageParam.Content content = new SmsMessageParam.Content();
        content.setTemplateCode("SMS_464035567");
        content.setSignName("开物云ECO");
        Map<String, String> templateParam = new HashMap<>();
        templateParam.put("name","设备一号");
        templateParam.put("time","2023-12-03 11:00:20");
        content.setTemplateParam(templateParam);
        param.setContent(content);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("sign", new MD5Utils().getMd5("sign"));
        headerMap.put("account", "zhangsan");
        headerMap.put("msgId", UUIDUtils.get32UUID());
//        pushSmsMessage("http://10.10.10.149:8830/msg_api/push", JSONObject.toJSONString(param));
        pushSmsMessage("http://10.10.10.223:8830/msg_api/push", JSONObject.toJSONString(param));
    }

    private static OkHttpClient client = new OkHttpClient();

    private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");

    public static JSONObject pushSmsMessage(String url, String json) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("sign", new MD5Utils().getMd5("sign"))
                .addHeader("account", "zhangsan")
                .addHeader("msgId", UUIDUtils.get32UUID())
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
//            System.out.println(JSONObject.toJSONString(response));
            System.out.println("请求响应状态码：" + response.code());
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                log.info("响应信息：{}", responseBody);
                return JSONObject.parseObject(responseBody);
            } else {
                int code = response.code();
                JSONObject resp = new JSONObject();
                resp.put("code", code);
                resp.put("success", false);
                resp.put("message", "http状态响应异常");
                return resp;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static JSONObject pushEmailMessage(String url, String json) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("sign", new MD5Utils().getMd5("sign"))
                .addHeader("account", "zhangsan")
                .addHeader("msgId", UUIDUtils.get32UUID())
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            System.out.println(JSONObject.toJSONString(response));
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                log.info("响应信息：{}", responseBody);
                return JSONObject.parseObject(responseBody);
            } else {
                int code = response.code();
                JSONObject resp = new JSONObject();
                resp.put("code", code);
                resp.put("success", false);
                resp.put("message", "http状态响应异常");
                return resp;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
