package com.ruoyi.brewery.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

import com.ruoyi.bar.domain.WyBar;
import com.ruoyi.bar.domain.WyBarIcon;
import com.ruoyi.bar.domain.WyBarIconLog;
import com.ruoyi.bar.service.IWyBarIconLogService;
import com.ruoyi.bar.service.IWyBarIconService;
import com.ruoyi.bar.service.IWyBarService;
import com.ruoyi.brewery.domain.WyGoods;
import com.ruoyi.brewery.service.IWyGoodsService;
import com.ruoyi.common.constant.CoinObtainType;
import com.ruoyi.common.constant.OrderStatusConstants;
import com.ruoyi.common.utils.CodeGeneratorUtils;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.stereotype.Service;
import com.ruoyi.brewery.mapper.WyRedeemOrderMapper;
import com.ruoyi.brewery.domain.WyRedeemOrder;
import com.ruoyi.brewery.service.IWyRedeemOrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 兑换订单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-21
 */
@Service
public class WyRedeemOrderServiceImpl implements IWyRedeemOrderService
{
    @Resource
    private WyRedeemOrderMapper wyRedeemOrderMapper;
    @Resource
    private IWyGoodsService wyGoodsService;
    @Resource
    private IWyBarIconService wyBarIconService;
    @Resource
    private IWyBarService wyBarService;
    @Resource
    private IWyBarIconLogService wyBarIconLogService;
    /**
     * 查询兑换订单
     *
     * @param id 兑换订单主键
     * @return 兑换订单
     */
    @Override
    public WyRedeemOrder selectWyRedeemOrderById(Long id)
    {
        return wyRedeemOrderMapper.selectWyRedeemOrderById(id);
    }

    /**
     * 查询兑换订单列表
     *
     * @param wyRedeemOrder 兑换订单
     * @return 兑换订单
     */
    @Override
    public List<WyRedeemOrder> selectWyRedeemOrderList(WyRedeemOrder wyRedeemOrder)
    {
        return wyRedeemOrderMapper.selectWyRedeemOrderList(wyRedeemOrder);
    }

    /**
     * 新增兑换订单
     *
     * @param wyRedeemOrder 兑换订单
     * @return 结果
     */
    @Override
    public int insertWyRedeemOrder(WyRedeemOrder wyRedeemOrder)
    {
        wyRedeemOrder.setOrderSn(generateOrderNo());
        wyRedeemOrder.setCreateTime(DateUtils.getNowDate());
        return wyRedeemOrderMapper.insertWyRedeemOrder(wyRedeemOrder);
    }

    /**
     * 生成订单号
     * @return 订单号
     */
    private String generateOrderNo() {
        //生成四位随机数
//        Random random = new Random();
//        int randomNum = random.nextInt(10000);
//        String orderNo = DateUtils.dateTimeNow() + String.format("%04d", randomNum);
        String orderNo = CodeGeneratorUtils.generateOrderNumber();
        //生成订单号
        final WyRedeemOrder query = new WyRedeemOrder();
        query.setOrderSn(orderNo);
        final List<WyRedeemOrder> wyRedeemOrders = selectWyRedeemOrderList(query);
        if (wyRedeemOrders.size() > 0) {
            return generateOrderNo();
        }
        return orderNo;
    }

    /**
     * 创建兑换订单
     * @param wyRedeemOrder 兑换订单
     * @return  结果
     */
    @Transactional
    @Override
    public Long createWyRedeemOrder(WyRedeemOrder wyRedeemOrder)
    {
        if (wyRedeemOrder.getGoodsId() == null) {
            throw new IllegalArgumentException("商品ID不能为空");
        }
        final WyGoods wyGoods = wyGoodsService.selectWyGoodsById(wyRedeemOrder.getGoodsId());
        if (wyGoods == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        final Long stockNum = wyGoods.getStockNum(); // 商品库存
        if (stockNum == null || stockNum <= 0) {
            throw new IllegalArgumentException("商品库存不足");
        }
        if (wyRedeemOrder.getRedeemNum() == null || wyRedeemOrder.getRedeemNum() > stockNum) {
            throw new IllegalArgumentException("兑换数量不能大于库存数量");
        }
        //检查是否有足够的积分
        WyBarIcon wyBarIcon = wyBarIconService.selectWyBarIconByBreweryIdAndBarId(wyGoods.getBreweryId(), wyRedeemOrder.getBarId());
        WyBarIcon platformIcon = wyBarIconService.selectWyBarIconByBreweryIdAndBarId(0L, wyRedeemOrder.getBarId());
        if (wyBarIcon == null) {
//            throw new IllegalArgumentException("尚未获得该品牌的啤酒币");
            //钱包不存在,创建钱包
            wyBarIcon = new WyBarIcon();
            wyBarIcon.setBreweryId(wyGoods.getBreweryId());
            wyBarIcon.setBarId(wyRedeemOrder.getBarId());
            wyBarIcon.setBalance(0L);
            wyBarIconService.insertWyBarIcon(wyBarIcon);
        }
        if (platformIcon == null) {
            platformIcon = new WyBarIcon();
            platformIcon.setBreweryId(0L);
            platformIcon.setBarId(wyRedeemOrder.getBarId());
            platformIcon.setBalance(0L);
            wyBarIconService.insertWyBarIcon(platformIcon);
        }
//        if(wyGoods.getGoodsPrice() == null){
//            throw new IllegalArgumentException("商品价格异常无法兑换，请联系管理员");
//        }
        final BigDecimal num = new BigDecimal(wyRedeemOrder.getRedeemNum());
        final BigDecimal redeemedNum = BigDecimal.valueOf(wyGoods.getRedeemedNum()); //兑换所需的啤酒币数量
        final BigDecimal priceAll = redeemedNum.multiply(num);
        final BigDecimal balance = new BigDecimal(wyBarIcon.getBalance());
        final BigDecimal balancePlatform = new BigDecimal(platformIcon.getBalance());
        final BigDecimal balanceAll = balance.add(balancePlatform);
        if (balanceAll.compareTo(BigDecimal.ZERO) < 0 || balanceAll.compareTo(priceAll) < 0) {
            throw new IllegalArgumentException("啤酒币余额不足");
        }
        BigDecimal balancePlatformPay = BigDecimal.ZERO;
        if (balance.compareTo(priceAll) < 0){
            balancePlatformPay = balancePlatform.subtract(balance); //平台币代付
            if (balancePlatformPay.compareTo(BigDecimal.ZERO) < 0) {    //平台币余额不足
                throw new IllegalArgumentException("啤酒币余额不足");
            }
        }
        final WyBar wyBar = wyBarService.selectWyBarById(wyRedeemOrder.getBarId());
        if (wyBar == null) {
            throw new IllegalArgumentException("门店不存在");
        }
        wyRedeemOrder.setBreweryId(wyGoods.getBreweryId());
        wyRedeemOrder.setCreateTime(DateUtils.getNowDate());
        wyRedeemOrder.setUpdateTime(DateUtils.getNowDate());
        wyRedeemOrder.setGoodsName(wyGoods.getGoodsName());
        wyRedeemOrder.setAddress(wyBar.getAddress()); // 门店地址
        wyRedeemOrder.setContactPerson(wyBar.getBarContactPhone()); // 门店联系电话
        wyRedeemOrder.setContactPhone(wyBar.getBarContactPhone()); // 门店联系电话
        wyRedeemOrder.setPaidTime(DateUtils.getNowDate());
        wyRedeemOrder.setOrderStatus(OrderStatusConstants.ORDER_STATUS_PAID); // 已支付,待发货
        wyRedeemOrder.setBeerCoinNum(priceAll.subtract(balancePlatformPay).longValue());
        wyRedeemOrder.setPlatformCoinNum(balancePlatformPay.longValue());
        final int i = insertWyRedeemOrder(wyRedeemOrder);
        //减库存
        wyGoods.setStockNum(stockNum - wyRedeemOrder.getRedeemNum());
        wyGoods.setFrozenNum(wyGoods.getFrozenNum() + wyRedeemOrder.getRedeemNum());
        wyGoodsService.updateWyGoods(wyGoods);
        //开始兑换
        wyBarIcon.setBalance(balance.subtract(priceAll).add(balancePlatformPay).longValue());
        wyBarIconService.updateWyBarIcon(wyBarIcon);
        //记录钱包变动日志
        final WyBarIconLog wyBarIconLog = new WyBarIconLog();
        wyBarIconLog.setBarId(wyRedeemOrder.getBarId());
        wyBarIconLog.setBreweryId(wyRedeemOrder.getBreweryId()); //平台奖励
        wyBarIconLog.setBalance(wyBarIcon.getBalance());
        wyBarIconLog.setAmount(priceAll.subtract(balancePlatformPay).longValue() * -1);//变动数量
        String remark = "兑换商品:" + wyRedeemOrder.getGoodsName() + " 数量:" + wyRedeemOrder.getRedeemNum();
        //平台币支付大于0
        if (balancePlatformPay.compareTo(BigDecimal.ZERO) > 0) {
            //平台币代付
            remark += " 平台币代付:" + balancePlatformPay.toString();
        }
        wyBarIconLog.setRemark(remark);
        wyBarIconLog.setObtainType(CoinObtainType.EXCHANGE); //兑换商品
        wyBarIconLogService.insertWyBarIconLog(wyBarIconLog);
        //平台币支付大于0
        if (balancePlatformPay.compareTo(BigDecimal.ZERO) > 0) {
            //平台币代付
            platformIcon.setBalance(balancePlatform.subtract(balancePlatformPay).longValue());
            wyBarIconService.updateWyBarIcon(platformIcon);
            //记录钱包变动日志
            final WyBarIconLog wyBarIconLogPlatform = new WyBarIconLog();
            wyBarIconLogPlatform.setBarId(wyRedeemOrder.getBarId());
            wyBarIconLogPlatform.setBreweryId(0L); //平台奖励
            wyBarIconLogPlatform.setBalance(platformIcon.getBalance());
            wyBarIconLogPlatform.setAmount(balancePlatformPay.longValue() * -1);//变动数量
            final String remarkPlatform = "平台币代付:" + balancePlatformPay.toString();
            wyBarIconLogPlatform.setRemark(remarkPlatform);
            wyBarIconLogPlatform.setObtainType(CoinObtainType.EXCHANGE); //平台币代付兑换商品
            wyBarIconLogService.insertWyBarIconLog(wyBarIconLogPlatform);
        }
        return wyRedeemOrder.getId();
    }

    /**
     * 修改订单状态
     */
    @Transactional
    @Override
    public int updateOrderStatus(WyRedeemOrder wyRedeemOrder) {
        if (wyRedeemOrder == null || wyRedeemOrder.getId() == null) {
            throw new IllegalArgumentException("订单不存在");
        }
        final WyRedeemOrder redeemOrder = selectWyRedeemOrderById(wyRedeemOrder.getId());// 检查订单是否存在
        if (wyRedeemOrder.getOrderStatus() == 2) { // 已发货
            redeemOrder.setShippingStatus(1);
            redeemOrder.setShippingTime(DateUtils.getNowDate());
            redeemOrder.setTrackingNumber(wyRedeemOrder.getTrackingNumber());
            redeemOrder.setDispatchMethod(wyRedeemOrder.getDispatchMethod());
            redeemOrder.setShippingCompany(wyRedeemOrder.getShippingCompany());
        } else if (wyRedeemOrder.getOrderStatus() == -1) { // 已取消
           //还原库存
            final WyGoods wyGoods = wyGoodsService.selectWyGoodsById(redeemOrder.getGoodsId());
            if (wyGoods == null) {
                throw new IllegalArgumentException("商品不存在");
            }
            wyGoods.setStockNum(wyGoods.getStockNum() + redeemOrder.getRedeemNum());
            wyGoods.setFrozenNum(wyGoods.getFrozenNum() - redeemOrder.getRedeemNum());
            wyGoodsService.updateWyGoods(wyGoods);
            //还原积分
            final WyBarIcon wyBarIcon = wyBarIconService.selectWyBarIconByBreweryIdAndBarId(redeemOrder.getBreweryId(), redeemOrder.getBarId());
            if (wyBarIcon == null) {
                throw new IllegalArgumentException("尚未获得该品牌的啤酒币");
            }
            final long iconNum = new BigDecimal(redeemOrder.getBeerCoinNum()).longValue();
            wyBarIcon.setBalance(wyBarIcon.getBalance() + iconNum);
            wyBarIconService.updateWyBarIcon(wyBarIcon);
            //记录钱包变动日志
            final WyBarIconLog wyBarIconLog = new WyBarIconLog();
            wyBarIconLog.setBarId(redeemOrder.getBarId());
            wyBarIconLog.setBreweryId(redeemOrder.getBreweryId()); //平台奖励
            wyBarIconLog.setBalance(wyBarIcon.getBalance());
            final BigDecimal multiply = new BigDecimal(redeemOrder.getBeerCoinNum()).multiply(new BigDecimal(-1));
            wyBarIconLog.setAmount(multiply.longValue());//变动数量
            final String remark = "取消兑换商品:" + redeemOrder.getGoodsName() + " 数量:" + redeemOrder.getRedeemNum();
            wyBarIconLog.setRemark(remark);
            wyBarIconLog.setObtainType(3); //兑换商品
            wyBarIconLogService.insertWyBarIconLog(wyBarIconLog);
        } else {
            throw new IllegalArgumentException("订单状态错误");
        }
        return wyRedeemOrderMapper.updateWyRedeemOrder(redeemOrder);
    }

    /**
     * 修改兑换订单
     *
     * @param wyRedeemOrder 兑换订单
     * @return 结果
     */
    @Override
    public int updateWyRedeemOrder(WyRedeemOrder wyRedeemOrder)
    {
        wyRedeemOrder.setUpdateTime(DateUtils.getNowDate());
        return wyRedeemOrderMapper.updateWyRedeemOrder(wyRedeemOrder);
    }

    /**
     * 批量删除兑换订单
     *
     * @param ids 需要删除的兑换订单主键
     * @return 结果
     */
    @Override
    public int deleteWyRedeemOrderByIds(Long[] ids)
    {
        return wyRedeemOrderMapper.deleteWyRedeemOrderByIds(ids);
    }

    /**
     * 删除兑换订单信息
     *
     * @param id 兑换订单主键
     * @return 结果
     */
    @Override
    public int deleteWyRedeemOrderById(Long id)
    {
        return wyRedeemOrderMapper.deleteWyRedeemOrderById(id);
    }
}
