package com.ruoyi.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.DlBaseEntity;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.member.domain.MemberOrder;
import com.ruoyi.member.mapper.MemberOrderMapper;
import com.ruoyi.member.service.IMemberCardService;
import com.ruoyi.member.service.IMemberCouponService;
import com.ruoyi.member.service.IMemberOrderService;
import com.ruoyi.member.vo.MemberOrderVO;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;

/**
 * 订单Service业务层处理
 *
 * @author pqz
 * @date 2025-03-17
 */
@Service
public class MemberOrderServiceImpl extends ServiceImpl<MemberOrderMapper, MemberOrder> implements IMemberOrderService {
    @Autowired
    private MemberOrderMapper memberOrderMapper;
    @Resource
    private IMemberCardService cardService;
    @Resource
    private IMemberCouponService couponService;


    /**
     * 分页查询订单列表
     *
     * @param memberOrder {@link MemberOrderVO}
     * @param page        分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.ruoyi.member.vo.MemberOrderVO>
     * @author PQZ
     * @date 15:25 2025/3/25
     **/
    @Override
    public IPage<MemberOrderVO> queryListPage(MemberOrderVO memberOrder, Page<MemberOrder> page) {
        return memberOrderMapper.queryListPage(memberOrder, page);
    }

    /**
     * 订单支付回调
     *
     * @param orderNo 订单编号
     * @author PQZ
     * @date 14:02 2025/3/26
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SneakyThrows
    public void payCallback(String orderNo) {
        /*1、校验数据完整性*/
        LambdaQueryWrapper<MemberOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DlBaseEntity::getDelFlag, 0).eq(MemberOrder::getOrderNo, orderNo);
        MemberOrder memberOrder = getOne(lambdaQueryWrapper);
        if(memberOrder.getIsPay() != 1) {
            /*2、处理不同类型订单*/
            if ("01".equals(memberOrder.getOrderType())) {
                cardService.dealMemberCard(memberOrder.getUserId(), memberOrder.getUserType(), memberOrder.getGoodsId(), memberOrder.getGoodsCycle(), memberOrder.getId());
            } else {
                couponService.dealMemberCoupon(memberOrder);
            }
            /*3、处理订单表数据*/
            memberOrder.setPayTime(new Date());
            memberOrder.setIsPay(1);
            memberOrder.setPayWay("02");
            updateById(memberOrder);
        }
    }

    /**
     * 保存订单并吊起支付(orderType,goodsCycle,goodsId,goodsNum,goodsPrice)
     *
     * @param memberOrder {@link MemberOrder}
     * @author PQZ
     * @date 14:02 2025/4/8
     **/
    @Override
    public String saveOrder(MemberOrder memberOrder) {
        //获取当前登录用户
        LoginUser securityUser = SecurityUtils.getLoginUser();
        memberOrder.setUserId(securityUser.getUserId());
        memberOrder.setNickname(securityUser.getUser().getNickName());
        memberOrder.setOrderNo(generateOrderId());
        //保存订单数据
        save(memberOrder);
        return  memberOrder.getOrderNo();
    }

    /**
     * 生成订单编号，生成规则：时间戳+随机数
     *
     * @return java.lang.String
     * @author PQZ
     * @date 14:14 2025/4/8
     **/
    private String generateOrderId() {
        // 获取当前时间戳（以秒为单位）
        long timestamp = System.currentTimeMillis() / 1000;
        // 生成3位随机数
        Random random = new Random();
        // 生成范围在100到999之间的随机数
        int randomNum = random.nextInt(900) + 100;
        // 组合成订单编号
        return "ORD-" + timestamp + String.format("%03d", randomNum);
    }

}
