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

import cn.com.ctop.common.constant.AccountReportConstants;
import cn.com.ctop.common.utils.JsonResourceUtil;
import cn.com.ctop.common.utils.LinkUtils;
import cn.com.ctop.report.entity.KuaishouAccountReportDailyDw;
import cn.com.ctop.report.mapper.KuaishouAccountReportDailyDwMapper;
import cn.com.ctop.report.mapper.KuaishouAccountReportHourlyDwMapper;
import cn.com.ctop.report.service.IKuaishouAccountReportDailyDwService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.SystemDateConstant;
import org.jeecg.common.util.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class KuaishouAccountReportDailyDwServiceImpl extends ServiceImpl<KuaishouAccountReportDailyDwMapper, KuaishouAccountReportDailyDw> implements IKuaishouAccountReportDailyDwService {
    @Resource
    private KuaishouAccountReportDailyDwMapper kuaishouAccountReportDailyDwMapper;
    @Resource
    private KuaishouAccountReportHourlyDwMapper kuaishouAccountReportHourlyDwMapper;

    @Override
    public List<JSONObject> getListDataByParams(String mediaId, BigDecimal discount, JSONArray accounts, String startDate, String endDate, int hour, String target, String order) {
        List<JSONObject> result;
        String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.getDicMapKs());
        Long startDateNum = Long.parseLong(startDate.replace("-", ""));
        Long anotherStartDateNum = Long.parseLong(DateUtils.getAnotherDay(SystemDateConstant.yyyy_MM_dd, startDate, -1).replace("-", ""));

        Long endDateNum = Long.parseLong(endDate.replace("-", ""));
        Long anotherEndDateNum = Long.parseLong(DateUtils.getAnotherDay(SystemDateConstant.yyyy_MM_dd, endDate, -1).replace("-", ""));

        if (startDateNum.equals(endDateNum)) {
            String groupBy = "account_id";
            if (startDate.equals(DateUtils.date2Str())) {
                result = kuaishouAccountReportHourlyDwMapper.getReportByParams(filedAll, startDateNum, hour, accounts, target, order, 1, groupBy);
                JSONObject afterSum = kuaishouAccountReportHourlyDwMapper.getReportByParams(filedAll, startDateNum, hour, accounts, target, order, 0, groupBy).get(0);
                JSONObject beforeSum = kuaishouAccountReportHourlyDwMapper.getReportByParams(filedAll, anotherStartDateNum, hour, accounts, target, order, 0, groupBy).get(0);
                result.add(afterSum);
                result.add(beforeSum);
                result.add(countTotal(afterSum, beforeSum));
            } else {
                result = kuaishouAccountReportDailyDwMapper.getReportByParams(filedAll, endDateNum, startDateNum, accounts, target, order, 1, groupBy);
                JSONObject afterSum = kuaishouAccountReportDailyDwMapper.getReportByParams(filedAll, endDateNum, startDateNum, accounts, target, order, 0, groupBy).get(0);
                JSONObject beforeSum = kuaishouAccountReportDailyDwMapper.getReportByParams(filedAll, anotherEndDateNum, anotherStartDateNum, accounts, target, order, 0, groupBy).get(0);
                result.add(afterSum);
                result.add(beforeSum);
                result.add(countTotal(afterSum, beforeSum));
            }
        } else {
            String groupBy = "stat_date";
            if (accounts.size() > 1) {
                groupBy = "account_id";
            }
            result = kuaishouAccountReportDailyDwMapper.getReportByParams(filedAll, endDateNum, startDateNum, accounts, target, order, 1, groupBy);
            List<JSONObject> totalList = kuaishouAccountReportDailyDwMapper.getReportByParams(filedAll, endDateNum, startDateNum, accounts, target, order, 0, groupBy);
            if (null != totalList && !totalList.isEmpty()) {
                result.add(totalList.get(0));
            }
        }
        return result;
    }

    //计算总计环比
    private JSONObject countTotal(JSONObject after, JSONObject before) {
        JSONObject jsonObject = new JSONObject();
        after.forEach((k, v) -> {
            //去除没法计算的字段
            if ("accountId".equals(k) || "authName".equals(k) || v.toString().contains("%") || before.getString(k).contains("%")) {
                jsonObject.put(k, "-");
            } else {
                jsonObject.put(k, (LinkUtils.countLink(after.getBigDecimal(k) == null ? BigDecimal.ZERO : after.getBigDecimal(k), before.getBigDecimal(k) == null ? BigDecimal.ZERO : before.getBigDecimal(k))).multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
            }
        });
        return jsonObject;
    }


    @Override
    public JSONObject getTotalCharge(Map<String, Object> paramsMap) {
        JSONObject ks = kuaishouAccountReportDailyDwMapper.getTotalCharge(paramsMap);
        Long count = kuaishouAccountReportDailyDwMapper.getYesterdayUploadNewMaterialCount(paramsMap);
        ks.put("kuaishouCount", count);
        return ks;
    }

    @Override
    public JSONObject getTrendCharge(Long projectId, String startTime, String endTime) {
        Integer startTimeInt = DateUtils.getDateInteger(startTime);
        Integer endTimeInt = DateUtils.getDateInteger(endTime);

        List<JSONObject> today = null;
        List<JSONObject> yesterday = null;
        if (startTime.equals(endTime)) {
            today = kuaishouAccountReportDailyDwMapper.getHourcharge(projectId, startTimeInt);
            yesterday = kuaishouAccountReportDailyDwMapper.getHourcharge(projectId, DateUtils.getDateInteger(DateUtils.getLastDay(startTime, 1)));
        } else {
            today = kuaishouAccountReportDailyDwMapper.getDatacharge(projectId, startTimeInt, endTimeInt);
            fillingDates(startTime, endTime, today);
            int days = DateUtils.dateDiff(startTime, endTime);
            String endTime2 = DateUtils.getLastDay(startTime, 1);
            String startTime2 = DateUtils.getLastDay(endTime2, days);
            yesterday = kuaishouAccountReportDailyDwMapper.getDatacharge(projectId, DateUtils.getDateInteger(startTime2), DateUtils.getDateInteger(endTime2));
            fillingDates(startTime2, endTime2, yesterday);
        }
        JSONObject data = new JSONObject();
        data.put("today", today);
        data.put("yesterday", yesterday);
        return data;
    }

    /**
     * 补充日期
     */
    private void fillingDates(String startTime, String endTime, List<JSONObject> today) {
        long dayNum = DateUtils.getDiscrepantDays(startTime, endTime) + 1;
        int size = today.size();
        if (dayNum - size != 0) {
            List<String> days = DateUtils.getDays(startTime, endTime);
            for (String day : days) {
                if (!today.contains(day)) {
                    JSONObject obj = new JSONObject();
                    obj.put("time", day);
                    obj.put("charge", 0.00);
                    today.add(obj);
                }
            }
        }
    }

    @Override
    public Result<Object> getProjectReport(Long projectId, String startTime, String endTime, Integer pageSize, Integer pageNo) throws Exception {
        Integer startTimeInt = DateUtils.getDateInteger(startTime);
        Integer endTimeInt = DateUtils.getDateInteger(endTime);
        //当前小时
        Integer nowHour = DateUtils.getNowHour();
        //当天日期
        String today = DateUtils.formatDate(new Date());
        List<JSONObject> data = null;
        Long total = null;
        if (startTime.equals(endTime) && today.equals(startTime)) {
            total = kuaishouAccountReportDailyDwMapper.getProjectToDayReportTotal(projectId, startTimeInt, nowHour);
            PageHelper.startPage(pageNo, pageSize, false);
            data = kuaishouAccountReportDailyDwMapper.getProjectToDayReport(projectId, startTimeInt, nowHour);
        } else {
            total = kuaishouAccountReportDailyDwMapper.getProjectMoreDaysReportTotal(projectId, startTimeInt, endTimeInt, nowHour);
            PageHelper.startPage(pageNo, pageSize, false);
            data = kuaishouAccountReportDailyDwMapper.getProjectMoreDaysReport(projectId, startTimeInt, endTimeInt, nowHour);
        }
        PageInfo<JSONObject> page = new PageInfo<>();
        page.setList(data);
        page.setTotal(total);
        return Result.OK(page);
    }


}
