package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.system.entity.DictData;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.entity.UserReferee;
import com.gxwebsoft.common.system.param.DictDataParam;
import com.gxwebsoft.common.system.service.DictDataService;
import com.gxwebsoft.common.system.service.UserRefereeService;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * 订单更新业务处理Service实现
 * 处理特定租户(10550)的订单相关业务逻辑
 *
 * @author 科技小王子
 * @since 2025-01-11 10:45:12
 */
@Slf4j
@Service
public class ShopOrderUpdate10550ServiceImpl implements ShopOrderUpdate10550Service {

    @Resource
    private UserService userService;
    @Resource
    private DictDataService dictDataService;
    @Resource
    private UserRefereeService userRefereeService;
    @Resource
    private ShopDealerOrderService shopDealerOrderService;
    @Resource
    private ShopDealerCapitalService shopDealerCapitalService;
    @Resource
    private ShopOrderGoodsService shopOrderGoodsService;
    @Resource
    private ShopGoodsService shopGoodsService;

    @Override
    public void update(ShopOrder order) {
        try {
            log.info("开始处理订单更新业务 - 订单ID: {}, 用户ID: {}, 租户ID: {}",
                order.getOrderId(), order.getUserId(), order.getTenantId());

            // 1. 获取合伙人条件配置
            BigDecimal partnerCondition = getPartnerCondition();
            if (partnerCondition == null) {
                log.warn("未找到合伙人条件配置，跳过用户等级更新");
                return;
            }

            // 2. 更新用户消费金额和等级
            updateUserGradeAndExpendMoney(order, partnerCondition);

            // 3. 处理分销业务（如果需要）
            // processDistributionBusiness(order);

            log.info("订单更新业务处理完成 - 订单ID: {}", order.getOrderId());
        } catch (Exception e) {
            log.error("处理订单更新业务异常 - 订单ID: {}", order.getOrderId(), e);
        }
    }

    /**
     * 获取合伙人条件配置
     * @return 合伙人条件金额
     */
    private BigDecimal getPartnerCondition() {
        try {
            // 查询字典ID为1460的配置
            DictDataParam param = new DictDataParam();
            param.setDictId(1460);
            List<DictData> dictDataList = dictDataService.listRel(param);

            if (dictDataList != null && !dictDataList.isEmpty()) {
                String dictDataCode = dictDataList.get(0).getDictDataCode();
                BigDecimal partnerCondition = new BigDecimal(dictDataCode);
                log.info("获取合伙人条件配置成功 - 金额: {}", partnerCondition);
                return partnerCondition;
            }
        } catch (Exception e) {
            log.error("获取合伙人条件配置异常", e);
        }
        return null;
    }

    /**
     * 更新用户等级和消费金额
     * @param order 订单信息
     * @param partnerCondition 合伙人条件金额
     */
    private void updateUserGradeAndExpendMoney(ShopOrder order, BigDecimal partnerCondition) {
        try {
            // 查询用户信息（忽略租户隔离）
            User user = userService.getByIdIgnoreTenant(order.getUserId());
            if (user == null) {
                log.warn("用户不存在 - 用户ID: {}", order.getUserId());
                return;
            }

            // 累加消费金额
            BigDecimal currentExpendMoney = user.getExpendMoney() != null ? user.getExpendMoney() : BigDecimal.ZERO;
            BigDecimal newExpendMoney = currentExpendMoney.add(order.getPayPrice());
            user.setExpendMoney(newExpendMoney);

            // 检查是否达到合伙人条件
            boolean shouldUpgrade = newExpendMoney.compareTo(partnerCondition) >= 0 && !Integer.valueOf(3).equals(user.getGradeId());
            if (shouldUpgrade) {
                user.setGradeId(3);
                log.info("用户等级升级为合伙人 - 用户ID: {}, 消费金额: {}, 条件金额: {}",
                    user.getUserId(), newExpendMoney, partnerCondition);
            }

            // 更新用户信息（使用忽略租户隔离的更新方法）
            userService.updateByUserId(user);

            log.info("用户信息更新成功 - 用户ID: {}, 消费金额: {} -> {}, 等级: {}",
                user.getUserId(), currentExpendMoney, newExpendMoney, user.getGradeId());

        } catch (Exception e) {
            log.error("更新用户等级和消费金额异常 - 用户ID: {}", order.getUserId(), e);
        }
    }

    /**
     * 处理分销业务（暂时注释，如需启用请取消注释）
     * @param order 订单信息
     */
    @SuppressWarnings("unused")
    private void processDistributionBusiness(ShopOrder order) {
        try {
            // 获取推荐人信息
            User parent = getParentUser(order.getUserId());
            if (parent == null) {
                log.info("用户无推荐人，跳过分销业务处理 - 用户ID: {}", order.getUserId());
                return;
            }

            // 计算佣金
            BigDecimal commission = calculateCommission(order);
            if (commission.compareTo(BigDecimal.ZERO) <= 0) {
                log.info("佣金为0，跳过分销业务处理 - 订单ID: {}", order.getOrderId());
                return;
            }

            // 更新推荐人余额
            updateParentBalance(parent, commission);

            // 创建分销订单记录
            createDealerOrder(parent, order, commission);

            // 创建分销资金明细
            createDealerCapital(parent, order);

            log.info("分销业务处理完成 - 订单ID: {}, 推荐人ID: {}, 佣金: {}",
                order.getOrderId(), parent.getUserId(), commission);

        } catch (Exception e) {
            log.error("处理分销业务异常 - 订单ID: {}", order.getOrderId(), e);
        }
    }

    /**
     * 获取推荐人信息
     * @param userId 用户ID
     * @return 推荐人信息
     */
    private User getParentUser(Integer userId) {
        try {
            UserReferee userReferee = userRefereeService.getByUserId(userId);
            if (userReferee != null && userReferee.getDealerId() != null) {
                return userService.getByIdIgnoreTenant(userReferee.getDealerId());
            }
        } catch (Exception e) {
            log.error("获取推荐人信息异常 - 用户ID: {}", userId, e);
        }
        return null;
    }

    /**
     * 计算佣金
     * @param order 订单信息
     * @return 总佣金
     */
    private BigDecimal calculateCommission(ShopOrder order) {
        try {
            // 获取订单商品列表（忽略租户隔离）
            List<ShopOrderGoods> orderGoodsList = shopOrderGoodsService.getListByOrderIdIgnoreTenant(order.getOrderId());
            if (orderGoodsList.isEmpty()) {
                return BigDecimal.ZERO;
            }

            // 获取商品信息
            List<Integer> goodsIds = orderGoodsList.stream()
                .map(ShopOrderGoods::getGoodsId)
                .toList();
            List<ShopGoods> goodsList = shopGoodsService.listByIds(goodsIds);

            // 计算总佣金
            BigDecimal totalCommission = BigDecimal.ZERO;
            for (ShopOrderGoods orderGoods : orderGoodsList) {
                ShopGoods goods = goodsList.stream()
                    .filter(g -> g.getGoodsId().equals(orderGoods.getGoodsId()))
                    .findFirst()
                    .orElse(null);

                if (goods != null && goods.getCommission() != null) {
                    BigDecimal goodsCommission = goods.getCommission()
                        .multiply(BigDecimal.valueOf(orderGoods.getTotalNum()));
                    totalCommission = totalCommission.add(goodsCommission);
                }
            }

            log.info("佣金计算完成 - 订单ID: {}, 总佣金: {}", order.getOrderId(), totalCommission);
            return totalCommission;

        } catch (Exception e) {
            log.error("计算佣金异常 - 订单ID: {}", order.getOrderId(), e);
            return BigDecimal.ZERO;
        }
    }

    /**
     * 更新推荐人余额
     * @param parent 推荐人信息
     * @param commission 佣金金额
     */
    private void updateParentBalance(User parent, BigDecimal commission) {
        try {
            BigDecimal currentBalance = parent.getBalance() != null ? parent.getBalance() : BigDecimal.ZERO;
            BigDecimal newBalance = currentBalance.add(commission);
            parent.setBalance(newBalance);

            userService.updateByUserId(parent);

            log.info("推荐人余额更新成功 - 用户ID: {}, 余额: {} -> {}",
                parent.getUserId(), currentBalance, newBalance);

        } catch (Exception e) {
            log.error("更新推荐人余额异常 - 用户ID: {}", parent.getUserId(), e);
        }
    }

    /**
     * 创建分销订单记录
     * @param parent 推荐人信息
     * @param order 订单信息
     * @param commission 佣金金额
     */
    private void createDealerOrder(User parent, ShopOrder order, BigDecimal commission) {
        try {
            ShopDealerOrder dealerOrder = new ShopDealerOrder();
            dealerOrder.setUserId(parent.getUserId());
            dealerOrder.setOrderId(order.getOrderId());
            dealerOrder.setOrderPrice(order.getTotalPrice());
            dealerOrder.setFirstUserId(order.getUserId());
            dealerOrder.setFirstMoney(commission);
            dealerOrder.setIsSettled(1);
            dealerOrder.setSettleTime(LocalDateTime.now());

            shopDealerOrderService.save(dealerOrder);

            log.info("分销订单记录创建成功 - 推荐人ID: {}, 订单ID: {}", parent.getUserId(), order.getOrderId());

        } catch (Exception e) {
            log.error("创建分销订单记录异常 - 推荐人ID: {}, 订单ID: {}", parent.getUserId(), order.getOrderId(), e);
        }
    }

    /**
     * 创建分销资金明细
     * @param parent 推荐人信息
     * @param order 订单信息
     */
    private void createDealerCapital(User parent, ShopOrder order) {
        try {
            ShopDealerCapital dealerCapital = new ShopDealerCapital();
            dealerCapital.setUserId(parent.getUserId());
            dealerCapital.setOrderId(order.getOrderId());
            dealerCapital.setFlowType(10); // 分销收入

            shopDealerCapitalService.save(dealerCapital);

            log.info("分销资金明细创建成功 - 推荐人ID: {}, 订单ID: {}", parent.getUserId(), order.getOrderId());

        } catch (Exception e) {
            log.error("创建分销资金明细异常 - 推荐人ID: {}, 订单ID: {}", parent.getUserId(), order.getOrderId(), e);
        }
    }
}
