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

import cn.com.ctop.toutiao.modules.link.entity.EtlDesignDailyReport;
import cn.com.ctop.toutiao.modules.link.mapper.ETLDesignDailyReportMapper;
import cn.com.ctop.toutiao.modules.link.service.IEtlDesignDailyReportService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设计人员日报
 */
@Service
public class EtlDesignDailyReportServiceImpl extends ServiceImpl<ETLDesignDailyReportMapper, EtlDesignDailyReport> implements IEtlDesignDailyReportService {

    @Autowired
    ETLDesignDailyReportMapper etlDesignDailyReportMapper;

    @Override
    public void cleanEtl(String statDate) {
        //查询t-1所有头条、快手素材产生的报表数据
        List<JSONObject> materialReport=etlDesignDailyReportMapper.queryMaterialCostGroupMd5ByStatDate(statDate);
        Map<String, BigDecimal> userMapCost= new HashMap<>();
        materialReport.forEach(m -> {
            if (userMapCost.get(m.getString("clipId")) == null) {
                userMapCost.put(m.getString("clipId"), userMapCost.get(m.getString("clipId"))==null?BigDecimal.ZERO:userMapCost.get(m.getString("clipId")));
            } else {
                userMapCost.put(m.getString("clipId"), userMapCost.get(m.getString("clipId"))==null?BigDecimal.ZERO:userMapCost.get(m.getString("clipId")).add(m.getBigDecimal("cost")));
            }
            if (userMapCost.get(m.getString("planId")) == null) {
                userMapCost.put(m.getString("planId"), userMapCost.get(m.getString("planId"))==null?BigDecimal.ZERO:userMapCost.get(m.getString("planId")));
            } else {
                userMapCost.put(m.getString("planId"), userMapCost.get(m.getString("planId"))==null?BigDecimal.ZERO:userMapCost.get(m.getString("planId")).add(m.getBigDecimal("cost")));
            }
            if (m.getString("shotId") != null) {
                if (userMapCost.get(m.getString("shotId")) == null) {
                    userMapCost.put(m.getString("shotId"), userMapCost.get(m.getString("shotId"))==null?BigDecimal.ZERO:userMapCost.get(m.getString("shotId")));
                } else {
                    userMapCost.put(m.getString("shotId"), userMapCost.get(m.getString("shotId"))==null?BigDecimal.ZERO:userMapCost.get(m.getString("shotId")).add(m.getBigDecimal("cost")));
                }
            }
        });
        //查询所有需要清洗数据的设计人员
        List<EtlDesignDailyReport> allDesign = etlDesignDailyReportMapper.queryAllDesign(statDate);
        allDesign.forEach(it->{
            it.setCost(userMapCost.get(it.getUserId())==null?BigDecimal.ZERO:userMapCost.get(it.getUserId()));
        });
        etlDesignDailyReportMapper.insertBatch(allDesign);
    }
}
