package org.jeecg.modules.oroqen.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.oroqen.entity.OroqenOrder;
import org.jeecg.modules.oroqen.mapper.OroqenOrderMapper;
import org.jeecg.modules.oroqen.service.IOroqenOrderService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Description: 订单
 * @Author: jeecg-boot
 * @Date: 2025-01-08
 * @Version: V1.0
 */
@Service
public class OroqenOrderServiceImpl extends ServiceImpl<OroqenOrderMapper, OroqenOrder> implements IOroqenOrderService {

    @Override
    public List<OroqenOrder> getByUserId(String userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public List<OroqenOrder> getByStatus(Integer status) {
        return baseMapper.selectByStatus(status);
    }

    @Override
    public String createOrder(OroqenOrder order) {
        // 生成订单号
        String orderNo = generateOrderNo();
        order.setOrderNo(orderNo);
        order.setStatus(0); // 待付款
        order.setCreateTime(new Date());
        this.save(order);
        return order.getId();
    }

    @Override
    public void updateOrderStatus(String orderId, Integer status) {
        UpdateWrapper<OroqenOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", orderId);
        updateWrapper.set("status", status);
        updateWrapper.set("update_time", new Date());
        this.update(updateWrapper);
    }

    @Override
    public void cancelOrder(String orderId) {
        UpdateWrapper<OroqenOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", orderId);
        updateWrapper.set("status", 4); // 已取消
        updateWrapper.set("update_time", new Date());
        this.update(updateWrapper);
    }

    @Override
    public void shipOrder(String orderId, String shippingCompany, String trackingNumber) {
        UpdateWrapper<OroqenOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", orderId);
        updateWrapper.set("status", 2); // 待收货
        updateWrapper.set("shipping_company", shippingCompany);
        updateWrapper.set("tracking_number", trackingNumber);
        updateWrapper.set("shipping_time", new Date());
        updateWrapper.set("update_time", new Date());
        this.update(updateWrapper);
    }

    @Override
    public void confirmReceived(String orderId) {
        UpdateWrapper<OroqenOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", orderId);
        updateWrapper.set("status", 3); // 已完成
        updateWrapper.set("received_time", new Date());
        updateWrapper.set("update_time", new Date());
        this.update(updateWrapper);
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis();
    }
}