package com.tuoheng.admin.tzhl.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.tzhl.config.TZHLConfig;
import com.tuoheng.admin.tzhl.constant.TZHLConstant;
import com.tuoheng.admin.tzhl.request.TZHLGetTokenRequest;
import com.tuoheng.admin.tzhl.response.TZHLTokenResponse;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.RedisUtils;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class CallTianYiPlatformService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    public String callGet(String apiPath, Object request) {
        String token = this.getToken();
        if (StringUtils.isEmpty(token)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "token不能为空");
        }

        String url = TZHLConfig.tzhlURL + apiPath;
        String properties = "Bearer " + token;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", properties);

        log.info("泰州海陵区城管，url:{}", url);
        log.info("泰州海陵区城管，request:{}", request);

        HttpEntity<Object> httpEntity = new HttpEntity<>(request, headers);
        ResponseEntity<JsonResult> response;
        try {
            response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, JsonResult.class);
        } catch (RestClientException e) {
            log.info("泰州海陵区城管，接口异常, url:{}", url);
            log.info("泰州海陵区城管，接口异常, request:{}", request);
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "泰州海陵区城管，接口异常");
        }

        if (null == response || !response.hasBody()) {
            log.info("泰州海陵区城管，接口返回为空，response为空");
            log.info("泰州海陵区城管，接口返回为空, url:{}", url);
            log.info("泰州海陵区城管，接口返回为空, request:{}", request);
            throw new ServiceException("泰州海陵区城管，接口返回为空");
        }
        if (response.getBody().getCode() != 200) {
            log.info("泰州海陵区城管，接口返回失败，response:{}", response.getBody());
            log.info("泰州海陵区城管，接口返回失败, url:{}", url);
            log.info("泰州海陵区城管，接口返回失败, request:{}", request);
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "泰州海陵区城管，接口返回失败");
        }

//        log.info("泰州海陵区城管，接口返回, response={}", response.getBody().getData());

        return JSONObject.toJSONString(response.getBody().getData());
    }

    public String callPost(String apiPath, Object request) {
        // 获取同行令牌token
        String token = this.getToken();
        if (StringUtils.isEmpty(token)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "token不能为空");
        }
        String properties = "Bearer " + token;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", properties);

        HttpEntity<Object> httpEntity = new HttpEntity<>(request, headers);

        String url = TZHLConfig.tzhlURL + apiPath;
        ResponseEntity<JsonResult> response;

        log.info("泰州海陵区城管，url:{}", url);
        log.info("泰州海陵区城管，request:{}", request);

        try {
            response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, JsonResult.class);
        } catch (Exception e) {
            log.info("泰州海陵区城管，接口异常, url:{}", url);
            log.info("泰州海陵区城管，接口异常, httpEntity:{}", httpEntity);
            throw new ServiceException("泰州海陵区城管，获取token接口异常");
        }
        if (null == response || !response.hasBody()) {
            log.info("泰州海陵区城管，接口返回为空，response为空");
            log.info("泰州海陵区城管，接口返回为空, url:{}", url);
            log.info("泰州海陵区城管，接口返回为空, httpEntity:{}", httpEntity);
            throw new ServiceException("泰州海陵区城管，接口返回为空");
        }
        if (response.getBody().getCode() != 200) {
            log.info("泰州海陵区城管，接口返回失败，response:{}", response.getBody());
            log.info("泰州海陵区城管，接口返回失败, url:{}", url);
            log.info("泰州海陵区城管，接口返回失败, request:{}", request);
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "泰州海陵区城管，接口返回失败");
        }

//        log.info("泰州海陵区城管，接口返回, response={}", response.getBody().getData());

        return JSONObject.toJSONString(response.getBody().getData());
    }

    /**
     * 获取token
     *
     * @return
     */
    public String getToken() {
        TZHLTokenResponse tokenResponse = (TZHLTokenResponse) redisUtils.get(TZHLConstant.HL_TOKEN_KEY);
        if (ObjectUtil.isNotNull(tokenResponse)) {
            return tokenResponse.getToken();
        }
        log.info("redis中不存在泰州海陵区城管token，重新获取");
        TZHLGetTokenRequest request = new TZHLGetTokenRequest();
        request.setTicket(TZHLConfig.tzhlTicket);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(request, headers);
        String url = TZHLConfig.tzhlURL + TZHLConstant.TIAN_YI_API_TICKET_LOGIN;
        ResponseEntity<TZHLTokenResponse> response;
        try {
            response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, TZHLTokenResponse.class);
        } catch (Exception e) {
            log.info("泰州海陵区城管，获取token接口异常, url:{}", url);
            log.info("泰州海陵区城管，获取token接口异常, httpEntity:{}", httpEntity);
            throw new ServiceException("南京海事局，获取token接口异常");
        }
        if (null == response || !response.hasBody()) {
            log.info("泰州海陵区城管，获取token接口失败，response为空");
            log.info("泰州海陵区城管，获取token接口失败, url:{}", url);
            log.info("泰州海陵区城管，获取token接口失败, httpEntity:{}", httpEntity);
            throw new ServiceException("泰州海陵区城管，获取token接口失败");
        }
        tokenResponse = JSONObject.parseObject(JSONObject.toJSONString(response.getBody()), TZHLTokenResponse.class);
        if (!TZHLConstant.RESPONSE_SUCCESS_CODE.equals(tokenResponse.getCode())) {
            log.error("泰州海陵区城管，获取token接口失败,{}", tokenResponse);
            throw new ServiceException("泰州海陵区城管，获取token接口失败");
        }
        redisUtils.set(TZHLConstant.HL_TOKEN_KEY, tokenResponse, 1500); // 过期时间为半小时1800，为防止延迟，缩小一点25分钟失效
        return tokenResponse.getToken();
    }
}
