package co.yixiang.yshop.module.distributor.api;

import co.yixiang.yshop.framework.common.util.collection.CollectionUtils;
import co.yixiang.yshop.framework.dict.core.util.DictFrameworkUtils;
import co.yixiang.yshop.module.distributor.api.dto.DistributorOrderDTO;
import co.yixiang.yshop.module.distributor.api.dto.DistributorProductDTO;
import co.yixiang.yshop.module.distributor.controller.admin.distributororder.vo.DistributorOrderExportReqVO;
import co.yixiang.yshop.module.distributor.controller.admin.distributororder.vo.DistributorOrderUpdateReqVO;
import co.yixiang.yshop.module.distributor.dal.dataobject.distributor.DistributorDO;
import co.yixiang.yshop.module.distributor.dal.dataobject.distributorlevel.DistributorLevelDO;
import co.yixiang.yshop.module.distributor.dal.dataobject.distributororder.DistributorOrderDO;
import co.yixiang.yshop.module.distributor.dal.dataobject.distributoruser.DistributorUserDO;
import co.yixiang.yshop.module.distributor.enums.DistributorConstants;
import co.yixiang.yshop.module.distributor.enums.DistributorLevelTypeEnum;
import co.yixiang.yshop.module.distributor.enums.DistributorOrderStatusEnum;
import co.yixiang.yshop.module.distributor.enums.DistributorSettlementTypeEnum;
import co.yixiang.yshop.module.distributor.service.distributor.DistributorFacade;
import co.yixiang.yshop.module.distributor.service.distributor.DistributorService;
import co.yixiang.yshop.module.distributor.service.distributorlevel.DistributorLevelService;
import co.yixiang.yshop.module.distributor.service.distributororder.DistributorOrderService;
import co.yixiang.yshop.module.distributor.service.distributoruser.DistributorUserFacade;
import co.yixiang.yshop.module.distributor.service.distributoruser.DistributorUserService;
import co.yixiang.yshop.module.distributor.service.distributorwages.DistributorWagesFacade;
import co.yixiang.yshop.module.system.enums.DistributorDictEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class DistributorOrderApiImpl implements DistributorOrderApi {

    @Resource
    private DistributorUserService distributorUserService;

    @Resource
    private DistributorService distributorService;

    @Resource
    private DistributorLevelService distributorLevelService;

    @Resource
    private DistributorFacade distributorFacade;

    @Resource
    private DistributorOrderService distributorOrderService;

    @Resource
    private DistributorWagesFacade distributorWagesFacade;

    @Override
    public void createDistributorOrder(DistributorOrderDTO distributorOrderDTO) {
        List<DistributorOrderDO> list = new ArrayList<>();

        // 所属一级ID
        Long superiorIdP1 = null;
        // 一级名称
        String superiorNameP1 = null;
        // 所属二级ID
        Long superiorIdP2 = null;
        // 二级名称
        String superiorNameP2 = null;
        // 下单是不是分销商
        Boolean isDistributor = Boolean.FALSE;

        Integer distributorWager = 0;
        Integer firstWages = 0;
        Integer secondWages = 0;

        // 获取全局自购返佣
        String purchase = DictFrameworkUtils.parseDictDataValue(DistributorDictEnum.DISTRIBUTOR_PURCHASE.getDictType(), DistributorDictEnum.DISTRIBUTOR_PURCHASE.getLabel());

        // 获取下单用户是不是分销商
        DistributorDO distributorDO = distributorService.getDistributorByUserId(distributorOrderDTO.getUserId());
        DistributorLevelDO levelP0 = null;
        if (distributorDO != null) {
            isDistributor = Boolean.TRUE;
            levelP0 = distributorLevelService.getLevel(distributorDO.getLevelId());
            distributorWager = levelP0.getFirstWages();
        }

        // 没有分销商id 获取绑定关系 订单分销商id为空
        if (distributorOrderDTO.getDistributorId() == null) {
            // 获取绑定关系
            DistributorUserDO distributorUserDO = distributorUserService.getByUserId(distributorOrderDTO.getUserId());
            if (distributorUserDO != null && distributorUserDO.getExpireTime().isAfter(LocalDateTime.now())) {
                // 有绑定搞关系
                superiorIdP1 = distributorUserDO.getSuperiorIdP1();
                superiorNameP1 = distributorUserDO.getSuperiorNameP1();
                superiorIdP2 = distributorUserDO.getSuperiorIdP2();
                superiorNameP2 = distributorUserDO.getSuperiorNameP2();
            } else if (!isDistributor) {
                // 不是分销并且没有绑定关系
                return;
            }
        } else {
            // 有分销商id绑定用户
            Long distributorUserId = distributorFacade.bindUser(distributorOrderDTO.getDistributorId(), distributorOrderDTO.getUserId(), DistributorConstants.FALSE_INTEGER);
            // 获取用户绑定关系
            DistributorUserDO distributorUserDO = distributorUserService.getUser(distributorUserId);
            superiorIdP1 = distributorUserDO.getSuperiorIdP1();
            superiorNameP1 = distributorUserDO.getSuperiorNameP1();
            superiorIdP2 = distributorUserDO.getSuperiorIdP2();
            superiorNameP2 = distributorUserDO.getSuperiorNameP2();
        }

        // 一级分销商
        DistributorDO superiorP1;
        DistributorLevelDO levelP1;

        if (superiorIdP1 != null) {
            // 一级分销商
            superiorP1 = distributorService.get(superiorIdP1);
            levelP1 = distributorLevelService.getLevel(superiorP1.getLevelId());
            firstWages = levelP1.getFirstWages();
        }

        // 二级分销商
        DistributorDO superiorP2;
        DistributorLevelDO levelP2;

        if (superiorIdP2 != null) {
            superiorP2 = distributorService.get(superiorIdP2);
            levelP2 = distributorLevelService.getLevel(superiorP2.getLevelId());
            secondWages = levelP2.getSecondWages();
        }

        // 保存订单
        List<DistributorProductDTO> productDTOList = distributorOrderDTO.getProductDTOList();
        for (DistributorProductDTO dto : productDTOList) {
            DistributorOrderDO distributorOrderDO = new DistributorOrderDO();
            distributorOrderDO.setOid(distributorOrderDTO.getOid());
            distributorOrderDO.setOrderId(distributorOrderDTO.getOrderId());
            distributorOrderDO.setUserId(distributorOrderDTO.getUserId());
            distributorOrderDO.setUserName(distributorOrderDTO.getUserName());
            distributorOrderDO.setProductOriginalPrice(dto.getProductOriginalPrice());
            distributorOrderDO.setProductPrice(dto.getProductPrice());
            distributorOrderDO.setProductId(dto.getProductId());
            distributorOrderDO.setProductName(dto.getProductName());
            distributorOrderDO.setProductAttrValueId(dto.getProductAttrValueId());
            distributorOrderDO.setDetailId(dto.getDetailId());
            distributorOrderDO.setDistributionRule(dto.getDistributionRule());

            // 判断商品结算方式
            BigDecimal price;
            distributorOrderDO.setDistributionProductSettlement(dto.getDistributionProductSettlement());
            if (dto.getDistributionProductSettlement().equals(DistributorConstants.FALSE_INTEGER)) {
                // 实际支付
                price = dto.getProductPrice();
            } else {
                // 商品价格
                price = dto.getProductOriginalPrice();
            }
            // 判断分销等级
            distributorOrderDO.setDistributionLevel(dto.getDistributionLevel());
            // 判断全局自购开启并且商品支持自购
            if (purchase.equals(DistributorConstants.TURE_STR) && dto.getDistributionPurchase().equals(DistributorConstants.TURE_INTEGER) && isDistributor) {
                // 自购逻辑
                distributorOrderDO.setSuperiorIdP1(distributorDO.getId());
                distributorOrderDO.setSuperiorNameP1(distributorDO.getRealName());

                // 判断商品分销规则
                if (dto.getDistributionRule().equals(DistributorConstants.FALSE_INTEGER)) {
                    // 默认
                    distributorOrderDO.setFirstWages(distributorWager);
                    distributorOrderDO.setSecondWages(firstWages);
                } else {
                    // 自定义
                    distributorOrderDO.setFirstWages(dto.getFirstWages());
                    distributorOrderDO.setSecondWages(dto.getSecondWages());
                }

                distributorOrderDO.setFirstAmount(new BigDecimal(distributorOrderDO.getFirstWages()).multiply(price).divide(new BigDecimal(100), RoundingMode.HALF_DOWN));

                // 判断开启二级分销
                if (dto.getDistributionLevel().equals(DistributorLevelTypeEnum.P2.getType())) {
                    // 有二级
                    distributorOrderDO.setSuperiorIdP2(superiorIdP1);
                    distributorOrderDO.setSuperiorNameP2(superiorNameP1);
                    distributorOrderDO.setSecondAmount(new BigDecimal(distributorOrderDO.getSecondWages()).multiply(price).divide(new BigDecimal(100), RoundingMode.HALF_DOWN));
                }
            } else {
                // 正常逻辑
                distributorOrderDO.setSuperiorIdP1(superiorIdP1);
                distributorOrderDO.setSuperiorNameP1(superiorNameP1);
                // 判断商品分销规则
                if (dto.getDistributionRule().equals(DistributorConstants.FALSE_INTEGER)) {
                    // 默认
                    distributorOrderDO.setFirstWages(firstWages);
                    distributorOrderDO.setSecondWages(secondWages);
                } else {
                    // 自定义
                    distributorOrderDO.setFirstWages(dto.getFirstWages());
                    distributorOrderDO.setSecondWages(dto.getSecondWages());
                }

                distributorOrderDO.setFirstAmount(new BigDecimal(distributorOrderDO.getFirstWages()).multiply(price).divide(new BigDecimal(100), RoundingMode.HALF_DOWN));

                // 判断开启二级分销
                if (dto.getDistributionLevel().equals(DistributorLevelTypeEnum.P2.getType())) {
                    // 有二级
                    distributorOrderDO.setSuperiorIdP2(superiorIdP2);
                    distributorOrderDO.setSuperiorNameP2(superiorNameP2);
                    distributorOrderDO.setSecondAmount(new BigDecimal(distributorOrderDO.getSecondWages()).multiply(price).divide(new BigDecimal(100), RoundingMode.HALF_DOWN));
                }
            }


            // 佣金结算方式 0-支付后结算 1-确认收获后结算 2-订单完成结算
            distributorOrderDO.setDistributionWagesSettlement(dto.getDistributionWagesSettlement());
            if (dto.getDistributionWagesSettlement().equals(DistributorSettlementTypeEnum.PAY.getType())) {
                // 支付后结算
                distributorOrderDO.setStatus(DistributorOrderStatusEnum.COMPLETE.getStatus());
                distributorOrderDO.setSettlementTime(LocalDateTime.now());
            } else {
                distributorOrderDO.setStatus(DistributorOrderStatusEnum.WAIT.getStatus());
            }


            // 保存集合
            list.add(distributorOrderDO);
        }

        // 批量保存
        distributorOrderService.insertBatch(list);
        // 结算佣金
        list.forEach(x -> {
            distributorWagesFacade.saveWages(x);
            if (x.getStatus().equals(DistributorOrderStatusEnum.COMPLETE.getStatus())) {
                distributorWagesFacade.settlementWages(x);
            }
        });
    }

    @Override
    public void cancelDistributorOrder(List<Long> ids) {
        List<DistributorOrderDO> orderList = distributorOrderService.getOrderList(new DistributorOrderExportReqVO().setDetailIds(ids));
        // 所有详情id
        List<Long> distributorOrderIds = CollectionUtils.convertList(orderList, DistributorOrderDO::getId);
        distributorWagesFacade.cancelWages(distributorOrderIds);
    }

    @Override
    public void updateDistributorOrder(DistributorOrderDTO distributorOrderDTO) {
        // 所有商品
        List<DistributorProductDTO> productDTOList = distributorOrderDTO.getProductDTOList();

        for (DistributorProductDTO dto : productDTOList) {
            // 查询此订单
            DistributorOrderDO distributorOrderDO = distributorOrderService.getOrderByDetailId(dto.getDetailId());
            if (distributorOrderDO.getStatus().equals(DistributorOrderStatusEnum.WAIT.getStatus())) {
                // 判断结算步骤
                boolean isCompleteSettlementType = distributorOrderDTO.getDistributorSettlementType().equals(DistributorSettlementTypeEnum.COMPLETE.getType());
                boolean isMatchingDistributionProductSettlement = distributorOrderDTO.getDistributorSettlementType().equals(distributorOrderDO.getDistributionProductSettlement());

                if (isCompleteSettlementType || isMatchingDistributionProductSettlement) {
                    // 直接结算
                    settleOrderAndWages(distributorOrderDO);
                }
            }
        }
    }

    private void settleOrderAndWages(DistributorOrderDO distributorOrderDO) {
        // 更新订单状态订单
        DistributorOrderUpdateReqVO distributorOrderUpdateReqVO = new DistributorOrderUpdateReqVO();
        distributorOrderUpdateReqVO.setId(distributorOrderDO.getId());
        distributorOrderUpdateReqVO.setStatus(DistributorOrderStatusEnum.COMPLETE.getStatus());
        distributorOrderUpdateReqVO.setSettlementTime(LocalDateTime.now());
        distributorOrderService.updateOrder(distributorOrderUpdateReqVO);
        distributorWagesFacade.settlementWages(distributorOrderDO);
    }

}
