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


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.ctop.material.constants.Check;
import org.jeecg.ctop.material.entity.AccountTrendPojo;
import org.jeecg.ctop.material.mapper.BossDataExhibitionMapper;
import org.jeecg.ctop.material.service.IBossDataExhibitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BossDataExhibitionServiceImpl implements IBossDataExhibitionService {

    @Autowired
    private BossDataExhibitionMapper bossDataExhibitionMapper;


    /**
     *
     * @description: 素材产出占比
     *
     * @param mediaType 1-头条 2-快手
     * @param startTime
     * @param endTime
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getMeterialProduceRate(String mediaType, String startTime, String endTime) {
        Integer stat_tim = DateUtils.getDateInteger(startTime);
        Integer end_tim = DateUtils.getDateInteger(endTime);
        List<Map<String,Object>> resultList = Arrays.asList();
        // 1-头条 2-快手
        if (StringUtils.equals("1",mediaType)){
            resultList = bossDataExhibitionMapper.getMeterialProduceRateBytedance(stat_tim,end_tim);
        }else if (StringUtils.equals("2",mediaType)){
            resultList = bossDataExhibitionMapper.getMeterialProduceRateKuaiShou(stat_tim,end_tim);
        }
        return Result.successMsg(("1".equals(mediaType) ? "【头条】" : "【快手】")+"===素材产出占比查询成功。",resultList);
    }

    /**
     *
     * @description:分公司素材消耗
     *
     * @param mediaType 1-头条 2-快手
     * @param startTime
     * @param endTime
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getCompanyMeterialConsume(String mediaType, String startTime, String endTime) {
        Integer stat_tim = DateUtils.getDateInteger(startTime);
        Integer end_tim = DateUtils.getDateInteger(endTime);
        List<Map<String,Object>> resultList = Arrays.asList();
        // 1-头条 2-快手
        if (StringUtils.equals("1",mediaType)){
            resultList = bossDataExhibitionMapper.getCompanyMeterialConsumeBytedance(stat_tim,end_tim);
        }else if (StringUtils.equals("2",mediaType)){
            resultList = bossDataExhibitionMapper.getCompanyMeterialConsumeKuaishou(stat_tim,end_tim);
        }
        return Result.successMsg(("1".equals(mediaType) ? "【头条】" : "【快手】")+"===素材消耗查询成功。",resultList);
    }


    /**
     *
     * @description: 素材相关---使用率；爆款率；创新率
     *
     * @param mediaType 1-头条 2-快手
     * @param startTime
     * @param endTime
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getMeterialRelevantInfo(String mediaType, String startTime, String endTime) {
        Map<String,Object> resultMap = new HashMap<>();
        Integer stat_tim = DateUtils.getDateInteger(startTime);
        Integer end_tim = DateUtils.getDateInteger(endTime);
        List<Map<String,Object>> userList = Arrays.asList();
        List<Map<String,Object>> faddishList = Arrays.asList();
        List<Map<String,Object>> innovateList = Arrays.asList();
        // 1-头条 2-快手
        if (StringUtils.equals("1",mediaType)){
            //素材使用率
            userList = bossDataExhibitionMapper.getMeterialUseRateBytedanc(stat_tim,end_tim);
            //素材爆款率
            faddishList = bossDataExhibitionMapper.getMeterialFaddishRateBytedance(stat_tim,end_tim);
            //素材创新率
            innovateList = bossDataExhibitionMapper.getMeterialInnovateRateBytedance(stat_tim,end_tim);
        }else if (StringUtils.equals("2",mediaType)){
            //素材使用率
            userList = bossDataExhibitionMapper.getMeterialUseRateKuaishou(stat_tim,end_tim);
            //素材爆款率
            faddishList = bossDataExhibitionMapper.getMeterialFaddishRateKuaishou(stat_tim,end_tim);
            //素材创新率
            innovateList = bossDataExhibitionMapper.getMeterialInnovateRateKuaishou(stat_tim,end_tim);
        }

        resultMap.put("useRate", Check.isNull(userList) ? "0" : userList.get(0).get("useRate"));
        resultMap.put("faddishRate",Check.isNull(faddishList) ? "0" : faddishList.get(0).get("faddishRate"));
        resultMap.put("innovateRate",Check.isNull(innovateList) ? "0" : innovateList.get(0).get("innovateRate"));
        return Result.successMsg(("1".equals(mediaType) ? "【头条】" : "【快手】")+"===素材相关查询成功。",resultMap);
    }


    /**
     *
     * @description: 分公司投放数据
     *
     * @param mediaType 1-头条 2-快手
     * @param startTime
     * @param endTime
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getCompanyAccountDataInfo(String mediaType, String startTime, String endTime) {
        Integer stat_tim = DateUtils.getDateInteger(startTime);
        Integer end_tim = DateUtils.getDateInteger(endTime);
        List<Map<String,Object>> resultList = Arrays.asList();
        // 1-头条 2-快手
        if (StringUtils.equals("1",mediaType)){
            resultList = bossDataExhibitionMapper.getCompanyAccountDataBytedance(stat_tim,end_tim);
        }else if (StringUtils.equals("2",mediaType)){
            resultList = bossDataExhibitionMapper.getCompanyAccountDataKuaishou(stat_tim,end_tim);
        }
        return Result.successMsg(("1".equals(mediaType) ? "【头条】" : "【快手】")+"===分公司投放数据查询成功。",resultList);
    }





    /**
     *
     * @description:分媒投放数据
     *
     * @param
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getAccountDataByMediaType() {
        Map<String,Object> resultMap = new HashMap<>();
        //获取当前月份第一天
        Integer firstDay = DateUtils.getFirstDayByMonth();
        List<Map<String,Object>>  resultList = bossDataExhibitionMapper.getMediaTypeAccountData(firstDay);
        if (Check.isNull(resultList)){
            return Result.error("分媒体投放数据暂无");
        }

        //图表数据组装
        List<Object> timeList = resultList.stream().map(map -> map.get("time")).collect(Collectors.toList());
        //时间格式转换 20220120 -->>> 01-20
        List<Object> resultTimeList = new ArrayList<>();
        if (!Check.isNull(timeList)){
            timeList.forEach(obj -> {
                resultTimeList.add(DateUtils.intDateToString(obj.toString()));
            });
        }
        //头条数据 坐标轴左侧 加 “-” 变为负数
        List<Object> bytedanceList = resultList.stream().map(map -> map.get("bytedanceCost")).collect(Collectors.toList());
        List<Object> resultBytedanceList = new ArrayList<>();
        if (!Check.isNull(bytedanceList)){
            bytedanceList.forEach(obj ->{
                resultBytedanceList.add(new StringBuilder().append("-").append(obj));
            });
        }
        //快手数据 坐标轴右侧  正数
        List<Object> kuaishouList = resultList.stream().map(map -> map.get("kuaishouCost")).collect(Collectors.toList());

        resultMap.put("time",resultTimeList);
        resultMap.put("bytedance",resultBytedanceList);
        resultMap.put("kuaishou",kuaishouList);
        return Result.successMsg("分媒体投放数据查询成功。",resultMap);
    }

    /**
     *
     * @description: 分媒体公司消耗-账户维度-分日数据 -折线图-
     *
     * @param mediaType
     * @param startTime
     * @param endTime
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getAccountTrendByMediaType(String mediaType, String startTime, String endTime) {
        Map<String,Object> resultMap = new HashMap();
        // 获取两个日期之间 所有的 时间 年-月-日
        List<String> betweenDaysList = DateUtils.getAllDatesOfTwoTimes(startTime,endTime);
        resultMap.put("time",betweenDaysList);

        Integer stat_tim = DateUtils.getDateInteger(startTime);
        Integer end_tim = DateUtils.getDateInteger(endTime);
        List<AccountTrendPojo> resultList = Arrays.asList();
        // 1-头条 2-快手
        if (StringUtils.equals("1",mediaType)){
            resultList = bossDataExhibitionMapper.getMediaTypeAccountTrendBytedance(stat_tim,end_tim);
        }else if (StringUtils.equals("2",mediaType)){
            resultList = bossDataExhibitionMapper.getMediaTypeAccountTrendKuaishou(stat_tim,end_tim);
        }
        if (Check.isNull(resultList)) {
            return Result.error("账户消耗数据查询为空");
        }

        /**
         * 数据组装
         */
        //根据 区域分组
        Map<String,List<AccountTrendPojo>> map = resultList.stream().collect(Collectors.groupingBy(AccountTrendPojo::getArea));

        //1-华北
        List<AccountTrendPojo> huaBeiList = !map.containsKey("华北") ? new ArrayList<>() : map.get("华北");
        //获取数据 时间 集合
        List<String> huabeiTime = huaBeiList.stream().map(AccountTrendPojo::getTime).collect(Collectors.toList());
        // 补充数据
        huaBeiList = getDateSupplement(betweenDaysList,huabeiTime,huaBeiList);
        // 获取属性 cost 返回数组
        List<String> huaBeiCostList = huaBeiList.stream().map(AccountTrendPojo::getCost).collect(Collectors.toList());
        resultMap.put("huaBei",huaBeiCostList);

        //2-华南
        List<AccountTrendPojo> huaNanList = !map.containsKey("华南") ? new ArrayList<>() : map.get("华南");
        List<String> huaNanTime = huaNanList.stream().map(AccountTrendPojo::getTime).collect(Collectors.toList());
        huaNanList = getDateSupplement(betweenDaysList,huaNanTime,huaNanList);
        List<String> huaNanCostList = huaNanList.stream().map(AccountTrendPojo::getCost).collect(Collectors.toList());
        resultMap.put("huaNan",huaNanCostList);

        //3-华东
        List<AccountTrendPojo> huaDongList = !map.containsKey("华东") ? new ArrayList<>() : map.get("华东");
        List<String> huaDongTime = huaDongList.stream().map(AccountTrendPojo::getTime).collect(Collectors.toList());
        huaDongList = getDateSupplement(betweenDaysList,huaDongTime,huaDongList);
        List<String> huaDongCostList = huaDongList.stream().map(AccountTrendPojo::getCost).collect(Collectors.toList());
        resultMap.put("huaDong",huaDongCostList);

        //4-骄阳
        List<AccountTrendPojo> jiaoYangList = !map.containsKey("骄阳") ? new ArrayList<>() : map.get("骄阳");
        List<String> jiaoYangTime = jiaoYangList.stream().map(AccountTrendPojo::getTime).collect(Collectors.toList());
        jiaoYangList = getDateSupplement(betweenDaysList,jiaoYangTime,jiaoYangList);
        List<String> jiaoYangCostList = jiaoYangList.stream().map(AccountTrendPojo::getCost).collect(Collectors.toList());
        resultMap.put("jiaoYang",jiaoYangCostList);

        return Result.successMsg(("1".equals(mediaType) ? "【头条】" : "【快手】")+"===分公司-分日-账户消耗数据查询成功。",resultMap);

    }


    /**
     * 补充数据 没有时间的补充时间并添加数据为0
     * @param betweenDaysList  两个日期中间的所有日期集合
     * @param nowList 现有日期的集合
     * @param accountTrendPojoList 数据集合
     * @return
     */
    public List<AccountTrendPojo> getDateSupplement(List<String> betweenDaysList,List<String> nowList,List<AccountTrendPojo> accountTrendPojoList){
        // 时间差集（所有时间段 - 已有的时间段）
        List<String>  reduceList = betweenDaysList.stream().filter(item -> !nowList.contains(item)).collect(Collectors.toList());
        reduceList.forEach(str ->{
                    AccountTrendPojo pojo = new AccountTrendPojo();
                    pojo.setTime(str);
                    pojo.setCost("0");
                    accountTrendPojoList.add(pojo);
                }
        );
        //时间排序
        accountTrendPojoList.sort(Comparator.comparing(AccountTrendPojo::getTime));
        return accountTrendPojoList;
    }



    /**
     *
     * @description: 项目消耗排行top10
     *
     * @param mediaType
     * @param startTime
     * @param endTime
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getProjectCostTopTenByMediaType(String mediaType, String startTime, String endTime) {
        Integer stat_tim = DateUtils.getDateInteger(startTime);
        Integer end_tim = DateUtils.getDateInteger(endTime);
        List<Map<String,Object>> resultList = Arrays.asList();
        // 1-头条 2-快手
        if (StringUtils.equals("1",mediaType)){
            resultList = bossDataExhibitionMapper.getMediaTypeProjectCostBytedance(stat_tim,end_tim);
            //基建数
            if (!Check.isNull(resultList)){
                for (Map<String, Object> dateMap : resultList) {
                    Map<String, Object> baseMap = bossDataExhibitionMapper.getMediaTypeProjectCostBytedanceBase(dateMap.get("projectId").toString(),stat_tim,end_tim);
                    dateMap.put("baseNum", Check.isNull(baseMap) ? "0" : baseMap.get("baseNum"));
                }
            }
        }else if (StringUtils.equals("2",mediaType)){
            resultList = bossDataExhibitionMapper.getMediaTypeProjectCostKuaishou(stat_tim,end_tim);
            //基建数
            if (!Check.isNull(resultList)){
                for (Map<String, Object> dateMap : resultList) {
                    Map<String, Object> baseMap = bossDataExhibitionMapper.getMediaTypeProjectCostKuaishouBase(dateMap.get("projectId").toString(),stat_tim,end_tim);
                    dateMap.put("baseNum", Check.isNull(baseMap) ? "0" : baseMap.get("baseNum"));
                }
            }
        }
        return Result.successMsg(("1".equals(mediaType) ? "【头条】" : "【快手】")+"===项目消耗排行top10查询成功。",resultList);
    }


}
