package org.jeecg.modules.ctop.service.impl;

import cn.com.ctop.common.module.entity.Advertiser;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.vo.SheetInfoVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.ctop.mapper.AdvertiserMapper;
import org.jeecg.modules.ctop.service.IAdvertiserService;
import org.jeecg.modules.excelutil.entity.KuaishouXxlEntity;
import org.jeecg.modules.excelutil.entity.YdPlanAggregateEntity;
import org.jeecg.modules.excelutil.entity.YdWeekAggregateEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 广告主信息表
 * @Author: jeecg-boot
 * @Date: 2019-06-11
 * @Version: V1.0
 */
@Service
public class AdvertiserServiceImpl extends ServiceImpl<AdvertiserMapper, Advertiser> implements IAdvertiserService {

    @Autowired
    private AdvertiserMapper advertiserMapper;

    @Override
    public List<Advertiser> getBySaleId(String saleId) {
        QueryWrapper<Advertiser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sale_id", saleId);
        return this.list(queryWrapper);
    }

    @Override
    public List<UserAllocation> getAllocationsBySaleId(String saleId) {
        return advertiserMapper.getAllocationsBySaleId(saleId);
    }

    @Override
    public SheetInfoVo getXxlStatisticInfo(Long projectId, String systemType, Long accountId, String sheetName) {
        SheetInfoVo vo = new SheetInfoVo<KuaishouXxlEntity>();
        List<KuaishouXxlEntity> details = new ArrayList<>();
        vo.setSheetName(sheetName);
        List<KuaishouXxlEntity> totalList = advertiserMapper.getXXlStatisticInfo(projectId, systemType, accountId, null);
        KuaishouXxlEntity totalEntity = totalList.get(0);
        totalEntity.setDate("汇总");
        details.add(totalEntity);
        details.addAll(advertiserMapper.getXXlStatisticInfo(projectId, systemType, accountId, "state_date"));
        vo.setDetails(details);
        return vo;
    }

    @Override
    public List<SheetInfoVo> getSystemTypeXxlStatisticInfo(Long projectId) {
        List<SheetInfoVo> vos = new ArrayList<>();
        SheetInfoVo android = getXxlStatisticInfo(projectId, "android", null, "android汇总表");
        vos.add(android);
        SheetInfoVo ios = getXxlStatisticInfo(projectId, "ios", null, "ios汇总表");
        vos.add(ios);
        return vos;
    }

    @Override
    public List<SheetInfoVo> getYdStatisticInfo(Long projectId, String startDate, String endDate) throws ParseException {
        List<SheetInfoVo> sheetInfoVos = new ArrayList<>();
        Date start = DateUtils.parseDate(startDate, "yyyy-MM-dd");
        Date end = DateUtils.parseDate(endDate, "yyyy-MM-dd");
        String lastWeekStart = DateUtils.formatDate(DateUtils.addDay(start, -7));
        String lastWeekEnd = DateUtils.formatDate(DateUtils.addDay(end, -7));
        //1：获取周报汇总数据
        SheetInfoVo voFirst = new SheetInfoVo();
        List<YdWeekAggregateEntity> weekEntities = new ArrayList<>();
        YdWeekAggregateEntity lastWeek = advertiserMapper.getYdWeekStatisticInfo(projectId, lastWeekStart + " 00:00:00", lastWeekEnd + " 00:00:00");
        weekEntities.add(lastWeek);
        YdWeekAggregateEntity thWeek = advertiserMapper.getYdWeekStatisticInfo(projectId, startDate + " 00:00:00", endDate + " 00:00:00");
        weekEntities.add(thWeek);
        YdWeekAggregateEntity qoq = new YdWeekAggregateEntity();
        qoq.setDate("环比数据");
        BigDecimal qoqActive = (new BigDecimal(thWeek.getActive()).subtract(new BigDecimal(lastWeek.getActive()))).divide(
                new BigDecimal(lastWeek.getActive()), 5, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
        qoq.setActive(qoqActive.toString() + "%");
        BigDecimal qoqCost = (new BigDecimal(thWeek.getCost()).subtract(new BigDecimal(lastWeek.getCost()))).divide(
                new BigDecimal(lastWeek.getCost()), 5, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
        qoq.setCost(qoqCost.toString() + "%");
        BigDecimal qoqActiveAvg = (new BigDecimal(thWeek.getActiveAvg()).subtract(new BigDecimal(lastWeek.getActiveAvg()))).divide(
                new BigDecimal(lastWeek.getActiveAvg()), 5, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
        qoq.setActiveAvg(qoqActiveAvg.toString() + "%");
        weekEntities.add(qoq);
        voFirst.setSheetName("周数据");
        voFirst.setDetails(weekEntities);
        sheetInfoVos.add(voFirst);
        //2:获取主力计划汇总
        SheetInfoVo secondVo = new SheetInfoVo();
        secondVo.setSheetName("主力计划汇总");
        List<YdPlanAggregateEntity> planAggregateEntities = getYdPlanStatisticInfo(projectId, startDate, endDate);
        secondVo.setDetails(planAggregateEntities);
        sheetInfoVos.add(secondVo);
        return sheetInfoVos;
    }

    @Override
    public List<UserAllocation> getAllocationsByAdvertiserId(String adId) {
        return advertiserMapper.getAllocationsByAdvertiserId(adId);
    }

    @Override
    public List<JSONObject> getAdvertiserByMap(Map<String, String> advertiserIdMap) {
        return advertiserMapper.getAdvertiserByMap(advertiserIdMap);
    }

    private List<YdPlanAggregateEntity> getYdPlanStatisticInfo(Long projectId, String startDate, String endDate) {
        List<YdPlanAggregateEntity> result = new ArrayList<>();
        List<UserAllocation> allocations = userAllocationService.getByParams(projectId, null, null);
        if (null != allocations && !allocations.isEmpty()) {
            allocations.forEach(allocation -> {
                List<YdPlanAggregateEntity> plans = statisticWeekInfoByAccount(allocation, startDate, endDate);
                result.addAll(plans);
            });
        }
        return result;
    }

    private List<YdPlanAggregateEntity> statisticWeekInfoByAccount(UserAllocation allocation, String startDate, String endDate) {
        List<YdPlanAggregateEntity> all = advertiserMapper.getYdWeekPlanStatisticInfoAll(startDate, endDate, allocation.getAccountId());
        List<YdPlanAggregateEntity> big = all.parallelStream().filter(ydPlanAggregateEntity -> new BigDecimal(ydPlanAggregateEntity.getTotalCost()).compareTo(new BigDecimal("10000")) >= 0).collect(Collectors.toList());
        if (null != big || big.size() > 0) {
            return big;
        }
        return all.parallelStream().limit(5).collect(Collectors.toList());
    }

    @Autowired
    private IUserAllocationService userAllocationService;
}
