package cn.iocoder.yudao.module.asset.controller.admin.vehicleregistration;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.asset.controller.admin.vehicleregistration.vo.VehicleLicenseRecognizeRespVO;
import cn.iocoder.yudao.module.asset.controller.admin.vehicleregistration.vo.VehicleRegistrationPageReqVO;
import cn.iocoder.yudao.module.asset.controller.admin.vehicleregistration.vo.VehicleRegistrationRespVO;
import cn.iocoder.yudao.module.asset.controller.admin.vehicleregistration.vo.VehicleRegistrationSaveReqVO;
import cn.iocoder.yudao.module.asset.convert.vehicleregistration.VehicleRegistrationConvert;
import cn.iocoder.yudao.module.asset.dal.dataobject.vehicleregistration.VehicleRegistrationDO;
import cn.iocoder.yudao.module.asset.service.vehicleregistration.VehicleRegistrationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 车辆上牌记录 Controller
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - 车辆上牌记录")
@RestController
@RequestMapping("/asset/vehicle-registration")
@Validated
@Slf4j
public class VehicleRegistrationController {

    @Resource
    private VehicleRegistrationService vehicleRegistrationService;

    @PostMapping("/recognize-license")
    @Operation(summary = "识别行驶证")
    @PreAuthorize("@ss.hasPermission('asset:vehicle-registration:recognize')")
    public CommonResult<VehicleLicenseRecognizeRespVO> recognizeVehicleLicense(
            @Parameter(description = "行驶证图片文件", required = true)
            @RequestParam("file") MultipartFile file) throws IOException {

        log.info("[recognizeVehicleLicense][开始识别行驶证，文件名：{}，大小：{}]",
                file.getOriginalFilename(), file.getSize());

        // 读取图片数据
        byte[] imageData = file.getBytes();

        // 调用识别服务
        VehicleLicenseRecognizeRespVO result = vehicleRegistrationService.recognizeVehicleLicense(imageData);

        return success(result);
    }

    @PostMapping("/ocr")
    @Operation(summary = "通过文件URL识别行驶证")
    @PreAuthorize("@ss.hasPermission('asset:vehicle-registration:recognize')")
    public CommonResult<VehicleLicenseRecognizeRespVO> ocrVehicleLicense(
            @RequestBody Map<String, String> body) throws IOException {
        String fileUrl = body.get("fileUrl");
        if (fileUrl == null || fileUrl.isBlank()) {
            throw new IllegalArgumentException("fileUrl 不能为空");
        }
        log.info("[ocrVehicleLicense][通过URL识别行驶证：{}]", fileUrl);
        try (InputStream is = URI.create(fileUrl).toURL().openStream()) {
            byte[] imageData = is.readAllBytes();
            VehicleLicenseRecognizeRespVO result = vehicleRegistrationService.recognizeVehicleLicense(imageData);
            return success(result);
        }
    }

    @PostMapping("/create")
    @Operation(summary = "创建车辆上牌记录")
    @PreAuthorize("@ss.hasPermission('asset:vehicle-registration:create')")
    public CommonResult<Long> createVehicleRegistration(@Valid @RequestBody VehicleRegistrationSaveReqVO createReqVO) {
        return success(vehicleRegistrationService.createVehicleRegistration(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新车辆上牌记录")
    @PreAuthorize("@ss.hasPermission('asset:vehicle-registration:update')")
    public CommonResult<Boolean> updateVehicleRegistration(@Valid @RequestBody VehicleRegistrationSaveReqVO updateReqVO) {
        vehicleRegistrationService.updateVehicleRegistration(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除车辆上牌记录")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('asset:vehicle-registration:delete')")
    public CommonResult<Boolean> deleteVehicleRegistration(@RequestParam("id") Long id) {
        vehicleRegistrationService.deleteVehicleRegistration(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得车辆上牌记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('asset:vehicle-registration:query')")
    public CommonResult<VehicleRegistrationRespVO> getVehicleRegistration(@RequestParam("id") Long id) {
        VehicleRegistrationDO registration = vehicleRegistrationService.getVehicleRegistration(id);
        return success(VehicleRegistrationConvert.INSTANCE.convert(registration));
    }

    @GetMapping("/page")
    @Operation(summary = "获得车辆上牌记录分页")
    @PreAuthorize("@ss.hasPermission('asset:vehicle-registration:query')")
    public CommonResult<PageResult<VehicleRegistrationRespVO>> getVehicleRegistrationPage(@Valid VehicleRegistrationPageReqVO pageReqVO) {
        PageResult<VehicleRegistrationDO> pageResult = vehicleRegistrationService.getVehicleRegistrationPage(pageReqVO);
        return success(VehicleRegistrationConvert.INSTANCE.convertPage(pageResult));
    }

    @PutMapping("/confirm")
    @Operation(summary = "确认上牌记录（更新车辆信息）")
    @Parameter(name = "id", description = "上牌记录ID", required = true)
    @PreAuthorize("@ss.hasPermission('asset:vehicle-registration:update')")
    public CommonResult<Boolean> confirmRegistration(@RequestParam("id") Long id) {
        vehicleRegistrationService.confirmRegistration(id);
        return success(true);
    }

    @PutMapping("/void")
    @Operation(summary = "作废上牌记录")
    @Parameter(name = "id", description = "上牌记录ID", required = true)
    @PreAuthorize("@ss.hasPermission('asset:vehicle-registration:update')")
    public CommonResult<Boolean> voidRegistration(@RequestParam("id") Long id) {
        vehicleRegistrationService.voidRegistration(id);
        return success(true);
    }

}
