package com.zhongshu.card.server.core.service.openAPI;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.github.microservice.core.helper.JsonHelper;
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.iot.IotSendGateWayParam;
import com.github.microservice.models.iot.IotSendParam;
import com.github.microservice.net.ResultContent;
import com.zhongshu.card.server.core.dao.org.OrganizationDao;
import com.zhongshu.card.server.core.dao.projectAbout.ProjectIotInfoDao;
import com.zhongshu.card.server.core.domain.projectAbout.ProjectIotInfo;
import com.zhongshu.card.server.core.httpRequest.conf.IotCenterAPIConfig;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.payment.RequestInfoService;
import com.zhongshu.opengateway.client.util.SignUtil;
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;
import org.springframework.util.StopWatch;

import java.util.HashMap;

/**
 * openAPI 的请求调用
 *
 * @author TRX
 * @date 2024/10/14
 */
@Slf4j
@Service
public class OpenApiRequestService extends SuperService {

    @Autowired
    private RequestInfoService requestInfoService;

    @Autowired
    private JsonHelper jsonHelper;

    @Autowired
    private OrganizationDao organizationDao;

    @Autowired
    private ProjectIotInfoDao projectIotInfoDao;

    /**
     * 发送发下数据
     *
     * @param param
     * @param projectOid
     * @return
     */
    public ResultContent sendIotMessage(IotSendParam param, String projectOid) {
        ApiConfParam apiConfParam = IotCenterAPIConfig.getApiConfParam(IotCenterAPIConfig.openAPISendMessage);
        return sendIotRequest(param, projectOid, apiConfParam.getApiName());
    }

    /**
     * 请求物联网接口
     *
     * @param param
     * @param projectOid
     * @return
     */
    public ResultContent sendIotRequest(Object param, String projectOid, String apiName) {
        if (StringUtils.isEmpty(projectOid)) {
            return ResultContent.buildFail("projectOid为空");
        }
        ProjectIotInfo projectIotInfo = projectIotInfoDao.findTopByProjectOid(projectOid);
        if (ObjectUtils.isEmpty(projectIotInfo)) {
            return ResultContent.buildFail(String.format("项目未配置物联网AK/SK信息", projectOid));
        }
        APIResponseModel responseModel = requestAPI(projectIotInfo.getUrl(), apiName,
                projectIotInfo.getAk(), projectIotInfo.getSk(), param);
        if (responseModel.isFailed()) {
            log.error("{} {}", responseModel.getMsg(), projectOid);
            return ResultContent.buildFail(responseModel.getMsg());
        }
        return ResultContent.buildSuccess(responseModel);
    }

    public APIResponseModel requestAPI(
            String url,
            String apiName,
            String ak, String sk, Object data) {
        APIResponseModel responseModel = new APIResponseModel();
        try {
            String authorization = SignUtil.sign(JSONUtil.toJsonStr(data), ak, sk);
            HashMap<String, Object> headers = new HashMap<>();
            headers.put("Authorization", authorization);

            ApiConfParam apiConfParam = new ApiConfParam();
            apiConfParam.setApiName(url);
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            ResponseModel request = HttpClientUtil.request(HttpModel.builder()
                    .url(url + apiName).method(MethodType.Json)
                    .header(headers)
                    .charset("utf-8").body(data).build());
            int code = request.getCode();
            if (code == 200) {
                responseModel = BeanUtil.copyProperties(request.getBody(), APIResponseModel.class);
            } else if (code == 404) {
                responseModel.setIsFailed("404 not found");
            } else {
                responseModel = BeanUtil.copyProperties(request.getBody(), APIResponseModel.class);
            }
            responseModel.setParam(apiConfParam);
            stopWatch.stop();
            responseModel.setMillis(stopWatch.getTotalTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
            responseModel.setIsFailed(String.format("请求出错：%s", e.getMessage()));
            return responseModel;
        }
        // 记录请求日志
        requestInfoService.addIotRequestInfo(data, responseModel);
        return responseModel;
    }

}
