/**
 * 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.common.utils.DateUtils;
import io.renren.modules.demo.service.RemoteAdvertPort;
import io.renren.modules.sys.dao.*;
import io.renren.modules.sys.dto.RdAudienceCityDTO;
import io.renren.modules.sys.entity.*;
import io.renren.modules.sys.service.ScopeCityCostService;
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.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 刷新受众分析市级数据
 *
 */
@Component("refreshAdvertiserAudienceCityTask")
public class RefreshAdvertiserAudienceCityTask implements ITask{
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private RdAdvertiserDao rdAdvertiserDao;
	@Autowired
	private AdvertOauthAccountDao advertOauthAccountDao;
	@Autowired
	private RdAudienceCityDao rdAudienceCityDao;
	@Autowired
	private ScopeCityCostDao scopeCityCostDao;
	@Autowired
	private ScopeCityCostService scopeCityCostService;
	@Autowired
	private AdvertPlatformOauthContext advertPlatformOauthContext;

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

		//查询所有广告主账号
		List<RdAdvertiserEntity> advertiserEntityList = rdAdvertiserDao.selectList(new QueryWrapper<RdAdvertiserEntity>().eq("status", 1));
		if (advertiserEntityList.isEmpty()) {
			return;
		}

		String date = DateUtils.format(DateUtils.addDateDays(new Date(),-1));
		for (RdAdvertiserEntity advertiserEntity:advertiserEntityList){
			try {
				//查询授权账户表获取token
				AdvertOauthAccountEntity account = advertOauthAccountDao.selectOne(new QueryWrapper<AdvertOauthAccountEntity>().eq("status", 1)
						.eq("account_id", advertiserEntity.getAccountId()).orderByDesc("update_time").last("limit 1"));
				if (account != null) {
					//获取受众分析市级数据
					RemoteAdvertPort remoteAdvertPort = advertPlatformOauthContext.getAdvertOauthPortByAnnotation(AdvertService.SERVICE_OAUTH + advertiserEntity.getAdvertPlatform());
					List<RdAudienceCityDTO> rdAudienceCityDTOList = remoteAdvertPort.getAdvertiserAudienceCity(advertiserEntity.getAdvertiserId(), account.getAccessToken(), date);
					if (!CollectionUtils.isEmpty(rdAudienceCityDTOList)) {
						for (RdAudienceCityDTO rdAudienceCityDTO : rdAudienceCityDTOList) {
							if (rdAudienceCityDTO != null) {
								//判断该广告主受众分析市级数据是否已经存在
								RdAudienceCityEntity rdAudienceCityEntity = rdAudienceCityDao.selectOne(new QueryWrapper<RdAudienceCityEntity>()
										.eq("status", 1).eq("advertiser_id", advertiserEntity.getAdvertiserId()).eq("date", date)
										.eq("province_name", rdAudienceCityDTO.getProvinceName()).eq("city_name", rdAudienceCityDTO.getCityName()));
								if (rdAudienceCityEntity == null) {
									rdAudienceCityEntity = new RdAudienceCityEntity();
									BeanUtils.copyProperties(rdAudienceCityDTO, rdAudienceCityEntity);
									rdAudienceCityEntity.setAdvertiserId(advertiserEntity.getAdvertiserId());
									rdAudienceCityEntity.setDate(date);
									rdAudienceCityEntity.setCreateTime(new Date());
									rdAudienceCityEntity.setUpdateTime(new Date());
									rdAudienceCityDao.insert(rdAudienceCityEntity);
								} else {
									Long id = rdAudienceCityEntity.getId();
									BeanUtils.copyProperties(rdAudienceCityDTO, rdAudienceCityEntity);
									rdAudienceCityEntity.setId(id);
									rdAudienceCityEntity.setUpdateTime(new Date());
									rdAudienceCityDao.updateById(rdAudienceCityEntity);
								}
								//判断该广告主受众城市单价是否已经存在
								ScopeCityCostEntity scopeCityCostEntity = scopeCityCostDao.selectOne(new QueryWrapper<ScopeCityCostEntity>()
										.eq("status", 1).eq("advertiser_id", advertiserEntity.getAdvertiserId()).eq("date", date)
										.eq("province", rdAudienceCityDTO.getProvinceName()).eq("city", rdAudienceCityDTO.getCityName()));
								if (scopeCityCostEntity == null) {
									scopeCityCostEntity = new ScopeCityCostEntity();
									scopeCityCostEntity.setProvince(rdAudienceCityDTO.getProvinceName());
									scopeCityCostEntity.setCity(rdAudienceCityDTO.getCityName());
									scopeCityCostEntity.setAdvertiserId(advertiserEntity.getAdvertiserId());
									RdAdvertiserEntity advertiserEntity1 = rdAdvertiserDao.selectOne(new QueryWrapper<RdAdvertiserEntity>().eq("status", 1)
											.eq("advertiser_id", advertiserEntity.getAdvertiserId()).last("limit 1"));
									scopeCityCostEntity.setAdvertiserName(advertiserEntity1.getAdvertiserName());
									if (rdAudienceCityDTO.getCost().compareTo(BigDecimal.ZERO)==0 || rdAudienceCityDTO.getConverts() == 0) {
										scopeCityCostEntity.setAvgCost(BigDecimal.ZERO);
									} else {
										scopeCityCostEntity.setAvgCost(rdAudienceCityDTO.getCost().divide(new BigDecimal(rdAudienceCityDTO.getConverts()), 0, BigDecimal.ROUND_HALF_UP));
									}
									scopeCityCostEntity.setDate(DateUtils.stringToDate(date,DateUtils.DATE_PATTERN));
									scopeCityCostEntity.setCreateTime(new Date());
									scopeCityCostEntity.setUpdateTime(new Date());
									scopeCityCostDao.insert(scopeCityCostEntity);
								} else {
									if (rdAudienceCityDTO.getCost().compareTo(BigDecimal.ZERO)==0 || rdAudienceCityDTO.getConverts() == 0) {
										scopeCityCostEntity.setAvgCost(BigDecimal.ZERO);
									} else {
										scopeCityCostEntity.setAvgCost(rdAudienceCityDTO.getCost().divide(new BigDecimal(rdAudienceCityDTO.getConverts()), 0, BigDecimal.ROUND_HALF_UP));
									}
									scopeCityCostEntity.setUpdateTime(new Date());
									scopeCityCostDao.updateById(scopeCityCostEntity);
								}
								//刷新落地城市公司对应的单价以及 分配人数
								scopeCityCostService.refreshCompanyAvgPriceAndAssignPersonCount(scopeCityCostEntity);

							}
						}
					}
				}
				Thread.sleep(200);
			}catch (Exception e){
				logger.error("refreshAdvertiserAudienceCityTask advertiserId={},error={}",advertiserEntity.getAdvertiserId(),e);
			}
		}
	}
}