package com.hzs.bonus.bonus.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.bonus.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.bonus.bonus.service.ICuMemberShareBonusService;
import com.hzs.bonus.bonus.service.ICuMemberShareDetailService;
import com.hzs.bonus.detail.service.ICuMemberAssessService;
import com.hzs.common.core.enums.EAwards;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.member.achieve.CuMemberSettlePeriod;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.bonus.CuMemberShareBonus;
import com.hzs.common.domain.member.bonus.CuMemberShareDetail;
import com.hzs.common.domain.member.detail.CuMemberAssess;
import com.hzs.common.domain.member.ext.CuMemberShareBonusExt;
import com.hzs.common.domain.member.ext.CuMemberShareDetailExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.bonus.base.service.ICuMemberService;
import com.hzs.bonus.bonus.mapper.CuMemberShareBonusMapper;
import com.hzs.bonus.bonus.param.CuMemberShareBonusParam;
import com.hzs.bonus.bonus.param.CuMemberShareDetailParam;
import com.hzs.sale.order.ISaOrderServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAwardsServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 会员奖金-分红奖金配置 服务实现类
 *
 * @author hzs
 * @since 2023-07-03
 */
@Service
public class CuMemberShareBonusServiceImpl extends ServiceImpl<CuMemberShareBonusMapper, CuMemberShareBonus> implements ICuMemberShareBonusService {

    @DubboReference
    ISaOrderServiceApi saOrderServiceApi;
    @DubboReference
    IAwardsServiceApi awardsServiceApi;
    @DubboReference
    ICurrencyServiceApi currencyServiceApi;

    @Autowired
    private ICuMemberShareDetailService cuMemberShareDetailService;
    @Autowired
    private ICuMemberService cuMemberService;
    @Autowired
    private ICuMemberAssessService cuMemberAssessService;
    @Autowired
    private ICuMemberSettlePeriodService cuMemberSettlePeriodService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMemberShareBonus(CuMemberShareBonusParam cuMemberShareBonusParam) {
        CuMemberShareBonusExt cuMemberShareBonusExt = queryCuMemberShareBonus(cuMemberShareBonusParam.getPkCountry(), cuMemberShareBonusParam.getSettleMonth());
        CuMemberShareBonus cuMemberShareBonus = BeanUtil.copyProperties(cuMemberShareBonusExt, CuMemberShareBonus.class);
        if (cuMemberShareBonus.getPkId() == null) {
            cuMemberShareBonus.setPkCountry(cuMemberShareBonusParam.getPkCountry());
            cuMemberShareBonus.setPkCreator(cuMemberShareBonusParam.getPkCreator());
            CuMemberSettlePeriod cuMemberSettlePeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(cuMemberShareBonusExt.getSettleMonth() + "-01");
            cuMemberShareBonus.setPeriod(cuMemberSettlePeriod.getPkId());
            CurrencyDTO currencyDTO = currencyServiceApi.getCurrency(cuMemberShareBonusParam.getPkCountry()).getData();
            cuMemberShareBonus.setPkRate(currencyDTO.getPkId());
            baseMapper.insert(cuMemberShareBonus);
        } else {
            cuMemberShareBonus.setPkModified(cuMemberShareBonusParam.getPkCreator());
            cuMemberShareBonus.setModifiedTime(DateUtils.currentDateTime());
            baseMapper.updateById(cuMemberShareBonus);
        }
        if (CollectionUtil.isNotEmpty(cuMemberShareBonusExt.getCuMemberShareDetailList())) {
            Map<Integer, CuMemberShareDetailParam> cuMemberShareDetailParamMap = new HashMap<>();
            cuMemberShareBonusParam.getCuMemberShareDetailList().forEach(cuMemberShareDetailParam ->
                    cuMemberShareDetailParamMap.put(cuMemberShareDetailParam.getPkAwards(), cuMemberShareDetailParam));
            Date currentDateTime = DateUtils.currentDateTime();
            for (CuMemberShareDetailExt cuMemberShareDetail : cuMemberShareBonusExt.getCuMemberShareDetailList()) {
                if (cuMemberShareDetailParamMap.containsKey(cuMemberShareDetail.getPkAwards())) {
                    CuMemberShareDetailParam cuMemberShareDetailParam = cuMemberShareDetailParamMap.get(cuMemberShareDetail.getPkAwards());
                    cuMemberShareDetail.setRealShareIncome(cuMemberShareDetailParam.getRealShareIncome());
                    cuMemberShareDetail.setRealShareSubtotal(ComputeUtil.computeMultiply(cuMemberShareDetailParam.getRealShareIncome(), cuMemberShareDetail.getReachTotal()));
                }
                if (cuMemberShareDetail.getPkId() == null) {
                    cuMemberShareDetail.setPkCountry(cuMemberShareBonusParam.getPkCountry());
                    cuMemberShareDetail.setPkShareBonus(cuMemberShareBonus.getPkId());
                    cuMemberShareDetail.setCreationTime(currentDateTime);
                    cuMemberShareDetail.setPkCreator(cuMemberShareBonusParam.getPkCreator());
                } else {
                    cuMemberShareDetail.setPkModified(cuMemberShareBonusParam.getPkCreator());
                    cuMemberShareDetail.setModifiedTime(DateUtils.currentDateTime());
                }
            }
            cuMemberShareDetailService.saveMemberShareBonus(cuMemberShareBonusExt.getCuMemberShareDetailList());
        }
    }

    @Override
    public CuMemberShareBonusExt queryCuMemberShareBonus(Integer pkCountry, String settleMonth) {
        CuMemberShareBonusExt cuMemberShareBonusExt = baseMapper.queryCuMemberShareBonus(pkCountry, settleMonth);
        if (cuMemberShareBonusExt == null) {
            cuMemberShareBonusExt = new CuMemberShareBonusExt();
            cuMemberShareBonusExt.setSettleMonth(settleMonth);
            Date endDate = DateUtils.parseDate(settleMonth + "-01");
            Date startDate = DateUtils.beforeMonthFirstDate(endDate);
            SaOrder saOrder = saOrderServiceApi.queryOrderTotalAchieveByTime(startDate, endDate).getData();
            BigDecimal shareRatio = BigDecimal.ZERO;
            List<BdAwards> bdAwardsList = awardsServiceApi.queryAwards(pkCountry).getData();
            List<CuMemberShareDetailExt> cuMemberShareDetailList = new ArrayList<>();
            // 查询奖衔 晋升人数
            List<CuMember> cuMemberList = cuMemberService.queryCuMemberShareTotal(pkCountry);
            Map<Integer, Integer> cuMemberMap = new HashMap<>();
            cuMemberList.forEach(cuMember ->
                    cuMemberMap.put(cuMember.getPkAwards(), cuMember.getShareStatus()));
            List<CuMemberAssess> cuMemberAssessList = cuMemberAssessService.queryCuMemberAssTotal(settleMonth + "-01", pkCountry);
            Map<Integer, Integer> cuMemberAssMap = new HashMap<>();
            cuMemberAssessList.forEach(cuMemberAssess ->
                    cuMemberAssMap.put(cuMemberAssess.getPkAwards(), cuMemberAssess.getAssessStatus()));
            // 查询奖衔 达标人数
            for (BdAwards bdAwards : bdAwardsList) {
                if (EAwards.MEMBER.getValue() == bdAwards.getAwardsValue()) {
                    continue;
                }
                shareRatio = ComputeUtil.computeAdd(shareRatio, bdAwards.getAbonusRatio());
                CuMemberShareDetailExt cuMemberShareDetail = new CuMemberShareDetailExt();
                cuMemberShareDetail.setPkAwards(bdAwards.getPkId());
                cuMemberShareDetail.setPkAwardsVal(bdAwards.getAwardsName());
                cuMemberShareDetail.setPromoteTotal(0);
                cuMemberShareDetail.setReachTotal(0);
                cuMemberShareDetail.setExpectShareIncome(BigDecimal.ZERO);
                cuMemberShareDetail.setExpectShareSubtotal(BigDecimal.ZERO);
                cuMemberShareDetail.setRealShareIncome(BigDecimal.ZERO);
                cuMemberShareDetail.setRealShareSubtotal(BigDecimal.ZERO);
                if (cuMemberMap.containsKey(bdAwards.getPkId())) {
                    cuMemberShareDetail.setPromoteTotal(cuMemberMap.get(bdAwards.getPkId()));
                }
                if (cuMemberAssMap.containsKey(bdAwards.getPkId())) {
                    cuMemberShareDetail.setReachTotal(cuMemberAssMap.get(bdAwards.getPkId()));
                }
                cuMemberShareDetailList.add(cuMemberShareDetail);
            }
            cuMemberShareBonusExt.setExpectShareTotal(saOrder == null ? BigDecimal.ZERO : ComputeUtil.computeMultiply(saOrder.getOrderAchieve(), shareRatio));
            cuMemberShareBonusExt.setRealShareTotal(saOrder == null ? BigDecimal.ZERO : ComputeUtil.computeMultiply(saOrder.getOrderAchieve(), shareRatio));
            // 处理预发金额 预发合计
            for (CuMemberShareDetail cuMemberShareDetail : cuMemberShareDetailList) {
                int count = bdAwardsList.size();
                if (count > 0) {
                    cuMemberShareDetail.setExpectShareSubtotal(ComputeUtil.computeDivide(cuMemberShareBonusExt.getExpectShareTotal(), BigDecimal.valueOf(count)));
                    cuMemberShareDetail.setExpectShareIncome(ComputeUtil.computeDivide(cuMemberShareDetail.getExpectShareSubtotal(), BigDecimal.valueOf(cuMemberShareDetail.getPromoteTotal())));
                } else {
                    cuMemberShareDetail.setExpectShareSubtotal(BigDecimal.ZERO);
                    cuMemberShareDetail.setExpectShareIncome(BigDecimal.ZERO);
                }
            }
            cuMemberShareBonusExt.setCuMemberShareDetailList(cuMemberShareDetailList);
        }
        return cuMemberShareBonusExt;
    }
}
