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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.bonus.base.service.ICuMemberService;
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.enums.EBonusItems;
import com.hzs.common.core.enums.EGrantStatus;
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.domain.vertex.BdVertexBonus;
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.*;

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

    @Autowired
    private ICuMemberBonusService iCuMemberBonusService;
    @Autowired
    private ICuMemberService iCuMemberService;

    /**
     * 新零售实时奖金：查询会员实时奖金，当日的奖金
     */
    @PostMapping("/query-current-bonus")
    public TableDataInfo listCurrentBonus(@RequestBody BonusParam bonusParam) {
        bonusParam.setPkCountry(SecurityUtils.getPkCountry());
        bonusParam.setPkMember(SecurityUtils.getUserId());
        bonusParam.setStartDate(DateUtils.currentDate());
        bonusParam.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, DateUtils.currentDate()));
        bonusParam.setGrantStatus(EGrantStatus.SETTLED.getValue());

        // 控制复购级差收益的返回
        final boolean rangeIncomeFlag = this.checkRangeIncome();

        List<CuMemberBonusExt> cuMemberBonusList = iCuMemberBonusService.queryMemberSecondBonusVoByCondition(bonusParam);
        List<MemberBonusVO> memberBonusVOList = new ArrayList<>();
        cuMemberBonusList.forEach(cuMemberBonus -> {
            if (ComputeUtil.compareValue(cuMemberBonus.getRealIncomeTotal())) {
                MemberBonusVO memberBonusVO = BeanUtil.copyProperties(cuMemberBonus, MemberBonusVO.class, "settleDate");
                memberBonusVO.setServiceSpend(BigDecimal.ZERO);
                memberBonusVO.setSettleDate(DateUtils.currentDate());
                BigDecimal serviceSpend = ComputeUtil.computeSubtract(
                        ComputeUtil.computeAddNum(cuMemberBonus.getRetailRangeIncome(), cuMemberBonus.getRetailSameLevelIncome(), cuMemberBonus.getRetailAreaIncome(), cuMemberBonus.getRepurRangeIncome()),
                        cuMemberBonus.getRetailRealSubtotal()
                );
                memberBonusVO.setBackPoints(serviceSpend);

                if (!rangeIncomeFlag) {
                    // 没有复购级差
                    memberBonusVO.setRepurRangeIncome(null);
                }

                memberBonusVOList.add(memberBonusVO);
            }
        });
        return getDataTable(memberBonusVOList);
    }

    /**
     * 新零售日结奖金：查询会员奖金列表
     */
    @PostMapping("/query-bonus-first")
    public TableDataInfo listFirstRepurchaseBonus(@RequestBody BonusParam bonusParam) {
        setBonusParam(bonusParam);

        List<CuMemberBonusExt> cuMemberBonusList = iCuMemberBonusService.queryMemberBonusVoByCondition(bonusParam);

        // 控制复购级差收益的返回
        final boolean rangeIncomeFlag = this.checkRangeIncome();

        List<MemberBonusFirstPurchaseVO> firstPurchaseVOList = new ArrayList<>();
        cuMemberBonusList.forEach(cuMemberBonus -> {
            MemberBonusFirstPurchaseVO memberBonusFirstPurchaseVO = BeanUtil.copyProperties(cuMemberBonus, MemberBonusFirstPurchaseVO.class, "settleDate");
            packageSettleDate(cuMemberBonus, memberBonusFirstPurchaseVO);
            if (!rangeIncomeFlag) {
                // 没有复购级差
                memberBonusFirstPurchaseVO.setRepurRangeIncome(null);
            }
            firstPurchaseVOList.add(memberBonusFirstPurchaseVO);
        });
        return getDataTable(firstPurchaseVOList);
    }

    /**
     * 新零售日结奖金：查询会员昨日奖金汇总
     */
    @PostMapping("/query-bonus-total")
    public TableDataInfo lisBonusTotal(@RequestBody BonusParam bonusParam) {
        bonusParam.setPkCountry(SecurityUtils.getPkCountry());
        bonusParam.setPkMember(SecurityUtils.getUserId());
        bonusParam.setEndDate(DateUtils.currentDate());
        bonusParam.setStartDate(DateUtils.beforeDate(1, ChronoUnit.DAYS, bonusParam.getEndDate()));

        List<CuMemberBonusExt> cuMemberBonusList = iCuMemberBonusService.queryMemberBonusTotalByCondition(bonusParam);
        MemberRealIncomeVO memberRealIncomeVO = new MemberRealIncomeVO();
        if (CollectionUtil.isEmpty(cuMemberBonusList)) {
            memberRealIncomeVO.setRealIncomeTotal(BigDecimal.ZERO);
        } else {
//            memberRealIncomeVO.setRealIncomeTotal(ComputeUtil.computeAdd(cuMemberBonusList.get(0).getRealIncomeTotal(), cuMemberBonusList.get(0).getBackPoints()));
            memberRealIncomeVO.setRealIncomeTotal(cuMemberBonusList.get(0).getRealIncomeTotal());
        }
        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.getRetailRangeIncome(),
                    memberBonusPurchaseVO.getRetailSameLevelIncome(), memberBonusPurchaseVO.getRetailAreaIncome(),
                    memberBonusPurchaseVO.getRetailBenefitRangeIncome(), memberBonusPurchaseVO.getRetailBenefitAvgIncome(),
                    memberBonusPurchaseVO.getRetailBenefitIncome()),
                    memberBonusPurchaseVO.getRetailRealSubtotal());
            memberBonusPurchaseVO.setBackPoints(serviceSpend);
            memberBonusPurchaseVO.setRetailBenefitIncome(ComputeUtil.computeAdd(memberBonusPurchaseVO.getRetailBenefitIncome(), memberBonusPurchaseVO.getRetailBenefitAvgIncome()));
            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);
    }

    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();
        return iCuMemberBonusService.queryMemberBonusDetailVoByCondition(bonusParam);
    }

    /**
     * 校验是否有复购级差
     *
     * @return
     */
    private boolean checkRangeIncome() {
        List<BdVertexBonus> vertexBonusList = iCuMemberService.listVertexBonus(SecurityUtils.getUserId());
        if (CollectionUtil.isNotEmpty(vertexBonusList)) {
            for (BdVertexBonus bdVertexBonus : vertexBonusList) {
                if (null != bdVertexBonus
                        && null != bdVertexBonus.getBonusItems()
                        && EBonusItems.REPURCHASE_RANGE_INCOME.getValue() == bdVertexBonus.getBonusItems()) {
                    return true;
                }
            }
        }
        return false;
    }

}
