/**
 * 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.AdvertPlatformOauthContext;
import io.renren.common.advert.AdvertService;
import io.renren.modules.demo.service.RemoteAdvertPort;
import io.renren.modules.sys.dao.AdvertOauthAccountDao;
import io.renren.modules.sys.dao.RdAdvertiserDao;
import io.renren.modules.sys.dto.RdAdvertiserDTO;
import io.renren.modules.sys.entity.AdvertOauthAccountEntity;
import io.renren.modules.sys.entity.RdAdvertiserEntity;
import io.renren.modules.sys.service.RdAdvertiserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 根据授权账号定时刷新广告主账号
 */
@Component("refreshAdvertiserTask")
public class RefreshAdvertiserTask implements ITask{
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private AdvertOauthAccountDao advertOauthAccountDao;
	@Autowired
	private RdAdvertiserService rdAdvertiserService;

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

		//获取所有的授权账号
		List<AdvertOauthAccountEntity> oauthAccountEntityList = advertOauthAccountDao.selectList(new QueryWrapper<AdvertOauthAccountEntity>().eq("status", 1));
		if (oauthAccountEntityList.isEmpty()) {
			return;
		}

		Set<String> existAdvertAccountSet = new HashSet<>();
		Iterator<AdvertOauthAccountEntity> iterator = oauthAccountEntityList.iterator();
		while (iterator.hasNext()){
			AdvertOauthAccountEntity entity = iterator.next();
			String advertAccountStr = entity.getAdvertPlatform()+"-"+entity.getAccountType()+"-"+entity.getAccountId();
			//重复的授权账号移出
			if (existAdvertAccountSet.contains(advertAccountStr)){
				iterator.remove();
			}
			existAdvertAccountSet.add(advertAccountStr);
		}
		if (CollectionUtils.isEmpty(oauthAccountEntityList)){
			return;
		}
		//刷新广告主账号
		for (AdvertOauthAccountEntity entity:oauthAccountEntityList) {
			try{
				rdAdvertiserService.refreshAdvertiserByAccountIdEntity(entity);
				Thread.sleep(200);
			}catch (Exception e){
				logger.error("refreshAdvertiserTask accountId={},error={}",entity.getAccountId(),e);
			}
		}

	}
}