package com.dayou.brokerage.handler;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dayou.bo.BrokerageDetailBO;
import com.dayou.brokerage.BrokerageCalculateSupport;
import com.dayou.brokerage.NonMarketerMarketerBrokerageCalculator;
import com.dayou.brokerage.constants.BrokerageRule;
import com.dayou.common.BaseEntity;
import com.dayou.dto.ParticipantSettleDTO;
import com.dayou.entity.ItemBrokerageDetail;
import com.dayou.entity.ItemStage;
import com.dayou.enums.GlobalConfigEnum;
import com.dayou.service.IItemBrokerageDetailService;
import com.google.common.cache.Cache;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import static com.dayou.brokerage.constants.BrokerageMsg.NON_MARKETER_MONTH_BROKERAGE;
import static com.dayou.brokerage.constants.BrokerageMsg.PARTICIPANT_BROKERAGE_PERCENTAGE;
import static com.dayou.common.Constants.HUNDRED;

/**
 * 类说明：土地规划部 非 市场人员提成计算处理器
 *
 * @author: wucl
 * @since: 2023/3/8
 * created with IntelliJ IDEA.
 */
@Component
@Slf4j
public class LandNonMarketerBrokerageHandler extends BrokerageCalculateSupport implements NonMarketerMarketerBrokerageCalculator {


    @Autowired
    private IItemBrokerageDetailService brokerageDetailService;

    @Autowired
    private LoadingCache<Long,BigDecimal> baseAmountsCache;
    @Override
    public ItemBrokerageDetail predictAmount(BrokerageDetailBO brokerageDetailBO) {
        checkItemBrokerageStatus(brokerageDetailBO);
        ItemBrokerageDetail itemBrokerageDetail = new ItemBrokerageDetail();
            //合同金额
        BigDecimal predictAmount = brokerageDetailBO.getAmount()
                //参与项目提成总比例
                .multiply(PARTICIPANT_BROKERAGE_PERCENTAGE)
                //阶段权重
                .multiply(brokerageDetailBO.getStageWeight()).divide(HUNDRED)
                //参与人权重
                .multiply(brokerageDetailBO.getParticipantWeight()).divide(HUNDRED);
        brokerageDetailBO.setPredictAmount(predictAmount.setScale(2,BigDecimal.ROUND_HALF_UP));
        BeanUtil.copyProperties(brokerageDetailBO,itemBrokerageDetail);
        log.info("项目id:[{}],合同金额：[{}],提成系数：[null],[未设置[土规部参与项目整体提成比例]，无法计算参与人员提成]",brokerageDetailBO.getItemId(),brokerageDetailBO.getAmount());
        return itemBrokerageDetail;
    }

    @Override
    public BigDecimal aheadAmount(Long userId){
        try {
            BigDecimal baseAheadAmount = baseAmountsCache.get(userId)==null
                    ?NON_MARKETER_MONTH_BROKERAGE
                    :baseAmountsCache.get(userId);
            return baseAheadAmount;
        } catch (ExecutionException e) {
            log.error("获取提成缓存数据失败");
            return BigDecimal.ZERO;
        }
    }
    @Override
    public List<ItemBrokerageDetail> actualAmount(ParticipantSettleDTO participantSettleDTO) {
        checkItemBrokerageStatusOnParticipantPredict(participantSettleDTO.getBrokerageState());
        List<ItemBrokerageDetail> participantBrokerageDetails = brokerageDetailService.list(new LambdaQueryWrapper<ItemBrokerageDetail>().eq(ItemBrokerageDetail::getGeneralId, participantSettleDTO.getGeneralId())
                .eq(BaseEntity::getDeleted, Boolean.FALSE).eq(ItemBrokerageDetail::getBrokerageRule, BrokerageRule.LAND_OTHER_RULE.getCode()));
        Map<Long, List<ItemBrokerageDetail>> brokerageByStage = participantBrokerageDetails.stream().collect(Collectors.groupingBy(ItemBrokerageDetail::getBrokerageStageId));
        for (Map.Entry<Long,List<ItemBrokerageDetail>> detail : brokerageByStage.entrySet()){
            for (ItemStage stage : participantSettleDTO.getStages()){
                if (detail.getKey().equals(stage.getId())){
                    List<ItemBrokerageDetail> value = detail.getValue();
                    for (ItemBrokerageDetail brokerage :value){
                        brokerage.setActualAmount(brokerage.getPredictAmount().multiply(participantSettleDTO.getWeight()).divide(HUNDRED));
                        if (stage.getOverdue()){
                            brokerage.setActualAmount(brokerage.getActualAmount().multiply(stage.getCoefficient()).divide(HUNDRED));
                        }
                    }
                }
            }
        }

        return participantBrokerageDetails;
    }

    @Override
    public BigDecimal advanceTotalAmount() {
        return null;
    }

    @Override
    public int advanceTimes() {
        return 0;
    }
}
