package com.weaver.seconddev.chapanda.beisen.util;

import com.alibaba.fastjson.JSONObject;
import com.weaver.common.cache.base.BaseCache;
import com.weaver.seconddev.chapanda.beisen.cache.BeisenTokenCacheKey;
import com.weaver.seconddev.chapanda.beisen.constant.Constants;
import com.weaver.seconddev.chapanda.beisen.module.BeisenTokenModuleKey;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;



@Component
public class Token2BeiSenUtil {
    private final static Logger log = LoggerFactory.getLogger(Token2BeiSenUtil.class);

    @Autowired
    private BaseCache baseCache;

    public int earlySecond = 120;

    /***
     * 获取token
     */
    public String getToken(){

        String token = (String) baseCache.get(BeisenTokenModuleKey.BENSENTOKEN_DATACENTER, BeisenTokenCacheKey.BEISEN_TOKEN);
        log.error("token:{}",token);
        try{
            if (StringUtils.isBlank(token)) {
                JSONObject returnJson = getAccessToken();
                log.error("returnJson:{}",returnJson.toJSONString());

                if(returnJson.containsKey("access_token")){
                    token = returnJson.getString("access_token");
                    String expire = returnJson.getString("expires_in");
                    log.error("token22:{}",token);
                    log.error("expire22:{}",expire);
                    if(StringUtils.isNotBlank(expire)){
                        int expire2 = earlySecond;
                        try {
                            if(StringUtils.isNotBlank(expire)){
                                expire2 = Integer.valueOf(expire);
                            }
                        }catch (Exception e){
                            log.error("e3:{}",e);
                        }
                        log.error("expire23:{}",expire2);
                        if(expire2 > 0){
                            log.error("expire3:{}",expire2);
                            baseCache.set(BeisenTokenModuleKey.BENSENTOKEN_DATACENTER, BeisenTokenCacheKey.BEISEN_TOKEN, token, expire2-earlySecond);
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error("e2:{}",e);
        }

        log.error("token4:{}",token);

        return token;
    }

    /***
     * http方式请求获取token
     * @return
     */
    public JSONObject getAccessToken(){
        JSONObject accessTokenJson = new JSONObject();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");

        JSONObject bodyJson = new JSONObject();
        bodyJson.put("app_key", Constants.app_key);
        bodyJson.put("app_secret",Constants.app_secret);
        bodyJson.put("grant_type","client_credentials");

        log.error("bodyJson:{}",bodyJson);
        //"https://openapi.italent.cn/token"
        // "{\n    \"grant_type\":\"client_credentials\",\n    \"app_key\":\"0F0F2B3F6356464EB59FB651E8DAACBA\",\n    \"app_secret\":\"AF4A2BFC6BB741FD9D80B7F56DA07F08F703AC14B40C453E8DA5BCABAF43A003\"\n}"

        RequestBody body = RequestBody.create(mediaType, bodyJson.toJSONString());
        try {
            Request request = new Request.Builder()
                    .url(Constants.tokenUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();

            int code = response.code();
            String msg = response.body().string();
            log.error("code:{}",code);
            log.error("msg:{}",msg);
            if(code == 200){
                if(StringUtils.isNotBlank(msg)){
                    accessTokenJson = JSONObject.parseObject(msg);
                }
            }else{
                log.error("msg:"+msg);
            }
        } catch (IOException e) {
            log.error("IOException:{}",e);
        }
        return accessTokenJson;
    }

    /***
     *
     * @param token
     * @param beishenHost
     * @param offerUrl
     * @param startDate
     * @param startTime
     * @param endDate
     * @param endTime
     * @return
     */
//    public JSONArray queryOfferByDateTime(String token, String beishenHost, String offerUrl, String startDate, String startTime, String endDate, String endTime){
//
//        // https://openapi.italent.cn/TenantBaseExternal/api/v5/Offer/GetByTimeWindow
////        "{\n    \"startTime\": \"2025-06-01T00:00:00\", \n    \"stopTime\": \"2025-06-21T00:00:00\",\n    \"timeWindowQueryType\": 1\n}"
//        JSONArray offerArray = new JSONArray();
//        JSONObject bodyJson = new JSONObject();
//        bodyJson.put("startTime",startDate+"T"+startTime);
//        bodyJson.put("stopTime",endDate+"T"+endTime);
//        bodyJson.put("timeWindowQueryType","1");
//
//        OkHttpClient client = new OkHttpClient().newBuilder()
//                .build();
//        MediaType mediaType = MediaType.parse("application/json");
//        RequestBody body = RequestBody.create(mediaType, bodyJson.toJSONString());
//        try {
//            Request request = new Request.Builder()
//                    .url(beishenHost+offerUrl)
//                    .method("POST", body)
//                    .addHeader("Content-Type", "application/json")
//                    .addHeader("Authorization", "Bearer "+token)
//                    .build();
//            Response response = client.newCall(request).execute();
//
//            int code = response.code();
//            String msg = response.body().string();
//            System.out.println("code:"+code);
//            if(code == 200){
//                if(StringUtils.isNotBlank(msg)){
//                    JSONObject returnJson = JSONObject.parseObject(msg);
//                    if(returnJson.containsKey("code")){
//                        String dataCode = returnJson.getString("code");
//                        if("200".equals(dataCode)){
//                            JSONArray dataArray = returnJson.getJSONArray("data");
//                            offerArray.addAll(dataArray);
//                            String scrollId = returnJson.getString("scrollId");
//                            if(StringUtils.isNotBlank(scrollId)){
//                                queryOfferByscrollId(token,beishenHost, offerUrl, startDate, startTime, endDate, endTime,offerArray);
//                            }
//                        }
//                    }
//                }
//
//            }else{
//                log.error("msg:"+msg);
//            }
//
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return offerArray;
//    }

//    /***
//     *
//     * @param token
//     * @param beishenHost
//     * @param offerUrl
//     * @param startDate
//     * @param startTime
//     * @param endDate
//     * @param endTime
//     * @param offerArray
//     */
//    public void queryOfferByscrollId(String token, String beishenHost, String offerUrl, String startDate, String startTime, String endDate, String endTime,JSONArray offerArray){
//
//        // https://openapi.italent.cn/TenantBaseExternal/api/v5/Offer/GetByTimeWindow
////        "{\n    \"startTime\": \"2025-06-01T00:00:00\", \n    \"stopTime\": \"2025-06-21T00:00:00\",\n    \"timeWindowQueryType\": 1\n}"
//
//        JSONObject bodyJson = new JSONObject();
//        bodyJson.put("startTime",startDate+"T"+startTime);
//        bodyJson.put("stopTime",endDate+"T"+endTime);
//        bodyJson.put("timeWindowQueryType","1");
//
//        OkHttpClient client = new OkHttpClient().newBuilder()
//                .build();
//        MediaType mediaType = MediaType.parse("application/json");
//        RequestBody body = RequestBody.create(mediaType, bodyJson.toJSONString());
//        try {
//            Request request = new Request.Builder()
//                    .url(beishenHost+offerUrl)
//                    .method("POST", body)
//                    .addHeader("Content-Type", "application/json")
//                    .addHeader("Authorization", "Bearer "+token)
//                    .build();
//            Response response = client.newCall(request).execute();
//
//            int code = response.code();
//            String msg = response.body().string();
//            log.error("code:{}",code);
//            if(code == 200){
//                if(StringUtils.isNotBlank(msg)){
//                    JSONObject returnJson = JSONObject.parseObject(msg);
//                    if(returnJson.containsKey("code")){
//                        String dataCode = returnJson.getString("code");
//                        if("200".equals(dataCode)){
//                            JSONArray dataArray = returnJson.getJSONArray("data");
//                            offerArray.addAll(dataArray);
//                            String scrollId = returnJson.getString("scrollId");
//                            if(StringUtils.isNotBlank(scrollId)){
//                                queryOfferByscrollId(token,beishenHost, offerUrl, startDate, startTime, endDate, endTime,dataArray);
//                            }
//                        }
//                    }
//                }
//            }else{
//                log.error("msg:"+msg);
//            }
//
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }




}
