package com.aiotagro.cattletrade.business.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.aiotagro.cattletrade.business.entity.Vehicle;
import com.aiotagro.cattletrade.business.service.IVehicleService;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.aiotagro.common.core.web.domain.PageResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 车辆管理控制器
 *
 * @author System
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/vehicle")
public class VehicleController {

    @Autowired
    private IVehicleService vehicleService;

    /**
     * 查询车辆列表（分页+搜索）
     */
    @SaCheckPermission("vehicle:query")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody Map<String, Object> params) {
        try {

            PageResultResponse<Vehicle> result = vehicleService.pageQuery(params);


            return AjaxResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询车辆列表失败：" + e.getMessage());
        }
    }

    /**
     * 新增车辆
     */
    @SaCheckPermission("vehicle:add")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Vehicle vehicle) {
        try {

            // 参数验证
            if (vehicle.getLicensePlate() == null || vehicle.getLicensePlate().trim().isEmpty()) {
                return AjaxResult.error("车牌号不能为空");
            }

            AjaxResult result = vehicleService.addVehicle(vehicle);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("新增车辆失败：" + e.getMessage());
        }
    }

    /**
     * 编辑车辆
     */
    @SaCheckPermission("vehicle:edit")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody Vehicle vehicle) {
        try {

            // 参数验证
            if (vehicle.getId() == null) {
                return AjaxResult.error("车辆ID不能为空");
            }

            if (vehicle.getLicensePlate() == null || vehicle.getLicensePlate().trim().isEmpty()) {
                return AjaxResult.error("车牌号不能为空");
            }

            AjaxResult result = vehicleService.updateVehicle(vehicle);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("编辑车辆失败：" + e.getMessage());
        }
    }

    /**
     * 删除车辆（逻辑删除）
     */
    @SaCheckPermission("vehicle:delete")
    @GetMapping("/delete")
    public AjaxResult delete(@RequestParam Integer id) {
        try {

            if (id == null) {
                return AjaxResult.error("车辆ID不能为空");
            }

            AjaxResult result = vehicleService.deleteVehicle(id);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("删除车辆失败：" + e.getMessage());
        }
    }
}


