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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.config.SpringContextUtil;
import io.renren.modules.demo.service.SaveOrUpdateAdvertAccount;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dao.AdvertOauthAccountDao;
import io.renren.modules.sys.entity.AdvertOauthAccountEntity;
import io.renren.modules.sys.entity.AdvertOauthEntity;
import io.renren.modules.sys.service.RdAdvertiserService;
import lombok.extern.slf4j.Slf4j;
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.*;

/**
 * Created by tianlei on  2022/5/30  17:13
 */
@Service
@Slf4j
public class AdvertAccountService implements SaveOrUpdateAdvertAccount {
    @Autowired
    private AdvertOauthAccountDao advertOauthAccountDao;
//    @Autowired
//    private RdAdvertiserService rdAdvertiserService;

    /**
     * 维护授权账号（授权操作）
     * @param advertOauthEntity
     */
    @Override
    public void saveAdvertAccountByGrantOath(AdvertOauthEntity advertOauthEntity, Map<String,String> accountTypeMap) {
        saveAdvertAccount(advertOauthEntity,accountTypeMap);
    }

    /**
     * 维护授权账号（取消授权操作）
     * @param advertOauthEntity
     */
    @Override
    public void saveAdvertAccountByCancelOath(AdvertOauthEntity advertOauthEntity,Map<String,String> accountTypeMap) {
        //清除授权账号
        List<AdvertOauthAccountEntity> list = advertOauthAccountDao.selectList(new QueryWrapper<AdvertOauthAccountEntity>().eq("status",1).eq("oauth_id",advertOauthEntity.getId()));
        if (!CollectionUtils.isEmpty(list)){
            for (AdvertOauthAccountEntity entity:list){
                entity.setStatus(0);
                entity.setDeleteTime(new Date());
                UserDetail userDetail = SecurityUser.getUser();
                entity.setUpdatedBy(userDetail.getId());
                advertOauthAccountDao.updateById(entity);
            }
        }
    }

    /**
     * 维护授权账号（刷新token操作）
     * @param advertOauthEntity
     */
    @Override
    public void saveAdvertAccountByRefreshOathToken(AdvertOauthEntity advertOauthEntity,Map<String,String> accountTypeMap) {
        //更新token（根据oauth_id）
        List<AdvertOauthAccountEntity> list = advertOauthAccountDao.selectList(new QueryWrapper<AdvertOauthAccountEntity>().eq("status",1).eq("oauth_id",advertOauthEntity.getId()));
        if (!CollectionUtils.isEmpty(list)){
            for (AdvertOauthAccountEntity entity:list){
                entity.setAccessToken(advertOauthEntity.getAccessToken());
                entity.setUpdateTime(new Date());
                advertOauthAccountDao.updateById(entity);
            }
        }
    }

    @Override
    public void saveAdvertAccount(AdvertOauthEntity advertOauthEntity,Map<String,String> accountTypeMap) {
        AdvertOauthAccountEntity advertOauthAccountEntity;
        if (accountTypeMap!=null && accountTypeMap.size()>0){
            Set<Map.Entry<String,String>> set = accountTypeMap.entrySet();
            Iterator<Map.Entry<String,String>> iterator = set.iterator();
            while (iterator.hasNext()){
                advertOauthAccountEntity = new AdvertOauthAccountEntity();
                Map.Entry<String,String> entry = iterator.next();
                String accountType = entry.getKey();
                String account = entry.getValue();
                advertOauthAccountEntity.setAccessToken(advertOauthEntity.getAccessToken());
                advertOauthAccountEntity.setAccountType(accountType);
                advertOauthAccountEntity.setAccountId(account);
                advertOauthAccountEntity.setOauthId(advertOauthEntity.getId());
                advertOauthAccountEntity.setAdvertPlatform(advertOauthEntity.getAdvertPlatform());
                advertOauthAccountEntity.setCreateTime(new Date());
                advertOauthAccountEntity.setUpdateTime(new Date());
                UserDetail userDetail = SecurityUser.getUser();
                advertOauthAccountEntity.setUpdatedBy(userDetail.getId());
                advertOauthAccountEntity.setCreatedBy(userDetail.getId());
                advertOauthAccountDao.insert(advertOauthAccountEntity);

                //刷新广告主账号
                AdvertOauthAccountEntity finalAdvertOauthAccountEntity = new AdvertOauthAccountEntity();
                BeanUtils.copyProperties(advertOauthAccountEntity,finalAdvertOauthAccountEntity);
                new Thread(() -> {
                    RdAdvertiserService rdAdvertiserService = SpringContextUtil.getBean(RdAdvertiserService.class);
                    rdAdvertiserService.refreshAdvertiserByAccountIdEntity(finalAdvertOauthAccountEntity);
                }).start();

            }
        }
    }

}
