package com.sptg.ad.biz.receiver;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.sptg.ad.api.entity.*;
import com.sptg.ad.biz.service.*;
import com.sptg.ad.biz.stream.AdvertTaskCallbackReceiverInterface;
import com.sptg.common.core.entity.PublishTaskResult;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.OrgFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *            
 *                
 * description: 广告任务回调消费者
 */
@Component
@Slf4j
@RequiredArgsConstructor
@EnableBinding(value = { AdvertTaskCallbackReceiverInterface.class})
public class AdvertTaskCallbackReceiver {

    private final AdPushDeviceDetailsServiceInterface adPushDeviceDetailsServiceInterface;
    private final AdPushTaskServiceInterface adPushTaskServiceInterface;
    private final AdPushContentServiceInterface adPushContentServiceInterface;
    private final DeviceAdvertService deviceAdvertService;
    private final OrgFeign orgFeign;
    private final DeviceAdvertStatisticsService deviceAdvertStatisticsService;

    @Transactional(rollbackFor = Throwable.class)
    @StreamListener(value = AdvertTaskCallbackReceiverInterface.INPUT)
    public void input(PublishTaskResult taskResult){
        //  更新或保存广告任务与设备的关联记录
        boolean isInsert = this.insertOrUpdateDeviceDetails(taskResult);

        if (isInsert){
            //  获取任务的广告信息
            AdPushTask task = this.adPushTaskServiceInterface.selectById(taskResult.getTaskId());
            List<AdPushContent> contentList = this.adPushContentServiceInterface.getAdPushContents(task.getId());
            List<DeviceAdvert> advertList = new ArrayList<>(contentList.size());
            Organization org = this.orgFeign.getOrgById(task.getOrgId());
            Date now = new Date();
            contentList.forEach(content -> {
                DeviceAdvert advert = new DeviceAdvert();
                advert.setTaskId(task.getId());
                advert.setTaskType(task.getTaskType());
                advert.setAdCode(content.getAdCode());
                advert.setAdName(content.getAdTitle());
                advert.setAdType(content.getAdTypeName());
                advert.setOrgName(org.getName());
                advert.setOrgPosition(task.getOrgPosition());
                advert.setCreateName(task.getCreateAccountName());
                advert.setCreateTime(now);
                advert.setBeginTime(task.getBeginDate());
                advert.setEndTime(task.getEndDate());
                advert.setStatus(0);
                advert.setMonthPlayVolume(0L);
                advert.setTotalPlayVolume(0L);
                advert.setSerialNumber(taskResult.getSerialNumber());
                advertList.add(advert);
            });
            //  保存广告与设备的关联记录
            this.deviceAdvertService.insertBatch(advertList);
            //  更新设备广告统计表
            DeviceAdvertStatistics statistics = this.deviceAdvertStatisticsService.selectCurrentMonthAdvertStatistics(taskResult.getDeviceId(), task.getTaskType());
            statistics.setPublishCount(statistics.getPublishCount() + contentList.size());
            statistics.setAdCount(statistics.getAdCount() + contentList.size());
            statistics.setDeviceSerialNumber(taskResult.getSerialNumber());
            this.deviceAdvertStatisticsService.updateById(statistics);
        }
    }

    private boolean insertOrUpdateDeviceDetails(PublishTaskResult taskResult){
        boolean result = true;
        //  获取广告任务与设备的关联
        Wrapper<AdPushDeviceDetails> wrapper = new EntityWrapper<>();
        wrapper.eq("l_task_id", taskResult.getTaskId());
        wrapper.eq("l_device_id",taskResult.getDeviceId());
        AdPushDeviceDetails deviceDetails = this.adPushDeviceDetailsServiceInterface.selectOne(wrapper);
        if (null == deviceDetails){
            deviceDetails = new AdPushDeviceDetails();
        }else {
            //  3表示正在向设备推送
            int inRelease = 3;
            //  推送成功，并且是第一次推送成功
            result = taskResult.getPushStatus() == inRelease && !deviceDetails.getPushStatus().equals(taskResult.getPushStatus());
        }
        deviceDetails.setTaskId(taskResult.getTaskId());
        deviceDetails.setDeviceId(taskResult.getDeviceId());
        deviceDetails.setDeviceName(taskResult.getDeviceName());
        deviceDetails.setSerialNumber(taskResult.getSerialNumber());
        deviceDetails.setInstallPath(taskResult.getInstallPath());
        deviceDetails.setXqName(taskResult.getXqName());
        deviceDetails.setDyName(taskResult.getDyName());
        deviceDetails.setPushStatus(taskResult.getPushStatus());
        deviceDetails.setRemark(taskResult.getRemark());
        //  更新或保存记录
        this.adPushDeviceDetailsServiceInterface.insertOrUpdate(deviceDetails);
        return result;
    }
}
