package cn.pluss.platform.merchantOrder;

import cn.pluss.platform.entity.MerchantOrderStatistics;
import cn.pluss.platform.mapper.MerchantOrderStatisticsMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.ibatis.annotations.Param;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>
 * 商户订单统计表 服务类
 * </p>
 *
 * @author Djh
 * @since 2021-12-21
 */
public interface MerchantOrderStatisticsService extends IService<MerchantOrderStatistics> {

    LocalDate INIT_START_DATE = LocalDate.of(2020, 1, 1);

    /**
     * 统计上个月的数据
     */
    default void untilLastMonth() {
        BaseMapper<MerchantOrderStatistics> baseMapper = getBaseMapper();
        LambdaQueryWrapper<MerchantOrderStatistics> qWrapper = new LambdaQueryWrapper<>();
        qWrapper.ne(MerchantOrderStatistics::getStartDate, "1970-01-01");
        qWrapper.orderByDesc(MerchantOrderStatistics::getCreateTime).last("limit 1");

        MerchantOrderStatistics entity = baseMapper.selectOne(qWrapper);

        Calendar calendar = Calendar.getInstance();
        Date from;

        if (entity != null) {
            from = Date.from(entity.getStartDate().atStartOfDay(ZoneId.systemDefault()).toInstant());
        } else {
            from = Date.from(INIT_START_DATE.atStartOfDay(ZoneId.systemDefault()).toInstant());
        }

        calendar.setTime(from);
        Date startDate = calendar.getTime();
        Date nextStartDate;

        Date now = new Date();
        while (startDate.compareTo(now) < 1) {

            calendar.add(Calendar.MONTH, 1);
            nextStartDate = calendar.getTime();

            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date endDate = calendar.getTime();

            LambdaQueryWrapper<MerchantOrderStatistics> removeWrapper = Wrappers.lambdaQuery();
            removeWrapper.eq(MerchantOrderStatistics::getStartDate, startDate);
            baseMapper.delete(removeWrapper);

            try {
                ((MerchantOrderStatisticsMapper) baseMapper).insertStatistics(startDate, endDate);
            } catch (Exception e) {
                e.printStackTrace();
            }

            startDate = nextStartDate;
            calendar.setTime(nextStartDate);
        }

        // 先清除全量统计数据
        LambdaQueryWrapper<MerchantOrderStatistics> dWrapper = Wrappers.lambdaQuery();
        dWrapper.eq(MerchantOrderStatistics::getStartDate, "1970-01-01");
        dWrapper.eq(MerchantOrderStatistics::getEndDate, "2099-12-31");
        baseMapper.delete(dWrapper);

        ((MerchantOrderStatisticsMapper) baseMapper).insertAllStatics();
    }

    /**
     * 获取直推总交易钱数, 以及交易笔数
     * @param pId       上级id
     * @param month     月份，传则当月，不传全部
     * @return
     */
    default MerchantOrderStatistics getDirectTotal(@Param("pId") String pId, @Param("month") String month) {
        MerchantOrderStatistics res = ((MerchantOrderStatisticsMapper) getBaseMapper()).selectDirectTotal(pId, month);
        if (res == null) {
            res = new MerchantOrderStatistics();
            res.setTotalFee(BigDecimal.ZERO);
            res.setCount(0);

            return res;
        }

        if (res.getTotalFee() == null) {
            res.setTotalFee(BigDecimal.ZERO);
        }

        if (res.getCount() == null) {
            res.setCount(0);
        }

        return res;
    }

    /**
     * 获取非直推总交易钱数, 以及交易笔数
     * @param pId       上级id
     * @param month     月份，传则当月，不传全部
     * @return
     */
    default MerchantOrderStatistics getIndirectTotal(@Param("pId") String pId, @Param("month") String month) {
        MerchantOrderStatistics res = ((MerchantOrderStatisticsMapper) getBaseMapper()).selectIndirectTotal(pId, month);
        if (res == null) {
            res = new MerchantOrderStatistics();
            res.setTotalFee(BigDecimal.ZERO);
            res.setCount(0);

            return res;
        }

        if (res.getTotalFee() == null) {
            res.setTotalFee(BigDecimal.ZERO);
        }

        if (res.getRetFee() == null) {
            res.setRetFee(BigDecimal.ZERO);
        }

        if (res.getCount() == null) {
            res.setCount(0);
        }

        res.setTotalFee(res.getTotalFee().subtract(res.getRetFee()));

        return res;
    }
}
