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

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import com.aliyun.core.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.ruoyi.bst.areaJoin.domain.enums.AreaJoinPermission;
import com.ruoyi.bst.bonus.domain.Bonus;
import com.ruoyi.bst.bonus.service.BonusConverter;
import com.ruoyi.bst.bonus.service.BonusService;
import com.ruoyi.bst.pay.domain.Pay;
import com.ruoyi.bst.pay.domain.vo.DoPayVO;
import com.ruoyi.bst.pay.service.PayConverter;
import com.ruoyi.bst.pay.service.PayService;
import com.ruoyi.bst.vipOrder.domain.VipOrder;
import com.ruoyi.bst.vipOrder.domain.VipOrderQuery;
import com.ruoyi.bst.vipOrder.domain.VipOrderVO;
import com.ruoyi.bst.vipOrder.domain.bo.VipOrderCreateBO;
import com.ruoyi.bst.vipOrder.domain.dto.VipOrderCreateDTO;
import com.ruoyi.bst.vipOrder.mapper.VipOrderMapper;
import com.ruoyi.bst.vipOrder.service.VipOrderConverter;
import com.ruoyi.bst.vipOrder.service.VipOrderService;
import com.ruoyi.bst.vipOrder.service.VipOrderValidator;
import com.ruoyi.common.core.redis.RedisLock;
import com.ruoyi.common.core.redis.enums.RedisLockKey;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.SnowFlakeUtil;

/**
 * 卡券订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-24
 */
@Service
public class VipOrderServiceImpl implements VipOrderService
{
    @Autowired
    private VipOrderMapper vipOrderMapper;

    @Autowired
    private VipOrderConverter vipOrderConverter;

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private VipOrderValidator vipOrderValidator;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private BonusConverter bonusConverter;

    @Autowired
    private PayConverter payConverter;

    @Autowired
    private PayService payService;

    @Autowired
    private BonusService bonusService;

    /**
     * 查询卡券订单
     *
     * @param id 卡券订单主键
     * @return 卡券订单
     */
    @Override
    public VipOrderVO selectVipOrderById(Long id, boolean scope)
    {
        if (id == null) {
            return null;
        }
        VipOrderQuery query = new VipOrderQuery();
        query.setId(id);
        query.setScope(scope);
        query.addAreaPermission(AreaJoinPermission.VIP_ORDER_VIEW.getCode());
        return this.selectOne(query);
    }

    private VipOrderVO selectOne(VipOrderQuery query) {
        PageHelper.startPage(1, 1);
        List<VipOrderVO> list = this.selectVipOrderList(query);
        return CollectionUtils.firstElement(list);
    }

    /**
     * 查询卡券订单列表
     *
     * @param vipOrder 卡券订单
     * @return 卡券订单
     */
    @Override
    public List<VipOrderVO> selectVipOrderList(VipOrderQuery vipOrder)
    {
        return vipOrderMapper.selectVipOrderList(vipOrder);
    }

    /**
     * 新增卡券订单
     *
     * @param vipOrder 卡券订单
     * @return 结果
     */
    @Override
    public int insertVipOrder(VipOrder vipOrder)
    {
        vipOrder.setCreateTime(DateUtils.getNowDate());
        vipOrder.setNo(String.valueOf(SnowFlakeUtil.newId()));
        return vipOrderMapper.insertVipOrder(vipOrder);
    }

    /**
     * 修改卡券订单
     *
     * @param vipOrder 卡券订单
     * @return 结果
     */
    @Override
    public int updateVipOrder(VipOrder vipOrder)
    {
        return vipOrderMapper.updateVipOrder(vipOrder);
    }

    /**
     * 批量删除卡券订单
     *
     * @param ids 需要删除的卡券订单主键
     * @return 结果
     */
    @Override
    public int deleteVipOrderByIds(Long[] ids)
    {
        return vipOrderMapper.deleteVipOrderByIds(ids);
    }

    /**
     * 删除卡券订单信息
     *
     * @param id 卡券订单主键
     * @return 结果
     */
    @Override
    public int deleteVipOrderById(Long id)
    {
        return vipOrderMapper.deleteVipOrderById(id);
    }

    @Override
    public DoPayVO createOrder(VipOrderCreateDTO dto) {
        ServiceUtil.assertion(dto == null, "卡券订单创建参数不能为空");

        // 加锁，防止设备重复下单
        Long lockKey = dto.getVipId();;
        boolean lock = redisLock.lock(RedisLockKey.VIP_ORDER_CREATE, lockKey);
        ServiceUtil.assertion(!lock, "请勿频繁下单");
        try {
            // 转为BO对象
            VipOrderCreateBO bo = vipOrderConverter.toCreateBO(dto);
            // 校验参数
            vipOrderValidator.validate(bo);

            return transactionTemplate.execute(status -> {

                // 创建订单
                VipOrder order = bo.getOrder();
                int rows = this.insertVipOrder(order);
                ServiceUtil.assertion(rows != 1, "创建订单失败");

                // 查询订单
                VipOrderVO vo = this.selectVipOrderByNo(order.getNo());
                ServiceUtil.assertion(vo == null, "查询创建的订单失败");

                // 转为分成，并创建分成
                List<Bonus> bonusList = bonusConverter.toBonusList(bo);
                int bonusRows = bonusService.batchInsert(bonusList);
                ServiceUtil.assertion(bonusRows != bonusList.size(), "创建分成失败");

                // 创建支付单
                Pay pay = payConverter.toPayPO(bo);
                return payService.createPayBill(pay);
            });

        } finally {
            // 解锁
            redisLock.unlock(RedisLockKey.VIP_ORDER_CREATE, lockKey);
        }
    }

    private VipOrderVO selectVipOrderByNo(String no) {
        if (StringUtils.isBlank(no)) {
            return null;
        }
        VipOrderQuery query = new VipOrderQuery();
        query.setEqNo(no);
        return this.selectOne(query);
    }

    @Override
    public VipOrderVO selectDetailByUserId(Long id, Long userId) {
        if (id == null || userId == null) {
            return null;
        }
        VipOrderQuery query = new VipOrderQuery();
        query.setId(id);
        query.setUserId(userId);
        return this.selectOne(query);
    }

    @Override
    public int updateByQuery(VipOrder data, VipOrderQuery query) {
        return vipOrderMapper.updateByQuery(data, query);
    }
}
