package com.hzs.bonus.bonus.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.bonus.bonus.param.BonusParam;
import com.hzs.bonus.bonus.service.ICuMemberBonusService;
import com.hzs.bonus.bonus.vo.*;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.ext.CuMemberBonusExt;
import com.hzs.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/bonus")
@Slf4j
public class ApiCuMemberBonusController extends BaseController {

    @Autowired
    private ICuMemberBonusService iCuMemberBonusService;

    /**
     * 查询会员某个时间段内的奖金，默认查询15天内,查询直推
     */
    @PostMapping("/query-bonus-first")
    public TableDataInfo listFirstRepurchaseBonus(@RequestBody BonusParam bonusParam) {
        setBonusParam(bonusParam);
        List<CuMemberBonusExt> cuMemberBonusList = iCuMemberBonusService.queryMemberBonusVoByCondition(bonusParam);
        List<MemberBonusFirstPurchaseVO> firstPurchaseVOList = new ArrayList<>();
        cuMemberBonusList.forEach(cuMemberBonus -> {
            MemberBonusFirstPurchaseVO memberBonusFirstPurchaseVO = BeanUtil.copyProperties(cuMemberBonus, MemberBonusFirstPurchaseVO.class, "settleDate");
            packageSettleDate(cuMemberBonus, memberBonusFirstPurchaseVO);
            memberBonusFirstPurchaseVO.setBackPoints(cuMemberBonus.getBackPoints());
            memberBonusFirstPurchaseVO.setServiceSpend(cuMemberBonus.getServiceSpend());
            // 拓展收益 = 首购拓展 + 复购拓展 + 复购推荐
            memberBonusFirstPurchaseVO.setExpandIncome(ComputeUtil.computeAddNum(memberBonusFirstPurchaseVO.getExpandIncome(),
                    memberBonusFirstPurchaseVO.getRepurExpandIncome(), memberBonusFirstPurchaseVO.getRepurPushIncome()));
            // 辅导收益 = 首购辅导 + 复购辅导
            memberBonusFirstPurchaseVO.setCoachIncome(ComputeUtil.computeAddNum(memberBonusFirstPurchaseVO.getCoachIncome(),
                    memberBonusFirstPurchaseVO.getRepurCoachIncome()));
            // 首购实发小计 = 首购实发小计 + 复购实发小计
            memberBonusFirstPurchaseVO.setPurRealSubtotal(ComputeUtil.computeAdd(memberBonusFirstPurchaseVO.getPurRealSubtotal(), memberBonusFirstPurchaseVO.getRepurRealSubtotal()));
            firstPurchaseVOList.add(memberBonusFirstPurchaseVO);
        });
        return getDataTable(firstPurchaseVOList);
    }

    /**
     * 查询会员昨天奖金的值
     */
    @PostMapping("/query-bonus-total")
    public TableDataInfo lisBonusTotal(@RequestBody BonusParam bonusParam) {
        Date nowDate = DateUtils.currentDate();
        bonusParam.setPkCountry(SecurityUtils.getPkCountry());
        bonusParam.setPkMember(SecurityUtils.getUserId());
//        bonusParam.setStartDate(DateUtils.beforeDate(1, ChronoUnit.DAYS));
        bonusParam.setStartDate(DateUtils.currentMonthFirstDate(nowDate));
        bonusParam.setEndDate(nowDate);
        List<CuMemberBonusExt> cuMemberBonusList = iCuMemberBonusService.queryMemberBonusTotalByCondition(bonusParam);
        MemberRealIncomeVO memberRealIncomeVO = MemberRealIncomeVO.builder()
                .realIncomeTotal(BigDecimal.ZERO)
                .monthIncomeTotal(BigDecimal.ZERO)
                .build();
        if (CollectionUtil.isNotEmpty(cuMemberBonusList)) {
            if (DateUtils.beforeDate(1, ChronoUnit.DAYS, nowDate).equals(cuMemberBonusList.get(0).getSettleDate())) {
                // 最新数据是昨天的奖金数据
                memberRealIncomeVO.setRealIncomeTotal(cuMemberBonusList.get(0).getRealIncomeTotal());
            }
            BigDecimal monthTotal = BigDecimal.ZERO;
            for (CuMemberBonusExt cuMemberBonusExt : cuMemberBonusList) {
                monthTotal = monthTotal.add(cuMemberBonusExt.getRealIncomeTotal());
            }
            memberRealIncomeVO.setMonthIncomeTotal(monthTotal);
        }
        return getDataTable(Collections.singletonList(memberRealIncomeVO));
    }

    /**
     * 查询会员某个时间段内的奖金，默认查询15天内,查询复购
     */
    @PostMapping("/query-bonus-repurchase")
    public TableDataInfo listRepurchaseBonus(@RequestBody BonusParam bonusParam) {
        setBonusParam(bonusParam);
        List<CuMemberBonusExt> cuMemberBonusList = iCuMemberBonusService.queryMemberBonusVoByCondition(bonusParam);
        List<MemberBonusPurchaseVO> memberBonusPurchaseVoList = new ArrayList<>();
        cuMemberBonusList.forEach(cuMemberBonus -> {
            MemberBonusPurchaseVO memberBonusPurchaseVO = BeanUtil.copyProperties(cuMemberBonus, MemberBonusPurchaseVO.class, "settleDate");
            packageSettleDate(cuMemberBonus, memberBonusPurchaseVO);
            BigDecimal serviceSpend = ComputeUtil.computeSubtract(ComputeUtil.computeAddNum(memberBonusPurchaseVO.getRepurPushIncome(), memberBonusPurchaseVO.getRepurExpandIncome(), memberBonusPurchaseVO.getRepurRangeIncome()),
                    memberBonusPurchaseVO.getRepurRealSubtotal());
            memberBonusPurchaseVO.setBackPoints(ComputeUtil.computeMultiplyHalf(serviceSpend));
            memberBonusPurchaseVO.setServiceSpend(ComputeUtil.computeMultiplyHalf(serviceSpend));
            memberBonusPurchaseVoList.add(memberBonusPurchaseVO);
        });
        return getDataTable(memberBonusPurchaseVoList);
    }

    private static void packageSettleDate(CuMemberBonusExt cuMemberBonus, PubMemberBonusVO pubMemberBonusVO) {
        if (cuMemberBonus.getEndSettleDate() == null) {
            pubMemberBonusVO.setSettleDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, cuMemberBonus.getSettleDate()));
        } else {
            pubMemberBonusVO.setSettleDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, cuMemberBonus.getSettleDate()) + "-" +
                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, cuMemberBonus.getEndSettleDate()));
        }
        pubMemberBonusVO.setServiceSpend(BigDecimal.ZERO);
    }

    /**
     * 查询会员某个时间段内的奖金，默认查询15天内,查询复购
     */
    @PostMapping("/query-bonus-cloud")
    public TableDataInfo listCloudAgentBonus(@RequestBody BonusParam bonusParam) {
        setBonusParam(bonusParam);
        List<CuMemberBonusExt> cuMemberBonusList = iCuMemberBonusService.queryMemberBonusVoByCondition(bonusParam);
        List<MemberBonusCloudAgentVO> memberBonusCloudAgentVoArrayList = new ArrayList<>();
        cuMemberBonusList.forEach(cuMemberBonus -> {
            if (ComputeUtil.compareValue(cuMemberBonus.getCloudRepurIncome())) {
                MemberBonusCloudAgentVO bonusCloudAgentVO = BeanUtil.copyProperties(cuMemberBonus, MemberBonusCloudAgentVO.class, "settleDate");
                packageSettleDate(cuMemberBonus, bonusCloudAgentVO);
                BigDecimal serviceSpend = ComputeUtil.computeSubtract(ComputeUtil.computeAddNum(bonusCloudAgentVO.getCloudDirectIncome(),
                        bonusCloudAgentVO.getCloudPurIncome(), bonusCloudAgentVO.getCloudRepurIncome()),
                        bonusCloudAgentVO.getCloudRealSubtotal());
                bonusCloudAgentVO.setServiceSpend(serviceSpend);
                memberBonusCloudAgentVoArrayList.add(bonusCloudAgentVO);
            }
        });
        return getDataTable(memberBonusCloudAgentVoArrayList);
    }

    /**
     * 查询会员某个时间段内的奖金，默认查询15天内,查询复购
     */
    @PostMapping("/query-bonus-coupon")
    public TableDataInfo listRepurchaseCouponBonus(@RequestBody BonusParam bonusParam) {
        setBonusParam(bonusParam);
        List<CuMemberBonusExt> cuMemberBonusList = iCuMemberBonusService.queryMemberBonusVoByCondition(bonusParam);
        List<MemberBonusRepurchaseCouponVO> memberBonusRepurchaseCouponList = new ArrayList<>();
        cuMemberBonusList.forEach(cuMemberBonus -> {
            MemberBonusRepurchaseCouponVO repurchaseCouponVO = BeanUtil.copyProperties(cuMemberBonus, MemberBonusRepurchaseCouponVO.class, "settleDate");
            packageSettleDate(cuMemberBonus, repurchaseCouponVO);
            BigDecimal serviceSpend = ComputeUtil.computeSubtract(ComputeUtil.computeAdd(repurchaseCouponVO.getRepurCoupon(),
                    repurchaseCouponVO.getRepurCouponShare()), repurchaseCouponVO.getRepurCouponSubtotal());
            repurchaseCouponVO.setServiceSpend(serviceSpend);
            memberBonusRepurchaseCouponList.add(repurchaseCouponVO);
        });
        return getDataTable(memberBonusRepurchaseCouponList);
    }

    private void setBonusParam(@RequestBody BonusParam bonusParam) {
        bonusParam.setPkCountry(SecurityUtils.getPkCountry());
        bonusParam.setPkMember(SecurityUtils.getUserId());
        Date startDate = DateUtils.beforeDate(15, ChronoUnit.DAYS, DateUtils.currentDate());
        if (bonusParam.getStartDate() == null) {
            bonusParam.setStartDate(startDate);
        } else if (DateUtils.compareDateBefore(bonusParam.getStartDate(), startDate)) {
            bonusParam.setStartDate(startDate);
        }
        if (bonusParam.getEndDate() == null) {
            bonusParam.setEndDate(DateUtils.currentDate());
        } else {
            bonusParam.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, bonusParam.getEndDate()));
        }
    }

    /**
     * 查询会员某个时间段内的奖金来源
     */
    @PostMapping("/query-bonus-detail")
    public TableDataInfo listBonusSource(@RequestBody BonusParam bonusParam) {
        setBonusParam(bonusParam);
        startPage();
        TableDataInfo tableDataInfo = iCuMemberBonusService.queryMemberBonusDetailVoByCondition(bonusParam);
        return tableDataInfo;
    }

}
