/**
 * Copyright (c) 2022 雷掣 All rights reserved.
 *
 * https://www.lc_crm.com
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.job.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.advert.AdvertPlatformAuthStatusEnum;
import io.renren.common.advert.AdvertPlatformOauthContext;
import io.renren.common.advert.AdvertService;
import io.renren.common.utils.DateUtils;
import io.renren.modules.demo.service.RemoteAdvertPort;
import io.renren.modules.sys.dao.AdvertOauthDao;
import io.renren.modules.sys.entity.AdvertOauthEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 刷新即将过期的acceeeToken
 *
 * trefreshOatuthAccessTokenTask为spring bean的名称
 *
 */
@Component("refreshOatuthAccessTokenTask")
public class RefreshOatuthAccessTokenTask implements ITask{
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private AdvertOauthDao advertOauthDao;
	@Autowired
	private AdvertPlatformOauthContext advertPlatformOauthContext;

	@Override
	public void run(String params){
		logger.debug("RefreshOatuthAccessTokenTask定时任务正在执行，参数为：{}", params);

		Date expireTime = DateUtils.addDateMinutes(new Date(),40);
		//检查最近30分钟即将过期的access_token
		List<AdvertOauthEntity> oauthEntityList = advertOauthDao.selectList(new QueryWrapper<AdvertOauthEntity>().eq("status", AdvertPlatformAuthStatusEnum.SUCCESS.name())
				.isNull("delete_time").le("access_token_expire_time",expireTime));
		if (oauthEntityList.isEmpty()) {
			return;
		}

		for (AdvertOauthEntity entity:oauthEntityList){
			try{
				if (entity.getRefreshTokenExpireTime().before(new Date())) {
					//refresh_token过期，授权状态更新为失效状态
					entity.setStatus(AdvertPlatformAuthStatusEnum.INVALID.name());
					entity.setUpdateTime(new Date());
					entity.setAccessToken(null);
					entity.setAccessTokenExpiresIn(null);
					entity.setAccessTokenExpireTime(null);
					entity.setRefreshTokenExpireTime(null);
					entity.setRefreshTokenExpiresIn(null);
					entity.setRefreshToken(null);
					advertOauthDao.updateById(entity);
				}
				//刷新token
				RemoteAdvertPort remoteAdvertPort = advertPlatformOauthContext.getAdvertOauthPortByAnnotation(AdvertService.SERVICE_OAUTH + entity.getAdvertPlatform());
				remoteAdvertPort.refreshToken(entity.getId(),entity.getRefreshToken());
				Thread.sleep(200);

			}catch (Exception e){
				logger.error("refreshOatuthAccessTokenTask oauthId={},error={}",entity.getId(),e);
			}
		}
	}
}