package com.fs.wxcid.service.impl;

import com.fs.common.core.redis.RedisCacheT;
import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.StringUtils;
import com.fs.wxcid.dto.common.ApiResponse;
import com.fs.wxcid.dto.admin.GenAuthKey1Request;
import com.fs.wxcid.dto.admin.GenAuthKey3Request;
import com.fs.wxcid.dto.common.ApiResponseCommon;
import com.fs.wxcid.dto.user.DelayAuthKeyRequest;
import com.fs.wxcid.dto.user.DeleteAuthKeyRequest;
import com.fs.wxcid.dto.user.DisableAuthKeyRequest;
import com.fs.wxcid.service.AdminLicenseService;
import com.fs.wxwork.utils.WxWorkHttpUtil;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class AdminLicenseServiceImpl implements AdminLicenseService {
    // 接口地址 这个后续优化为从数据库中获取
    private static final String BASE_URL = "http://114.117.215.244:7006";
    private static final String KEY = "df704bd7012548049e68db25aff0507f";
    private static final String TOKEN_KEY = "wx:pad:authKey:";
    @Autowired
    private RedisCacheT<String> redisCache;


    @Override
    public ApiResponse delayAuthKey(String key, DelayAuthKeyRequest request) {
        return post("/admin/DelayAuthKey", key, request);
    }

    @Override
    public ApiResponse deleteAuthKey(String key, DeleteAuthKeyRequest request) {
        return post("/admin/DeleteAuthKey", key, request);
    }

    @Override
    public ApiResponse disableAuthKey(String key, DisableAuthKeyRequest request) {
        return post("/admin/DisableAuthKey", key, request);
    }

    @Override
    public ApiResponse genAuthKey1(String key, GenAuthKey1Request request) {
        return get("/admin/GenAuthKey1", key);
    }

    @Override
    public ApiResponse genAuthKey2(String key) {
        return get("/admin/GenAuthKey2", key);
    }

//    @Override
//    public ApiResponse genAuthKey3(String key, GenAuthKey3Request request) {
//        return post("/admin/GenAuthKey3", key, request);
//    }

    @Override
    public ApiResponse getActiveLicenseKeys(String key) {
        return get("/admin/GetActiveLicenseKeys", key);
    }

    @Override
    public ApiResponse getProxyMappingList(String key) {
        return get("/admin/GetProxyMappingList", key);
    }

    @Override
    public ApiResponse httpSyncLicenseKey(String key) {
        return get("/admin/HttpSyncLicenseKey", key);
    }

    @Override
    public List<String> genAuthKey3(String key, GenAuthKey3Request request) {
        String url = BASE_URL + "/admin/GenAuthKey3" + "?key=" + key;
        ApiResponseCommon<List<String>> listApiResponseCommon = WxWorkHttpUtil.postWithType(
                url,
                request,
                new TypeReference<ApiResponseCommon<List<String>>>() {
                }
        );
        log.info("获取授权码结果列表: {}", listApiResponseCommon.getData());
        if(listApiResponseCommon.getCode() == 200){
            return listApiResponseCommon.getData();
        }else{
            throw new BaseException("授权码生成失败：" +  listApiResponseCommon.getText());
        }
    }

    @Override
    public String getToken(Long accountId) {
        String key = TOKEN_KEY + accountId;
        String token = redisCache.getCacheObject(key);
        if(StringUtils.isNotEmpty(token)){
            return token;
        }
        List<String> list = genAuthKey3(KEY, GenAuthKey3Request.builder().Count(1).Type(30000).build());
        token = list.get(0);
        redisCache.setCacheObject(key, token);
        return token;
    }

    // ------------------ 工具方法 ------------------
    /**
     * 通用 POST 请求方法
     *
     * @param path   接口路径，如 "/friend/AgreeAdd"
     * @param key    账号唯一标识（query 参数）
     * @param request 请求体对象
     * @return 统一响应结果
     */
    private ApiResponse post(String path, String key, Object request) {
        String url = BASE_URL + path + "?key=" + key;
        return WxWorkHttpUtil.postWithType(url, request, new TypeReference<ApiResponse>() {});
    }

    /**
     * 通用 GET 请求方法（无请求体）
     *
     * @param path 接口路径
     * @param key  账号唯一标识
     * @return 统一响应结果
     */
    private ApiResponse get(String path, String key) {
        String url = BASE_URL + path;
        Map<String, Object> params = new HashMap<>();
        params.put("key", key);
        String resp = WxWorkHttpUtil.get(url, params);
        return com.alibaba.fastjson.JSON.parseObject(resp, ApiResponse.class);
    }
}