package com.ruoyi.bst.bonus.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.bst.areaJoin.domain.AreaJoinVO;
import com.ruoyi.bst.areaJoin.domain.enums.AreaJoinType;
import com.ruoyi.bst.areaJoin.service.AreaJoinService;
import com.ruoyi.bst.bonus.domain.Bonus;
import com.ruoyi.bst.bonus.domain.enums.BonusArrivalType;
import com.ruoyi.bst.bonus.domain.enums.BonusBstType;
import com.ruoyi.bst.bonus.domain.enums.BonusStatus;
import com.ruoyi.bst.bonus.service.BonusConverter;
import com.ruoyi.bst.bonus.utils.BonusUtil;
import com.ruoyi.bst.channel.domain.ChannelVO;
import com.ruoyi.bst.channel.domain.enums.ChannelType;
import com.ruoyi.bst.device.domain.DeviceVO;
import com.ruoyi.bst.order.domain.Order;
import com.ruoyi.bst.order.domain.bo.OrderCreateBO;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.iot.util.BatUtil;

@Service
public class BonusConverterImpl implements BonusConverter {

    @Autowired
    private AreaJoinService areaJoinService;

    @Override
    public List<Bonus> toBonusList(OrderCreateBO bo) {
        if (bo == null) {
            return Collections.emptyList();
        }

        ChannelVO channel = bo.getChannel();
        if (channel == null) {
            return Collections.emptyList();
        }

        // 加盟信息，当车辆归属用户不是当前运营区的运营商时，才有加盟信息
        DeviceVO device = bo.getDevice();
        if (device != null && device.getMchId() != null && !Objects.equals(device.getMchId(), device.getAreaUserId())) {
            AreaJoinVO areaJoin = areaJoinService.selectByUserArea(device.getMchId(), device.getAreaId());
            bo.setAreaJoin(areaJoin);
        }

        // 若渠道为官方收款，则处理官方收款分成
        if (ChannelType.PLATFORM.getType().equals(channel.getType())) {
            return this.toBonusListPlatform(bo);
        } else {
            // TODO 待处理
            throw new ServiceException("暂不支持独立收款渠道");
        }
    }

    // 处理官方收款分成
    private List<Bonus> toBonusListPlatform(OrderCreateBO bo) {

        // 获取基础分成列表
        List<Bonus> result = toBaseBonusListPlatform(bo.getDevice(), bo.getPartners(), bo.getAreaJoin());

        // 设置分成金额
        Order order = bo.getOrder();
        BonusUtil.partAmount(result, order.getPayAmount());

        // 设置其他基础数据
        String reason = "订单收入:" + order.getNo();
        for (Bonus bonus : result) {
            bonus.setReason(reason);
            bonus.setBstType(BonusBstType.ORDER.getType());
            bonus.setBstId(order.getId());
            bonus.setStatus(BonusStatus.INVALID.getStatus());
            bonus.setToBalance(true);
            bonus.setInvalidAmount(bonus.getAmount());
            bonus.setAreaId(order.getAreaId());
        }

        return result;
    }

    /**
     * 获取基础分成列表
     * @param device 设备
     * @param partners 运营区合伙人列表
     * @param join 设备的所属用户在对应区域的加盟信息
     */
    @Override
    public List<Bonus> toBaseBonusListPlatform(DeviceVO device, List<AreaJoinVO> partners, AreaJoinVO join) {
        if (device == null) {
            return Collections.emptyList();
        }

        Long areaUserId = device.getAreaUserId();   // 运营区归属用户(运营商)
        Long areaAgentId = device.getAreaAgentId(); // 运营区代理商
        BigDecimal totalPoint = BigDecimal.ZERO;    // 已分成百分比
        BigDecimal decimal100 = new BigDecimal(100);
        List<Bonus> result = new ArrayList<>();

        // 处理加盟分成：车是加盟商的，且加盟方式为加盟商
        if (join != null && Objects.equals(device.getMchId(), join.getUserId()) && AreaJoinType.JOIN.getCode().equals(join.getType())) {
            Long joinUserId = join.getUserId();  // 加盟用户ID
            // 加盟商分成
            Bonus bonus = BonusUtil.getInitBonus(BonusArrivalType.JOIN, joinUserId, join.getUserName(), join.getPoint());
            if (bonus != null) {
                result.add(bonus);
                // 代理商、运营商可见
                bonus.addViewUserId(areaUserId);
                bonus.addViewUserId(areaAgentId);
                totalPoint = totalPoint.add(bonus.getPoint());
            }
        }
        // 处理合伙人分成：车不是加盟商的，且运营区有合伙人
        else if (CollectionUtils.isNotEmptyElement(partners)) {
            for (AreaJoinVO partner : partners) {
                // 合伙人分成
                Bonus bonus = BonusUtil.getInitBonus(BonusArrivalType.PARTNER, partner.getUserId(), partner.getUserName(), partner.getPoint());
                if (bonus != null) {
                    result.add(bonus);
                    // 代理商、运营商可见
                    bonus.addViewUserId(areaUserId);
                    bonus.addViewUserId(areaAgentId);
                    totalPoint = totalPoint.add(bonus.getPoint());
                }
            }
        }

        // 运营商分成
        if (areaUserId != null && device.getAreaUserPoint() != null ) {
            Bonus bonus = BonusUtil.getInitBonus(BonusArrivalType.MCH, areaUserId, device.getAreaUserName(), device.getAreaUserPoint().subtract(totalPoint));
            if (bonus != null) {
                result.add(bonus);
                // 代理商可见
                bonus.addViewUserId(areaAgentId);
                totalPoint = totalPoint.add(bonus.getPoint());
            }
        }

        // 代理商分成
        if (areaAgentId != null && device.getAreaAgentPoint() != null) {
            Bonus bonus = BonusUtil.getInitBonus(BonusArrivalType.AGENT, areaAgentId, device.getAreaAgentName(), device.getAreaAgentPoint().subtract(totalPoint));
            if (bonus != null) {
                result.add(bonus);
                totalPoint = totalPoint.add(bonus.getPoint());
            }
        }

        // 平台分成
        if (totalPoint.compareTo(decimal100) < 0) {
            Bonus bonus = BonusUtil.getInitBonus(BonusArrivalType.PLATFORM, 1L, "创特科技", decimal100.subtract(totalPoint));
            if (bonus != null) {
                result.add(bonus);
                totalPoint = totalPoint.add(bonus.getPoint());
            }
        }

        // 判断分成是否正确
        if (totalPoint.compareTo(decimal100) != 0) {
            throw new ServiceException("分成计算错误，总分成百分比不为100%");
        }
        for (Bonus bonus : result) {
            ServiceUtil.assertion(bonus == null, "分成计算错误，分成方数据为空");
            ServiceUtil.assertion(bonus.getArrivalId() == null, "分成计算错误，分成方ID为空");
            ServiceUtil.assertion(bonus.getPoint().compareTo(BigDecimal.ZERO) < 0, "分成计算错误，分成方【%s】分成百分比为负数", bonus.getArrivalName());
        }


        return result;
    }

}
