package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.OauthAgentToken;
import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IOauthAgentTokenService;
import cn.com.ctop.common.module.service.IOauthConfigService;
import cn.com.ctop.common.module.service.IRefreshTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.common.module.utils.HttpUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RefreshTokenServiceImpl implements IRefreshTokenService {
    @Autowired
    private CtopOauthTokenMapper oauthTokenMapper;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private IOauthAgentTokenService agentTokenService;
    @Autowired
    private IOauthConfigService configService;
    @Resource(name = "adqRedisTemplate")
    private StringRedisTemplate adqRedisTemplate;
    private static ExecutorService kuaishouTokenExecutorService = Executors.newFixedThreadPool(4);

    /**
     * 获取所有token
     *
     * @return
     */
    @Override
    public void getKuaiShouRefresh() {
        List<CtopOauthToken> oauthTokens = oauthTokenMapper.selectKuaiShouTokens(CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
        if (!Check.isNull(oauthTokens)) {
            Map<Long, String> configMap = configService.getConfigMapByMediaId(CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT);
            for (CtopOauthToken oauthToken : oauthTokens) {
                XxlJobHelper.log("刷新token,accountId:{}", oauthToken.getAccountId());
                //快手
                if (CtopAdConstant.PLATFORM_TYPE_KUAISHOU.equals(oauthToken.getMediaId().trim())) {
                    String secret = configMap.get(oauthToken.getAppId());
                    kuaishouTokenExecutorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            oauthTokenService.getKuaiShouRefreshToken(oauthToken.getAccountId(), oauthToken.getAccessToken(), oauthToken.getRefreshToken(), oauthToken.getAppId(), secret);

                        }
                    });
                }
            }
        } else {
            XxlJobHelper.log("----------------------刷新token获取数据返回结果为空----------------------------------");
        }
    }

    @Override
    public void byteDanceRefresh(String accountId) {
        if (null == accountId || "".equals(accountId.trim()) || "null".equalsIgnoreCase(accountId)) {
            List<CtopOauthToken> byteDanceOauthTokens = oauthTokenMapper.selectToutiaoToken();
            if (!Check.isNull(byteDanceOauthTokens)) {
                for (CtopOauthToken oauthToken : byteDanceOauthTokens) {
                    oauthTokenService.getByteDanceAccessToken(oauthToken);
                }
            }
        } else {
            CtopOauthToken token = oauthTokenMapper.selectByAccountId(Long.parseLong(accountId));
            if (token == null) {
                XxlJobHelper.log("未获取到账户数据,accountId:{}", accountId);
                return;
            }
            oauthTokenService.getByteDanceAccessToken(token);
        }
    }


    @Override
    public void bytedanceRefreshAgentToken(String agentId) {
        if (Check.isNull(agentId)) {
            List<JSONObject> tokens = oauthTokenMapper.queryBytedanceAgentTokens();
            if (!Check.isNull(tokens)) {
                for (JSONObject token : tokens) {
                    oauthTokenService.refreshAgentBytedanceToken(token);
                }
            }
        } else {
            JSONObject token = oauthTokenMapper.queryBytedanceAgentTokenByAccountId(Long.parseLong(agentId));
            if (token == null) {
                XxlJobHelper.log("未获取到代理商账户数据,accountId:{}", agentId);
                return;
            }
            oauthTokenService.refreshAgentBytedanceToken(token);
        }
    }

    @Override
    public void adqRefreshTokenJob() {
        List<JSONObject> tokenList = oauthTokenService.getAdqTokenList();
        if (Check.isNull(tokenList)) {
            return;
        }
        for (JSONObject tokenJson : tokenList) {
            Long adminAdvertiserId = tokenJson.getLong("adminAdvertiserId");
            String clientId = tokenJson.getString("clientId");
            String clientSecret = tokenJson.getString("clientSecret");
            String refreshToken = tokenJson.getString("refreshToken");
            Map<String, Object> param = new HashMap<>();
            param.put("client_id", clientId);
            param.put("client_secret", clientSecret);
            param.put("refresh_token", refreshToken);
            param.put("grant_type", "refresh_token");
            String s = HttpUtils.httpGet("https://api.e.qq.com/oauth/token", param, new HashMap<>());
            JSONObject tokenResult = JSONObject.parseObject(s);
            System.err.println(tokenResult);
            if (Check.isNull(tokenResult)) {
                continue;
            }
            Integer code = tokenResult.getInteger("code");
            if (code != 0) {
                continue;
            }
            JSONObject data = tokenResult.getJSONObject("data");
            if (Check.isNull(data)) {
                continue;
            }
            String updateAccessToken = data.getString("access_token");
            String updateRefreshToken = data.getString("refresh_token");
            oauthTokenService.updateAdqToken(adminAdvertiserId, updateAccessToken, updateRefreshToken);
            // 同步到 ADQ 独立 Redis，key 规则：adq:access_token:{adminAdvertiserId}
            try {
                String redisKey = "adq:access_token:" + adminAdvertiserId;
                Integer expiresIn = data.getInteger("expires_in");
                if (expiresIn != null && expiresIn > 0) {
                    adqRedisTemplate.opsForValue().set(redisKey, updateAccessToken, expiresIn, TimeUnit.SECONDS);
                } else {
                    adqRedisTemplate.opsForValue().set(redisKey, updateAccessToken);
                }
                XxlJobHelper.log("ADQ token 已同步到 Redis, account:{}, key:{}", adminAdvertiserId, redisKey);
            } catch (Exception e) {
                log.error("ADQ token 同步到 Redis 失败, account:{}", adminAdvertiserId, e);
            }
        }
    }

    @Override
    public void getKuaiShouAgentRefresh() {
        QueryWrapper<OauthAgentToken> agentTokenQueryWrapper = new QueryWrapper<>();
        agentTokenQueryWrapper.eq("media_id", 2);
        List<OauthAgentToken> list = agentTokenService.list(agentTokenQueryWrapper);
        if (!Check.isNull(list)) {
            for (OauthAgentToken agentToken : list) {
                oauthTokenService.getKuaiShouAgentRefreshToken(agentToken.getId(), agentToken.getAgentId(), agentToken.getAccessToken(), agentToken.getRefreshToken(), agentToken.getAppId(), agentToken.getSecret());
            }
        }
    }


    /**
     * 获取所有token
     *
     * @return
     */
    @Override
    public void getLiveKuaiShouAgentRefresh() {
        List<OauthAgentToken> list = agentTokenService.getLiveKuaiShouAgentList(2);
        if (!Check.isNull(list)) {
            for (OauthAgentToken agentToken : list) {
                oauthTokenService.getLiveKuaiShouAgentRefreshToken(agentToken.getId(), agentToken.getAccessToken(), agentToken.getRefreshToken(), agentToken.getAppId(), agentToken.getSecret());
            }
        }
    }
}
