package cn.com.ctop.toutiao.modules.report.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.toutiao.modules.report.entity.BytedanceAdvertiserDailyReport;
import cn.com.ctop.toutiao.modules.report.entity.BytedanceCheckReportTaskInfo;
import cn.com.ctop.toutiao.modules.report.mapper.BytedanceCheckReportTaskInfoMapper;
import cn.com.ctop.toutiao.modules.report.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 头条数据检查任务记录
 * @author jeecg-boot
 * 2021-06-07
 * @version V1.0
 */
@Service
public class BytedanceCheckReportTaskInfoServiceImpl extends ServiceImpl<BytedanceCheckReportTaskInfoMapper, BytedanceCheckReportTaskInfo> implements IBytedanceCheckReportTaskInfoService {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IBytedanceAdvertiserDailyReportService advertiserDailyReportService;
    @Autowired
    private IBytedanceCampaignDailyReportService campaignDailyReportService;
    @Autowired
    private IReportService reportService;
    @Autowired
    private IBytedanceReportMaterialDailyService materialDailyService;
    @Autowired
    private IBytedanceReportService bytedanceReportService;

    @Override
    public void initTask(String date) {
        List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
        if(null != tokens&&!tokens.isEmpty()){
            tokens.forEach(token->{
                this.saveOrUpdateTaskInfo(token,date);
            });
        }
    }

    private void saveOrUpdateTaskInfo(CtopOauthToken token, String date) {
        BytedanceCheckReportTaskInfo taskInfo = this.getInfoByParams(token.getAccountId(),date);
        if(null == taskInfo){
            taskInfo = new BytedanceCheckReportTaskInfo(token,date);
            this.save(taskInfo);
        }
    }

    @Override
    public BytedanceCheckReportTaskInfo getInfoByParams(Long accountId, String date) {
        QueryWrapper<BytedanceCheckReportTaskInfo> queryWrapper = new QueryWrapper<>();
        if(null!=accountId&&accountId!=0){
            queryWrapper.eq("account_id",accountId);
        }
        if(null!=date&&!"".equals(date.trim())){
            queryWrapper.eq("state_date",date);
        }
        queryWrapper.orderByDesc("id").last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public List<BytedanceCheckReportTaskInfo> getListByParams(Long accountId, String date,Integer status) {
        QueryWrapper<BytedanceCheckReportTaskInfo> queryWrapper = new QueryWrapper<>();
        if(null!=accountId&&accountId!=0){
            queryWrapper.eq("account_id",accountId);
        }
        if(null!=date&&!"".equals(date.trim())){
            queryWrapper.eq("state_date",date);
        }
        if(null!=status){
            queryWrapper.eq("status",status);
        }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }

    @Override
    public void checkCost(BytedanceCheckReportTaskInfo taskInfo){
        CtopOauthToken token = tokenService.getTokenByAccountId(taskInfo.getAccountId());
        if(null == token){
            taskInfo.setStatus(-1);
            taskInfo.setDescription("token数据不存在!");
            taskInfo.setCostStatus(-1);
            taskInfo.setUpdateTime(new Date());
            this.saveOrUpdate(taskInfo);
            return;
        }
        //1:获取账户消耗数据
        BytedanceAdvertiserDailyReport dailyReport = advertiserDailyReportService.getByParams(taskInfo.getAccountId(),taskInfo.getStateDate());
        if(null!=dailyReport){
            taskInfo.setAccountCost(dailyReport.getCost());
        }
        //2:获取组消耗数据
        BytedanceCheckReportTaskInfo campaignTaskInfo = campaignDailyReportService.checkCampaignCostByParams(taskInfo.getAccountId(),taskInfo.getStateDate());
        if(null!=campaignTaskInfo){
            taskInfo.setCampaignCost(campaignTaskInfo.getCampaignCost());
        }
        //3:获取素材消耗数据
        BytedanceCheckReportTaskInfo matTaskInfo = materialDailyService.checkMatCostByParams(taskInfo.getAccountId(),taskInfo.getStateDate());
        if(null!=matTaskInfo){
            taskInfo.setMatCost(matTaskInfo.getMatCost());
        }
        //4:获取图片消耗数据
        BytedanceCheckReportTaskInfo imageTaskInfo = materialDailyService.checkImageCostByParams(taskInfo.getAccountId(),taskInfo.getStateDate());
        if(null!=imageTaskInfo){
            taskInfo.setImageCost(imageTaskInfo.getImageCost());
        }
        if(taskInfo.getAccountCost().compareTo(taskInfo.getCampaignCost())!=0){
            taskInfo.setDescription("账户消耗与组消耗不匹配");
            taskInfo.setStatus(50001);
            taskInfo.setCostStatus(-1);
            this.saveOrUpdate(taskInfo);
            return;
        }
        if(taskInfo.getImageCost().add(taskInfo.getMatCost()).subtract(taskInfo.getAccountCost()).abs().compareTo(new BigDecimal("10"))>0){
            taskInfo.setDescription("账户消耗与素材消耗不匹配");
            taskInfo.setStatus(50001);
            taskInfo.setCostStatus(-2);
            this.saveOrUpdate(taskInfo);
            return;
        }

        taskInfo.setDescription("消耗数据正常");
        taskInfo.setStatus(1);
        taskInfo.setCostStatus(1);
        this.saveOrUpdate(taskInfo);
    }

    @Override
    public void reloadData(BytedanceCheckReportTaskInfo taskInfo){
        CtopOauthToken token = tokenService.getTokenByAccountId(taskInfo.getAccountId());
        BigDecimal accountCost = taskInfo.getAccountCost();
        BigDecimal campaignCost = taskInfo.getCampaignCost();
        BigDecimal imageCost = taskInfo.getImageCost();
        BigDecimal matCost = taskInfo.getMatCost();
        //账户消耗!=组消耗
        if(accountCost.compareTo(campaignCost)!=0){
            reportService.getAdvertiserReport(token, DateUtils.parseDate(taskInfo.getStateDate(),"yyyy-MM-dd"),DateUtils.parseDate(taskInfo.getStateDate(),"yyyy-MM-dd"), CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
            reportService.getAdvertiserCampaignReport(token, DateUtils.parseDate(taskInfo.getStateDate(),"yyyy-MM-dd"),DateUtils.parseDate(taskInfo.getStateDate(),"yyyy-MM-dd"), CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
        }
        if(imageCost.add(matCost).subtract(campaignCost).abs().compareTo(BigDecimal.ZERO)>0){
            reportService.getAdvertiserReport(token, DateUtils.parseDate(taskInfo.getStateDate(),"yyyy-MM-dd"),DateUtils.parseDate(taskInfo.getStateDate(),"yyyy-MM-dd"), CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
            reportService.getAdvertiserCampaignReport(token, DateUtils.parseDate(taskInfo.getStateDate(),"yyyy-MM-dd"),DateUtils.parseDate(taskInfo.getStateDate(),"yyyy-MM-dd"), CtopAdConstant.BYTEDANCE_REPORT_TYPE_DAILY);
            bytedanceReportService.bytedanceMaterialReport(token, taskInfo.getStateDate(), taskInfo.getStateDate());
        }
    }

}
