package cn.iocoder.yudao.module.ocr.api;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.ocr.api.dto.VehicleLicenseRespDTO;
import cn.iocoder.yudao.module.ocr.framework.ocr.core.client.OcrClient;
import cn.iocoder.yudao.module.ocr.framework.ocr.core.client.OcrClientFactory;
import cn.iocoder.yudao.module.ocr.framework.ocr.core.result.VehicleLicenseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;

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

/**
 * OCR 识别 API 实现类
 *
 * @author 芋道源码
 */
@RestController
@Validated
@Slf4j
public class OcrApiImpl implements OcrApi {

    @Resource
    private OcrClientFactory ocrClientFactory;

    @Override
    public CommonResult<VehicleLicenseRespDTO> recognizeVehicleLicense(String imageData, String provider) {
        long startTime = System.currentTimeMillis();

        log.info("[recognizeVehicleLicense][开始识别行驶证，provider：{}，数据长度：{}]",
                provider, imageData != null ? imageData.length() : 0);

        // Base64 解码图片数据
        byte[] imageBytes = Base64.decode(imageData);

        // 获取 OCR 客户端
        OcrClient ocrClient;
        if (StrUtil.isNotBlank(provider)) {
            ocrClient = ocrClientFactory.getClient(provider);
        } else {
            ocrClient = ocrClientFactory.getDefaultClient();
        }

        // 调用识别
        VehicleLicenseResult result = ocrClient.recognizeVehicleLicense(imageBytes);

        // 转换为 DTO
        VehicleLicenseRespDTO respDTO = BeanUtils.toBean(result, VehicleLicenseRespDTO.class);

        long costTime = System.currentTimeMillis() - startTime;
        log.info("[recognizeVehicleLicense][识别完成，耗时：{}ms，VIN：{}，车牌号：{}]",
                costTime, respDTO.getVin(), respDTO.getPlateNo());

        return success(respDTO);
    }

}
