package com.fs.wxcid;

import com.alibaba.fastjson.TypeReference;
import com.fs.common.core.redis.RedisCacheT;
import com.fs.common.exception.CustomException;
import com.fs.common.exception.base.BaseException;
import com.fs.company.domain.CompanyWxAccount;
import com.fs.company.mapper.CompanyWxAccountMapper;
import com.fs.wxcid.domain.CidIpadServer;
import com.fs.wxcid.dto.common.ApiResponseCommon;
import com.fs.wxcid.dto.login.RequestBaseVo;
import com.fs.wxcid.service.AdminLicenseService;
import com.fs.wxcid.service.ICidIpadServerService;
import com.fs.wxwork.utils.WxWorkHttpUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
public class ServiceUtils {

    private final CompanyWxAccountMapper companyWxAccountMapper;
    private final ICidIpadServerService cidIpadServerService;
    private final RedisCacheT<CidIpadServer> redisCache;
    private final AdminLicenseService adminLicenseService;
    private final static String KEY = "cid:ipad:servic:";

    private CidIpadServer getService(Long accountId){
        String key = KEY + accountId;
        CidIpadServer service = redisCache.getCacheObject(key);
        if(service == null){
            CompanyWxAccount account = companyWxAccountMapper.selectById(accountId);
            if(account.getServerId() == null){
                throw new BaseException("未绑定服务器");
            }
            service = cidIpadServerService.getById(account.getServerId());
            redisCache.setCacheObject(key, service);
        }
        return service;
    }

    public String getUrl(Long accountId){
        CidIpadServer service = getService(accountId);
        return service.getUrl();
    }
    public String getProxy(Long accountId){
        CidIpadServer service = getService(accountId);
        return service.getProxy();
    }




    public <S, R,T extends ApiResponseCommon<S>> T sendPost(String url, RequestBaseVo<R> r, TypeReference<T> type){
        Long accountId = r.getAccountId();
        String baseUrl = getUrl(accountId) + url + "?key=" + adminLicenseService.getToken(accountId);
        T response = WxWorkHttpUtil.postWithType(baseUrl, r.getData(), type);

        //先判断是否成功
        if (response.getCode() != 200 || response.getData() == null) {
            throw new CustomException("接口请求失败: " + response.getText());
        }
        return response;
    }

    public <S, R,T extends ApiResponseCommon<S>> T sendGet(String url, RequestBaseVo<R> r, TypeReference<T> type){
        Long accountId = r.getAccountId();
        String baseUrl = getUrl(accountId) + url + "?key=" + adminLicenseService.getToken(accountId);
        T response = WxWorkHttpUtil.getWithType(baseUrl, type);

        //先判断是否成功
        if (response.getCode() != 200 || response.getData() == null) {
            throw new CustomException("接口请求失败: " + response.getText());
        }
        return response;
    }
}
