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

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.vo.DailyAccountReportVO;
import cn.com.ctop.common.module.vo.DailyGroupReportVO;
import cn.com.ctop.common.module.vo.DailyReportVO;
import cn.com.ctop.kuaishou.modules.report.mapper.DailyReportMapper;
import cn.com.ctop.kuaishou.modules.report.service.IDailyReportService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 日报报表
 */

@Slf4j
@Service
public class DailyReportServiceImpl implements IDailyReportService {

    @Autowired
    private DailyReportMapper dailyReportMapper;

    /**
     * 获取日报数据
     *
     * @param requestJson
     * @return
     */
    @Override
    public DailyReportVO getDailyReport(JSONObject requestJson) {
        try {
            log.info("日报开始统计");
            long startTime = System.currentTimeMillis();

            JSONArray accountIds = requestJson.getJSONArray("accountIds");
            BigDecimal discount = requestJson.getBigDecimal("discount");
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("accountIds", accountIds);
            requestMap.put("discount", discount);
            requestMap.put("date", requestJson.getString("date"));
            DailyAccountReportVO dailyAccountReport = dailyReportMapper.getDailyReport(requestMap);
            if (!Check.isNull(dailyAccountReport)) {
                BigDecimal cost = dailyAccountReport.getCost();
                BigDecimal contractRebateRealCharged = dailyAccountReport.getContractRebateRealCharged();
                if (!Check.isNull(cost) && !Check.isNull(contractRebateRealCharged)) {
                    BigDecimal actualCost = ((cost.subtract(contractRebateRealCharged)).divide(discount, 2, RoundingMode.HALF_UP));
                    dailyAccountReport.setActualCost(actualCost);
                }

            }
            List<DailyGroupReportVO> dailyGroupReport = dailyReportMapper.getDailyGroupReport(requestMap);
            DailyReportVO dailyReport = new DailyReportVO();
            dailyReport.setDailyAccountReport(dailyAccountReport);
            dailyReport.setDailyGroupReport(dailyGroupReport);
            log.info("日报统计完成,用时: " + ((System.currentTimeMillis() - startTime) / 1000) + " s");
            return dailyReport;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

}
