package com.zhongshu.card.server.core.httpRequest;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.StopWatch;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.microservice.core.util.net.apache.HttpClientUtil;
import com.github.microservice.core.util.net.apache.HttpModel;
import com.github.microservice.core.util.net.apache.MethodType;
import com.github.microservice.core.util.net.apache.ResponseModel;
import com.github.microservice.http.APIResponseModel;
import com.github.microservice.http.ApiConfParam;
import com.github.microservice.models.hxz.WxPayResult;
import com.zhongshu.card.server.core.httpRequest.conf.IotCenterAPIConfig;
import com.zhongshu.card.server.core.httpRequest.conf.IotCenterConf;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.payment.RequestInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author TRX
 * @date 2024/6/25
 */
@Slf4j
@Service
public class ApiRequestService extends SuperService {

    @Autowired
    IotCenterConf iotCenterConf;

    @Autowired
    RequestInfoService requestInfoService;

    /**
     * 发送请求
     *
     * @param apiName
     * @param data
     * @return
     */
    public APIResponseModel sendIotCenterAPI(String apiName, Object data) {
        APIResponseModel responseModel = new APIResponseModel();
        responseModel.setRequestData(data);
        if (StringUtils.isEmpty(iotCenterConf.getUrl())) {
            responseModel.setIsFailed("未配置物联网平台URL");
            return responseModel;
        }
        ApiConfParam apiConfParam = IotCenterAPIConfig.getApiConfParam(apiName);
        if (ObjectUtils.isEmpty(apiConfParam)) {
            responseModel.setIsFailed("未找到API配置");
            return responseModel;
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
            String url = iotCenterConf.getUrl() + iotCenterConf.getIotserverName() + apiConfParam.getApiName();
            ResponseModel request = HttpClientUtil.request(HttpModel.builder().url(url).method(
                    MethodType.Json).charset("utf-8").body(data).build());
            if (request.getCode() == 200) {
                responseModel = BeanUtil.copyProperties(request.getBody(), APIResponseModel.class);
            } else {
                responseModel = BeanUtil.copyProperties(request.getBody(), APIResponseModel.class);
            }
            // 请求API参数
            responseModel.setParam(apiConfParam);
        } catch (Exception e) {
            e.printStackTrace();
            responseModel.setIsFailed(String.format("请求出错：%s", e.getMessage()));
            return responseModel;
        }
        stopWatch.stop();
        // 请求时间：毫秒
        responseModel.setMillis(stopWatch.getTotalTimeMillis());
        // 请求日志
        requestInfoService.addIotRequestInfo(data, responseModel);
        return responseModel;
    }

    /**
     * 访问地址
     *
     * @param url
     * @param data
     * @return
     */
    public APIResponseModel sendWxRequest(String url, Object data) {
        APIResponseModel responseModel = new APIResponseModel();
        responseModel.setRequestData(data);

        ApiConfParam apiConfParam = new ApiConfParam();
        apiConfParam.setApiName(url);
        apiConfParam.setMethodType(MethodType.Json.name());

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
            JSONObject jsonObject = JSONUtil.parseObj(JSONUtil.toJsonStr(data));
            responseModel.setParam(apiConfParam);
            ResponseModel request = HttpClientUtil.request(HttpModel.builder().url(apiConfParam.getApiName()).method(
                    MethodType.Json).charset("utf-8").body(jsonObject).build());
            WxPayResult result = null;
            if (request.getCode() == 200) {
                Object object = request.getBody();
                log.info("obj: {}", object);
                responseModel.setIsSuccess();
                result = BeanUtil.copyProperties(request.getBody(), WxPayResult.class);
            } else {
                result = BeanUtil.copyProperties(request.getBody(), WxPayResult.class);
            }

            // 判断是否成功
            if (result.isSuccess()) {
                responseModel.setIsSuccess();
            } else {
                String msg = result.getMsg();
                if (msg != null && msg.contains("每个二维码仅限使用一次")) {
                    msg = "重复扫码";
                }
                responseModel.setIsFailed(msg);
            }
            responseModel.setContent(JSONUtil.toJsonStr(result));
            // 请求API参数
            responseModel.setParam(apiConfParam);
        } catch (Exception e) {
            e.printStackTrace();
            responseModel.setIsFailed(String.format("请求出错：%s", e.getMessage()));
            return responseModel;
        }
        stopWatch.stop();
        // 请求时间：毫秒
        responseModel.setMillis(stopWatch.getTotalTimeMillis());
        // 请求日志
        requestInfoService.addIotRequestInfo(data, responseModel);
        return responseModel;
    }

}
