package com.carmaintenance.controller;

import com.carmaintenance.dto.Result;
import com.carmaintenance.entity.ServiceOrder;
import com.carmaintenance.entity.Vehicle;
import com.carmaintenance.repository.ServiceOrderRepository;
import com.carmaintenance.repository.VehicleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 维保工单管理控制器
 */
@RestController
@RequestMapping("/orders")
@CrossOrigin
public class ServiceOrderController {

    @Autowired
    private ServiceOrderRepository serviceOrderRepository;

    @Autowired
    private VehicleRepository vehicleRepository;

    /**
     * 获取所有工单
     */
    @GetMapping
    public Result<List<ServiceOrder>> getAllOrders() {
        List<ServiceOrder> orders = serviceOrderRepository.findAll();
        return Result.success(orders);
    }

    /**
     * 根据ID获取工单
     */
    @GetMapping("/{id}")
    public Result<ServiceOrder> getOrderById(@PathVariable Integer id) {
        ServiceOrder order = serviceOrderRepository.findById(id).orElse(null);
        if (order == null) {
            return Result.notFound("工单不存在");
        }
        return Result.success(order);
    }

    /**
     * 根据客户ID获取工单列表
     */
    @GetMapping("/customer/{customerId}")
    public Result<List<ServiceOrder>> getOrdersByCustomerId(@PathVariable Integer customerId) {
        List<ServiceOrder> orders = serviceOrderRepository.findByCustomerId(customerId);
        return Result.success(orders);
    }

    /**
     * 根据车辆ID获取工单列表
     */
    @GetMapping("/vehicle/{vehicleId}")
    public Result<List<ServiceOrder>> getOrdersByVehicleId(@PathVariable Integer vehicleId) {
        List<ServiceOrder> orders = serviceOrderRepository.findByVehicleId(vehicleId);
        return Result.success(orders);
    }

    /**
     * 根据状态获取工单列表
     */
    @GetMapping("/status/{status}")
    public Result<List<ServiceOrder>> getOrdersByStatus(@PathVariable String status) {
        try {
            ServiceOrder.OrderStatus orderStatus = ServiceOrder.OrderStatus.valueOf(status);
            List<ServiceOrder> orders = serviceOrderRepository.findByStatus(orderStatus);
            return Result.success(orders);
        } catch (IllegalArgumentException e) {
            return Result.error("状态参数错误");
        }
    }

    /**
     * 创建工单
     */
    @PostMapping
    public Result<ServiceOrder> createOrder(@RequestBody ServiceOrder order) {
        String orderNo = generateOrderNo();
        order.setOrderNo(orderNo);
        order.setStatus(ServiceOrder.OrderStatus.pending);
        order.setPaymentStatus(ServiceOrder.PaymentStatus.unpaid);

        ServiceOrder savedOrder = serviceOrderRepository.save(order);
        return Result.success("工单创建成功", savedOrder);
    }

    /**
     * 更新工单
     */
    @PutMapping("/{id}")
    public Result<ServiceOrder> updateOrder(@PathVariable Integer id, @RequestBody ServiceOrder order) {
        ServiceOrder existingOrder = serviceOrderRepository.findById(id).orElse(null);
        if (existingOrder == null) {
            return Result.notFound("工单不存在");
        }

        // 记录原状态，用于后续判断是否需要更新车辆保养时间
        ServiceOrder.OrderStatus oldStatus = existingOrder.getStatus();

        if (order.getStaffId() != null) existingOrder.setStaffId(order.getStaffId());
        if (order.getArrivalTime() != null) existingOrder.setArrivalTime(order.getArrivalTime());
        if (order.getStartTime() != null) existingOrder.setStartTime(order.getStartTime());
        if (order.getCompleteTime() != null) existingOrder.setCompleteTime(order.getCompleteTime());
        if (order.getCurrentMileage() != null) existingOrder.setCurrentMileage(order.getCurrentMileage());
        if (order.getFaultDescription() != null) existingOrder.setFaultDescription(order.getFaultDescription());
        if (order.getDiagnosisResult() != null) existingOrder.setDiagnosisResult(order.getDiagnosisResult());
        if (order.getServiceItems() != null) existingOrder.setServiceItems(order.getServiceItems());
        if (order.getPartsCost() != null) existingOrder.setPartsCost(order.getPartsCost());
        if (order.getLaborCost() != null) existingOrder.setLaborCost(order.getLaborCost());
        if (order.getTotalCost() != null) existingOrder.setTotalCost(order.getTotalCost());
        if (order.getStatus() != null) existingOrder.setStatus(order.getStatus());
        if (order.getPaymentStatus() != null) existingOrder.setPaymentStatus(order.getPaymentStatus());
        if (order.getRemark() != null) existingOrder.setRemark(order.getRemark());

        ServiceOrder updatedOrder = serviceOrderRepository.save(existingOrder);

        // 如果工单状态变更为"已完成"，且服务类型为"保养维护"，则更新车辆的上次保养时间
        if (oldStatus != ServiceOrder.OrderStatus.completed
            && updatedOrder.getStatus() == ServiceOrder.OrderStatus.completed
            && updatedOrder.getServiceType() == ServiceOrder.ServiceType.maintenance) {

            Vehicle vehicle = vehicleRepository.findById(updatedOrder.getVehicleId()).orElse(null);
            if (vehicle != null) {
                // 使用完成时间作为上次保养时间，如果没有完成时间则使用当前时间
                LocalDate maintenanceDate = updatedOrder.getCompleteTime() != null
                    ? updatedOrder.getCompleteTime().toLocalDate()
                    : LocalDate.now();

                vehicle.setLastMaintenanceDate(maintenanceDate);

                // 更新车辆里程（如果工单中有记录当前里程）
                if (updatedOrder.getCurrentMileage() != null
                    && updatedOrder.getCurrentMileage().signum() > 0) {
                    vehicle.setMileage(updatedOrder.getCurrentMileage());
                }

                vehicleRepository.save(vehicle);
            }
        }

        return Result.success("更新成功", updatedOrder);
    }

    /**
     * 删除工单
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteOrder(@PathVariable Integer id) {
        if (!serviceOrderRepository.existsById(id)) {
            return Result.notFound("工单不存在");
        }
        serviceOrderRepository.deleteById(id);
        return Result.<Void>success("删除成功", null);
    }

    /**
     * 生成工单编号
     */
    private String generateOrderNo() {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long count = serviceOrderRepository.count() + 1;
        return "SO" + date + String.format("%04d", count);
    }
}
