package cn.pluss.platform.bill;

import cn.hutool.core.date.DateUtil;
import cn.pluss.platform.entity.MemberTransStatistics;
import cn.pluss.platform.mapper.MemberTransStatisticsMapper;
import com.baomidou.mybatisplus.extension.service.IService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 会员消费日记录 服务类
 * </p>
 *
 * @author Djh
 * @since 2021-03-17
 */
public interface MemberTransStatisticsService extends IService<MemberTransStatistics> {

    /**
     * 保存指定日期的账单总计统计
     * @param day   日期格式为 yyyy-MM-dd
     */
    default void saveDaysBill(String day) {
        ((MemberTransStatisticsMapper) getBaseMapper()).insertDuringBill(day, day);
    }

    /**
     * 查询当日/当周/当月的账单
     * @param condition
     * @return
     */
    default MemberTransStatistics currentDuringBill(MemberTransStatistics condition) {
        Date currentDate = new Date();
        Date startDate;
        Date endDate;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        switch (condition.getType()) {
            case 2:
                // 当周周一
                startDate = DateUtil.beginOfWeek(currentDate).toJdkDate();
                endDate = DateUtil.endOfWeek(currentDate);
                break;
            case 3:
                // 当月一号
                startDate = DateUtil.beginOfMonth(currentDate).toJdkDate();
                endDate = DateUtil.endOfMonth(currentDate);
                break;
            case 4:
                // 当年一号
                startDate = DateUtil.beginOfYear(currentDate).toJdkDate();
                endDate = DateUtil.endOfYear(currentDate);
                break;
            default:
                // 当天开始时间
                startDate = DateUtil.beginOfDay(currentDate).toJdkDate();
                endDate = startDate;
                break;
        }

        MemberTransStatistics result = ((MemberTransStatisticsMapper) getBaseMapper()).selectOneDuringBill(sdf.format(startDate), sdf.format(endDate), condition.getUserId().toString());

        if (result == null) {
            result = new MemberTransStatistics();
        }

        if (result.getConsumeAmount() == null) {
            result.setConsumeAmount(BigDecimal.ZERO);
        } else {
            result.setConsumeAmount(result.getConsumeAmount().setScale(2, RoundingMode.HALF_UP));
        }

        if (result.getGiveAmount() == null) {
            result.setGiveAmount(BigDecimal.ZERO);
        } else {
            result.setGiveAmount(result.getGiveAmount().setScale(2, RoundingMode.HALF_UP));
        }

        if (result.getRechargeAmount() == null) {
            result.setRechargeAmount(BigDecimal.ZERO);
        } else {
            result.setRechargeAmount(result.getRechargeAmount().setScale(2, RoundingMode.HALF_UP));
        }

        return result;
    }
}
