package com.aircraft.modules.order.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aircraft.exception.BadRequestException;
import com.aircraft.modules.order.domain.OrderDetail;
import com.aircraft.modules.order.domain.enums.OrderTaskStatusEnum;
import com.aircraft.modules.order.mapper.OrderDetailMapper;
import com.aircraft.modules.order.service.IOrderDetailService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 订单明细表 服务实现类
 * </p>
 *
 * @author cli
 * @since 2025-07-10
 */
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements IOrderDetailService {

    @Override
    public OrderDetail addOrderDetail(OrderDetail orderTask) {
         this.save(orderTask);
         return orderTask;
    }

    @Override
    public List<OrderDetail> queryOrderDetailByOrderId(Long orderId) {
        return this.list(Wrappers.lambdaQuery(OrderDetail.class).eq(OrderDetail::getOrderId, orderId));
    }

    @Override
    public void deleteOrderDetailByOrderId(Long orderId) {
        // 根据订单ID 删除
        this.remove(Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getOrderId, orderId));
    }

    @Override
    public void checkOrderDetail(Long orderId, Long orderInitiatorId) {
        // 根据订单ID，飞行员ID查询,结果集返回一个
        OrderDetail orderDetail = list(
                Wrappers.lambdaQuery(OrderDetail.class)
                        .eq(OrderDetail::getOrderId, orderId)
                        .eq(OrderDetail::getOperatorId, orderInitiatorId)
                        .in(OrderDetail::getOrderItemStatus, OrderTaskStatusEnum.NOT_STARTED.getCode(), OrderTaskStatusEnum.PROCESSING.getCode())
        ).stream().findFirst().orElse(null);

        if (ObjectUtil.isNull(orderDetail)) {
            return;
        }
        throw new BadRequestException("新增订单飞行任务: 同一个订单同一个飞行员下，只能存在一个任务状态处于[未进行或进行中]");
    }

    @Override
    public OrderDetail obtainOrderDetailById(Long orderTaskId) {
        return getById(orderTaskId);
    }

    @Override
    public void updateOrderTaskStatus(Long orderTaskId, Integer taskStatus) {
        LambdaUpdateWrapper<OrderDetail> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(OrderDetail::getId, orderTaskId)
                .set(OrderDetail::getOrderItemStatus, taskStatus);
        this.update(updateWrapper);
    }

    @Override
    public void deleteOrderDetailById(Long id) {
        // 根据订单ID 删除
        this.remove(Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getId, id));
    }
}
