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

import cn.com.ctop.toutiao.modules.report.mapper.BytedanceHomepageMapper;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceHomepageReportService;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.constant.SystemDateConstant;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * Created by JQ.bi on 2020.05.19
 */
@Service
public class BytedanceHomepageReportServiceImpl implements IBytedanceHomepageReportService {

    @Autowired
    BytedanceHomepageMapper bytedanceHomepageMapper;

    @Override
    public Map<String, JSONObject> getWeekReport(JSONObject requestBody) {
        Map<String, JSONObject> result = new HashMap<>();
        //当天日期
        String nowDate = DateUtils.getNowDate(SystemDateConstant.yyyy_MM_dd);
        //本周汇总数据
        JSONObject weekSumData = bytedanceHomepageMapper.querySumByStartEndDate(nowDate,
                DateUtils.getAnotherDay(SystemDateConstant.yyyy_MM_dd, nowDate, -7));
        //上周汇总数据
        JSONObject weekBeforeSumData = bytedanceHomepageMapper.querySumByStartEndDate(DateUtils.getAnotherDay(SystemDateConstant.yyyy_MM_dd, nowDate, -7),
                DateUtils.getAnotherDay(SystemDateConstant.yyyy_MM_dd, nowDate, -14));
        //一周内每日数据汇总
        List<JSONObject> weekDetailData = bytedanceHomepageMapper.queryDetailByStartEndDate(nowDate,
                DateUtils.getAnotherDay(SystemDateConstant.yyyy_MM_dd, nowDate, -7));
        //一周内cost top数据
        List<JSONObject> costTop = bytedanceHomepageMapper.queryTopCost(nowDate, DateUtils.getAnotherDay(SystemDateConstant.yyyy_MM_dd, nowDate, -7), 7);
        JSONObject top = new JSONObject();
        top.put("top7", costTop);
        //周明细环比数据拼接
        JSONObject costWeekData = new JSONObject();
        JSONObject clickWeekData = new JSONObject();
        JSONObject showNumWeekData = new JSONObject();
        weekDetailData.forEach(day -> {
            costWeekData.put((String) day.get("statDate"), day.get("cost"));
            clickWeekData.put((String) day.get("statDate"), day.get("click"));
            showNumWeekData.put((String) day.get("statDate"), day.get("showNum"));
        });
        costWeekData.put("weekCostSum", weekSumData.get("cost"));
        costWeekData.put("weekCostSumLink", countLink(weekSumData.getBigDecimal("cost"), weekBeforeSumData.getBigDecimal("cost")));
        clickWeekData.put("weekClickSum", weekSumData.get("click"));
        clickWeekData.put("weekClickSumLink", countLink(BigDecimal.valueOf(weekSumData.getLongValue("click")), BigDecimal.valueOf(weekBeforeSumData.getLong("click"))));
        showNumWeekData.put("weekCostSum", weekSumData.get("showNum"));
        showNumWeekData.put("weekShowNumSumLink", countLink(BigDecimal.valueOf(weekSumData.getLongValue("showNum")), BigDecimal.valueOf(weekBeforeSumData.getLong("showNum"))));

        result.put("costWeek", costWeekData);
        result.put("clickWeek", clickWeekData);
        result.put("showNumWeek", showNumWeekData);
        result.put("top", top);

        return result;
    }

    /**
     * timeType :1,2,3,4,5,6,7,8,9  前端约束入参类型
     */
    @Override
    public List<JSONObject> getChartByDate(JSONObject requestBody) {
        int timeType = requestBody.getInteger("type");
        List<JSONObject> resultBody = new ArrayList<>();
        if (requestBody.isEmpty()) {
            return resultBody;
        }
        //当天日期
        String nowDate = DateUtils.getNowDate(SystemDateConstant.yyyy_MM_dd);
        //startTime 为取什么时间段数据的开始时间，默认昨天
        String anotherDay = DateUtils.getAnotherDay(SystemDateConstant.yyyy_MM_dd, nowDate, -1);
        switch (timeType) {
            //今天
            case 1:
                resultBody = getCompareGroupByHour(nowDate, anotherDay);
                break;
            //昨天
            case 2:
                resultBody = bytedanceHomepageMapper.queryTodayDetailReportBy(anotherDay);
                break;
            //近一周
            case 3:
                resultBody = bytedanceHomepageMapper.queryDetailByStartEndDate(nowDate,
                        DateUtils.getAnotherDay(SystemDateConstant.yyyy_MM_dd, anotherDay, -6));
                break;
            //近半个月（15天）
            case 4:
                resultBody = bytedanceHomepageMapper.queryDetailByStartEndDate(nowDate,
                        DateUtils.getAnotherDay(SystemDateConstant.yyyy_MM_dd, anotherDay, -14));
                break;
            //近一个月
            case 5:
                resultBody = bytedanceHomepageMapper.queryDetailByStartEndDate(nowDate,
                        DateUtils.getMonthBefore(SystemDateConstant.yyyy_MM_dd, anotherDay, -1));
                break;
            //近三个月
            case 6:
                resultBody = bytedanceHomepageMapper.queryDetailByStartEndDate(nowDate,
                        DateUtils.getMonthBefore(SystemDateConstant.yyyy_MM_dd, anotherDay, -3));
                break;
            //近半年
            case 7:
                resultBody = bytedanceHomepageMapper.queryDetailByStartEndDate(nowDate,
                        DateUtils.getMonthBefore(SystemDateConstant.yyyy_MM_dd, anotherDay, -6));
                break;
            //全部数据
            case 8:
                resultBody = bytedanceHomepageMapper.queryDetailGroupMonthByDate(SystemDateConstant.BEGIN_TIME, nowDate);
                break;
            //自定义起始时间
            case 9:
                resultBody = bytedanceHomepageMapper.queryDetailByStartEndDate(requestBody.getString("startDate"), requestBody.getString("endDate"));
                break;
            //对比
            case 10:
                resultBody = getChartByType_10(requestBody.getString("sign"), requestBody.getString("smallDate"), requestBody.getString("bigDate"));
                break;
            default:
        }
        return resultBody;
    }

    @Override
    public JSONObject getTopCostByDate(JSONObject requestBody) {
        return null;
    }

    //自定义日期对比（日对比，月对比）
    private List<JSONObject> getChartByType_10(String sign, String smallDate, String bigDate) {
        List<JSONObject> result = new ArrayList<>();
        if (!sign.isEmpty() && sign.equals("month")) {
            result = this.getCompareGroupByDay(smallDate, bigDate);
        } else if (!sign.isEmpty() && sign.equals("day")) {
            result = this.getCompareGroupByHour(bigDate, smallDate);
        }
        return result;
    }

    //两个月份的数据对比
    private List<JSONObject> getCompareGroupByDay(String smallDate, String bigDate) {
        //大月份数据
        List<JSONObject> afterDetail = bytedanceHomepageMapper.queryDetailGroupDayByMonth(bigDate);
        //小月份数据
        List<JSONObject> beforeDetail = bytedanceHomepageMapper.queryDetailGroupDayByMonth(smallDate);
        List<JSONObject> beforeData;List<JSONObject> afterData;
        if (afterDetail.size() >= beforeDetail.size()) {
            beforeData = afterDetail;
            afterData = beforeData;
        } else {
            beforeData = beforeDetail;
            afterData = afterDetail;
        }
        return this.getCompareDate(beforeData,afterData,"day");
    }

    //今天昨天数据对比
    private List<JSONObject> getCompareGroupByHour(String nowDate, String anotherDay) {
        List<JSONObject> afterDetail = bytedanceHomepageMapper.queryTodayDetailReportBy(nowDate);
        List<JSONObject> beforeDetail = bytedanceHomepageMapper.queryTodayDetailReportBy(anotherDay);
        return this.getCompareDate(beforeDetail, afterDetail, "statHour");
    }

    //数据对比,环比计算
    private List<JSONObject> getCompareDate(List<JSONObject> beforeData, List<JSONObject> AfterData, String standard) {
        List<JSONObject> result = new ArrayList<>();
        beforeData.forEach(before -> {
            String yesStatHour = String.valueOf(before.get(standard));
            AfterData.forEach(after -> {
                if ((String.valueOf(after.get(standard))).equals(yesStatHour)) {
                    //消耗较昨日环比
                    after.put("costProportion", countLink(after.getBigDecimal("cost"), before.getBigDecimal("cost")));
                    //展示量较昨日环比
                    after.put("showProportion", countLink(BigDecimal.valueOf(after.getLong("showNum")), BigDecimal.valueOf(before.getLong("showNum"))));
                    //点击量较昨日环比
                    after.put("photoClickProportion", countLink(BigDecimal.valueOf(after.getLong("click")), BigDecimal.valueOf(before.getLong("click"))));
                    before.put("afterData", after);
                }
            });
            result.add(before);
        });
        return result;
    }

    //环比计算
    private BigDecimal countLink(BigDecimal numA, BigDecimal numB) {
        BigDecimal link = new BigDecimal(0);
        if (!BigDecimal.ZERO.equals(numB)) {
            link = (numA.subtract(numB)).divide(numB, 4, RoundingMode.HALF_UP);
        }
        return link;
    }

}

