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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
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 com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class RefreshTokenServiceImpl implements IRefreshTokenService {
    @Autowired
    private CtopOauthTokenMapper oauthTokenMapper;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;

    /**
     * 获取所有token
     *
     * @return
     */
    @Override
    public void getKuaiShouRefresh() {
        List<CtopOauthToken> oauthTokens = oauthTokenMapper.selectKuaiShouTokens(CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
        if (!Check.isNull(oauthTokens)) {
            for (CtopOauthToken oauthToken : oauthTokens) {
                XxlJobLogger.log("刷新token,accountId:{}", oauthToken.getAccountId());
                //快手
                if (CtopAdConstant.PLATFORM_TYPE_KUAISHOU.equals(oauthToken.getMediaId().trim())) {
                    oauthTokenService.getKuaiShouRefreshToken(oauthToken.getAccountId(), oauthToken.getAccessToken(), oauthToken.getRefreshToken(), oauthToken.getAgentType());
                }
            }
        } else {
            XxlJobLogger.log("----------------------刷新token获取数据返回结果为空----------------------------------");
        }
    }

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