package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.advert.AdvertPlatformOauthContext;
import io.renren.common.advert.AdvertService;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.demo.service.RemoteAdvertPort;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 广告主账号表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2022-06-03
 */
@Service
public class RdAdvertiserServiceImpl extends CrudServiceImpl<RdAdvertiserDao, RdAdvertiserEntity, RdAdvertiserDTO> implements RdAdvertiserService {

    @Autowired
    private AdvertPlatformOauthContext advertPlatformOauthContext;
    @Override
    public QueryWrapper<RdAdvertiserEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String accountId = (String)params.get("accountId");
        String advertiserId = (String)params.get("advertiserId");
        String advertiserName = (String)params.get("advertiserName");
        String role = (String)params.get("role");
        String advertiserStatus = (String)params.get("advertiserStatus");

        QueryWrapper<RdAdvertiserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id).eq("status",1)
                .eq(StringUtils.isNotBlank(accountId), "account_id",accountId)
                .eq(StringUtils.isNotBlank(advertiserId), "advertiser_id",advertiserId)
                .eq(StringUtils.isNotBlank(role), "role",role)
                .eq(StringUtils.isNotBlank(advertiserStatus), "advertiser_status",advertiserStatus)
                .like(StringUtils.isNotBlank(advertiserName),"advertiser_name","%"+advertiserName+"%")
                .orderByDesc("id");

        return wrapper;
    }

    @Override
    public void refreshAdvertiserByAccountIdEntity(AdvertOauthAccountEntity entity) {
        //获取新的广告主账户
        RemoteAdvertPort remoteAdvertPort = advertPlatformOauthContext.getAdvertOauthPortByAnnotation(AdvertService.SERVICE_OAUTH + entity.getAdvertPlatform());
        List<RdAdvertiserDTO> newAdvertiserList = remoteAdvertPort.getAdvertiserIdList(entity.getAccountType(), entity.getAccountId(),entity.getAccessToken());

        //筛选需要删除的广告主账号
        List<RdAdvertiserEntity> oldAdvertiserDeleteList =  baseDao.selectList(new QueryWrapper<RdAdvertiserEntity>()
                .eq("status",1).eq("account_id",entity.getAccountId()));
        if (!CollectionUtils.isEmpty(oldAdvertiserDeleteList)){
            Iterator<RdAdvertiserEntity> advertiserIterator = oldAdvertiserDeleteList.iterator();
            while (advertiserIterator.hasNext()){
                RdAdvertiserEntity advertiserEntity = advertiserIterator.next();
                //最新的广告主账号包含旧的广告主账号，直接移出(不用删除)
                if (!CollectionUtils.isEmpty(newAdvertiserList)){
                    for (RdAdvertiserDTO newAdvertiser:newAdvertiserList){
                        if (newAdvertiser.getAdvertiserId().equalsIgnoreCase(advertiserEntity.getAdvertiserId())){
                            advertiserIterator.remove();//将保留的广告主账户从oldAdvertiserDeleteList移出
                            newAdvertiserList.remove(newAdvertiser);//将保留的广告主账户从新的广告主列表移出（已存在，不用再次新增）
                            break;
                        }
                    }
                }
            }
            if (!oldAdvertiserDeleteList.isEmpty()) {
                for (RdAdvertiserEntity entityDelete:oldAdvertiserDeleteList) {
                    entityDelete.setStatus(0);
                    entityDelete.setDeleteTime(new Date());
                    baseDao.updateById(entityDelete);
                }
            }
        }
        //添加新的广告主账号
        if (!CollectionUtils.isEmpty(newAdvertiserList)){
            RdAdvertiserEntity advertiserEntity;
            for (RdAdvertiserDTO advertister:newAdvertiserList){
                advertiserEntity = new RdAdvertiserEntity();
                BeanUtils.copyProperties(advertister,advertiserEntity);
                advertiserEntity.setCreateTime(new Date());
                advertiserEntity.setUpdateTime(new Date());
                baseDao.insert(advertiserEntity);
            }
        }
    }
}