package com.heyu.api.controller;

import com.heyu.api.alibaba.request.ACommonTextRequest;
import com.heyu.api.data.constants.ApiConstants;
import com.heyu.api.data.constants.RedisConstans;
import com.heyu.api.data.utils.ApiR;
import com.heyu.api.data.utils.RedisUtils;
import com.heyu.api.data.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Map;

@Slf4j
@SuppressWarnings({"unchecked", "deprecation"})
public class BaseController {

    private static final String BAIDU_API_KEY = "zs9oN4gSuoS3eK8dVJg6jyKh";
    private static final String BAIDU_SECRET_KEY = "uHIRXkj6rbW1eXy8eRVCeP1e3cRQKXay";
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @Autowired
    private RedisUtils redisUtils;



    public  boolean isSuccessStatusCode(Integer statusCode){
        if(statusCode!=null && statusCode==200){
            return true;
        }
        return false;
    }

    protected boolean hasImage(ACommonTextRequest request) {
        return request != null && (!isBlank(request.getImageUrl()) || !isBlank(request.getImageBase64()));
    }

    protected boolean isFaceOrBack(String side) {
        return ApiConstants.face.equals(side) || ApiConstants.back.equals(side);
    }

    protected String thirdError(ApiR<?> apiR) {
        if (apiR != null && !isBlank(apiR.getErrorMsg())) {
            return apiR.getErrorMsg();
        }
        return "识别失败";
    }

    protected boolean isBlank(String value) {
        return value == null || value.trim().length() == 0;
    }

    protected Map<String, Object> requestBaidu(String uri, String content) {
        String result = null;
        try {
            if (StringUtils.isBlank(content)) {
                log.error("请求内容为空，未知异常");
                return null;
            }
            if (content.startsWith("&")) {
                content = content.substring(1);
            }

            Request baiduRequest = createBaiduRequest(uri, content);
            try (Response response = HTTP_CLIENT.newCall(baiduRequest).execute()) {
                result = response.body().string();
                return com.alibaba.fastjson.JSONObject.parseObject(result, Map.class);
            }
        } catch (IOException e) {
            log.error("BaseController requestBaidu 异常", e);
        } finally {
            log.info("BaseController requestBaidu result :{}", result);
        }
        log.error("BaseController requestBaidu 没有返回值。");
        return null;
    }

    private Request createBaiduRequest(String uri, String content) {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, content);
        return new Request.Builder()
                .url("https://aip.baidubce.com/" + uri + "?access_token=" + getBaiduAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
    }

    private String getAccessToken(String apiKey, String secretKey) throws Exception {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + apiKey
                + "&client_secret=" + secretKey);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            return new org.json.JSONObject(response.body().string()).getString("access_token");
        }
    }

    private String getBaiduAccessToken() {
        try {
            String accessTokenKey = BAIDU_API_KEY + ":" + BAIDU_SECRET_KEY + ":token";
            String accessToken = redisUtils.get(accessTokenKey);
            if (StringUtils.isBlank(accessToken)) {
                accessToken = getAccessToken(BAIDU_API_KEY, BAIDU_SECRET_KEY);
                redisUtils.set(accessTokenKey, accessToken, RedisConstans.SECOND_OF_ONE_7_DAY);
            }
            return accessToken;
        } catch (Exception e) {
            log.error("getBaiduToken error", e);
        }
        log.error("getBaiduToken error token is null ");
        return null;
    }

}
