package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.store.MerchantPaymentOrder;
import shop.alien.entity.store.UserReservationOrder;
import shop.alien.mapper.UserReservationOrderMapper;
import shop.alien.store.service.MerchantPaymentOrderService;
import shop.alien.store.service.UserReservationOrderService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 用户预订订单表 服务实现类
 *
 * @author system
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class UserReservationOrderServiceImpl extends ServiceImpl<UserReservationOrderMapper, UserReservationOrder> implements UserReservationOrderService {

    private final MerchantPaymentOrderService merchantPaymentOrderService;

    @Override
    public UserReservationOrder getByOrderSn(String orderSn) {
        if (orderSn == null || orderSn.trim().isEmpty()) {
            return null;
        }
        LambdaQueryWrapper<UserReservationOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserReservationOrder::getOrderSn, orderSn);
        return this.getOne(wrapper);
    }

    @Override
    public UserReservationOrder getByOutTradeNo(String outTradeNo) {
        if (outTradeNo == null || outTradeNo.trim().isEmpty()) {
            return null;
        }
        MerchantPaymentOrder paymentOrder = merchantPaymentOrderService.getByOutTradeNo(outTradeNo);
        if (paymentOrder == null) {
            return null;
        }
        return this.getById(paymentOrder.getOrderId());
    }

    @Override
    public String generateOrderSn() {
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        int random = ThreadLocalRandom.current().nextInt(1000000);
        return "YS" + dateStr + String.format("%06d", random);
    }

    @Override
    public int physicalDeleteByReservationId(Integer reservationId) {
        if (reservationId == null) {
            return 0;
        }
        return baseMapper.physicalDeleteByReservationId(reservationId);
    }

    @Override
    public List<Integer> listOrderIdsForRefundRetry() {
        return baseMapper.listOrderIdsForRefundRetry();
    }
}
