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.common.utils.DateUtils;
import io.renren.modules.demo.service.RemoteAdvertPort;
import io.renren.modules.sys.dao.AdvertOauthAccountDao;
import io.renren.modules.sys.dao.RdAccountLogDao;
import io.renren.modules.sys.dao.RdAdvertiserDao;
import io.renren.modules.sys.dto.AdvertiserFundTransactionPageDTO;
import io.renren.modules.sys.dto.RdAccountLogDTO;
import io.renren.modules.sys.entity.AdvertOauthAccountEntity;
import io.renren.modules.sys.entity.RdAccountLogEntity;
import io.renren.modules.sys.entity.RdAdvertiserEntity;
import io.renren.modules.sys.service.RdAccountLogService;
import lombok.extern.slf4j.Slf4j;
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.List;
import java.util.Map;

/**
 * 账号流水明细
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2022-06-03
 */
@Service
@Slf4j
public class RdAccountLogServiceImpl extends CrudServiceImpl<RdAccountLogDao, RdAccountLogEntity, RdAccountLogDTO> implements RdAccountLogService {

    @Autowired
    private AdvertOauthAccountDao advertOauthAccountDao;
    @Autowired
    private RdAdvertiserDao rdAdvertiserDao;
    @Autowired
    private AdvertPlatformOauthContext advertPlatformOauthContext;

    @Override
    public QueryWrapper<RdAccountLogEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String advertiserId = (String)params.get("advertiserId");
        String accountCreateTimeStart = (String)params.get("accountCreateTimeStart");
        String accountCreateTimeEnd = (String)params.get("accountCreateTimeEnd");

        QueryWrapper<RdAccountLogEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id).eq("status",1)
                .eq(StringUtils.isNotBlank(advertiserId), "advertiser_id", advertiserId)
                .ge(StringUtils.isNotBlank(accountCreateTimeStart), "account_create_time", accountCreateTimeStart)
                .le(StringUtils.isNotBlank(accountCreateTimeEnd), "account_create_time", accountCreateTimeEnd)
                .orderByDesc("id");

        return wrapper;
    }

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

        date = StringUtils.isNotEmpty(date)?date:DateUtils.format(new Date());

        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());
                    AdvertiserFundTransactionPageDTO advertiserFundTransactionPageDTOReq = new AdvertiserFundTransactionPageDTO(date,advertiserEntity.getAdvertiserId(),account.getAccessToken());
                    AdvertiserFundTransactionPageDTO result = remoteAdvertPort.getAdvertiserFundTransaction(advertiserFundTransactionPageDTOReq,transactionType);
                    if (result!=null && !CollectionUtils.isEmpty(result.getRdAccountLogDTOList())){
                        //判断该广告主账户日流水明细是否已经存在
                        List<RdAccountLogEntity> rdAccountLogEntityList = baseDao.selectList(new QueryWrapper<RdAccountLogEntity>()
                                .eq("status",1).eq("advertiser_id",advertiserEntity.getAdvertiserId()).eq("date",date)
                                .eq("transaction_type",transactionType));
                        if (!CollectionUtils.isEmpty(rdAccountLogEntityList)){
                            //删流水明细
                            for (RdAccountLogEntity rdAccountLogEntity:rdAccountLogEntityList){
                                rdAccountLogEntity.setStatus(0);
                                rdAccountLogEntity.setDeleteTime(new Date());
                                baseDao.updateById(rdAccountLogEntity);
                            }
                        }
                        //添加流水明细
                        RdAccountLogEntity rdAccountLogEntity;
                        for (RdAccountLogDTO rdAccountLogDTO:result.getRdAccountLogDTOList()){
                            rdAccountLogEntity = new RdAccountLogEntity();
                            BeanUtils.copyProperties(rdAccountLogDTO,rdAccountLogEntity);
                            rdAccountLogEntity.setCreateTime(new Date());
                            rdAccountLogEntity.setUpdateTime(new Date());
                            baseDao.insert(rdAccountLogEntity);
                        }
                    }
                }
                Thread.sleep(200);
            }catch (Exception e){
                log.error("refreshAdvertiserAudienceCity advertiserId={},error={}",advertiserEntity.getAdvertiserId(),e);
            }
        }
        /*String[] dates = {"2022-05-20"
                ,"2022-05-21","2022-05-22","2022-05-23","2022-05-24","2022-05-25","2022-05-26","2022-05-27"
                ,"2022-05-28","2022-05-29","2022-05-30","2022-05-31","2022-06-01","2022-06-02","2022-06-03"
                ,"2022-06-04"};
        for (int i=0;i<dates.length;i++){
            date = dates[i];
            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());
                        AdvertiserFundTransactionPageDTO advertiserFundTransactionPageDTOReq = new AdvertiserFundTransactionPageDTO(date,advertiserEntity.getAdvertiserId(),account.getAccessToken());
                        AdvertiserFundTransactionPageDTO result = remoteAdvertPort.getAdvertiserFundTransaction(advertiserFundTransactionPageDTOReq);
                        if (result!=null && !CollectionUtils.isEmpty(result.getRdAccountLogDTOList())){
                            //判断该广告主账户日流水明细是否已经存在
                            List<RdAccountLogEntity> rdAccountLogEntityList = baseDao.selectList(new QueryWrapper<RdAccountLogEntity>()
                                    .eq("status",1).eq("advertiser_id",advertiserEntity.getAdvertiserId()).eq("date",date));
                            if (!CollectionUtils.isEmpty(rdAccountLogEntityList)){
                                //删流水明细
                                for (RdAccountLogEntity rdAccountLogEntity:rdAccountLogEntityList){
                                    rdAccountLogEntity.setStatus(0);
                                    rdAccountLogEntity.setDeleteTime(new Date());
                                    baseDao.updateById(rdAccountLogEntity);
                                }
                            }
                            //添加流水明细
                            RdAccountLogEntity rdAccountLogEntity;
                            for (RdAccountLogDTO rdAccountLogDTO:result.getRdAccountLogDTOList()){
                                rdAccountLogEntity = new RdAccountLogEntity();
                                BeanUtils.copyProperties(rdAccountLogDTO,rdAccountLogEntity);
                                rdAccountLogEntity.setCreateTime(new Date());
                                rdAccountLogEntity.setUpdateTime(new Date());
                                baseDao.insert(rdAccountLogEntity);
                            }
                        }
                    }
                }catch (Exception e){
                    log.error("refreshAdvertiserAudienceCity advertiserId={},error={}",advertiserEntity.getAdvertiserId(),e);
                }
            }
        }*/
    }
}