package com.hotwj.platform.integration.ocr.aliyun;

import org.dromara.common.core.utils.StringUtils;
import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hotwj.platform.integration.ocr.OcrStrategy;
import com.hotwj.platform.integration.ocr.baidu.domain.vo.BusinessLicenseVo;
import com.hotwj.platform.integration.ocr.baidu.domain.vo.DrivingLicenseVo;
import com.hotwj.platform.integration.ocr.baidu.domain.vo.IdCardVo;
import com.hotwj.platform.integration.ocr.baidu.domain.vo.VehicleLicenseVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云OCR识别服务实现
 */
@Slf4j
@RequiredArgsConstructor
@Service("aliyunOcrStrategy")
public class AliyunOcrService implements OcrStrategy {

    private final AliyunOcrIdCardProperties properties;
    private final ISysOssService ossService;

    @Override
    public String getType() {
        return "aliyun";
    }

    private String formatDate(String dateStr) {
        if (StringUtils.isBlank(dateStr) || dateStr.length() != 8) {
            return dateStr;
        }
        return dateStr.substring(0, 4) + "-" + dateStr.substring(4, 6) + "-" + dateStr.substring(6, 8);
    }

    @Override
    public BusinessLicenseVo recognizeBusinessLicense(MultipartFile file) {
        throw new ServiceException("阿里云OCR暂不支持营业执照识别");
    }

    @Override
    public IdCardVo recognizeIdCard(MultipartFile file, String side) {
        // ... (原有实现) ...
        // 1. Upload to OSS (保持与百度OCR一致的逻辑，先上传再识别，方便前端回显)
        SysOssVo ossVo;
        try {
            ossVo = ossService.upload(file);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new ServiceException("文件上传失败: " + e.getMessage());
        }

        // 2. Read file content
        String base64;
        try {
            base64 = Base64.encode(file.getBytes());
        } catch (IOException e) {
            throw new ServiceException("读取文件失败");
        }

        // 3. Call Aliyun OCR API
        String host = properties.getHost();
        String path = properties.getPath();
        String appcode = properties.getAppcode();
        String method = "POST";

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/json; charset=UTF-8");

        JSONObject configObj = new JSONObject();
        // 阿里云参数: face=正面, back=反面. 兼容百度的 front 参数
        String aliSide = "front".equalsIgnoreCase(side) ? "face" : side;
        configObj.put("side", aliSide);

        JSONObject requestObj = new JSONObject();
        requestObj.put("image", base64);
        if (configObj.size() > 0) {
            requestObj.put("configure", configObj.toString());
        }
        String body = requestObj.toString();

        try {
            HttpResponse response = HttpRequest.post(host + path)
                    .headerMap(headers, true)
                    .body(body)
                    .timeout(10000)
                    .execute();

            int stat = response.getStatus();
            String resBody = response.body();
            log.info("阿里云OCR响应: {}", resBody);

            if (stat != 200) {
                log.error("阿里云OCR识别失败, Http code: {}, msg: {}", stat, resBody);
                throw new ServiceException("识别失败，请重试");
            }

            JSONObject json = JSONUtil.parseObj(resBody);
            // 阿里云返回结构解析
            // { "address" : "", "config_str" : "{\\\"side\\\":\\\"face\\\"}", "face_rect" : {...}, "name" : "张三", "nationality" : "汉", "num" : "...", "request_id" : "...", "sex" : "男", "success" : true, "birth" : "20000101" }

            Boolean success = json.getBool("success", false);
            if (!success) {
                throw new ServiceException("识别失败");
            }

            IdCardVo result = new IdCardVo();
            result.setOssId(ossVo.getOssId().toString());
            result.setUrl(ossVo.getUrl());

            if ("face".equals(aliSide)) {
                result.setName(json.getStr("name"));
                result.setIdNumber(json.getStr("num"));
                result.setAddress(json.getStr("address"));
                result.setGender(json.getStr("sex"));
                result.setEthnicity(json.getStr("nationality"));
                // 阿里云返回格式 YYYYMMDD，转换为 YYYY-MM-DD (兼容百度)
                result.setBirthDate(formatDate(json.getStr("birth"))); 
            } else {
                result.setExpiryDate(formatDate(json.getStr("end_date"))); // 格式 YYYYMMDD -> YYYY-MM-DD
                result.setIssueDate(formatDate(json.getStr("start_date"))); // 格式 YYYYMMDD -> YYYY-MM-DD
                result.setAuthority(json.getStr("issue"));
            }

            return result;

        } catch (Exception e) {
            log.error("调用阿里云OCR接口异常", e);
            if (e instanceof ServiceException) {
                throw e;
            }
            throw new ServiceException("识别服务异常");
        }
    }

    @Override
    public VehicleLicenseVo recognizeVehicleLicense(MultipartFile file, String side) {
        throw new ServiceException("阿里云OCR暂不支持行驶证识别");
    }

    @Override
    public DrivingLicenseVo recognizeDrivingLicense(MultipartFile file, String side) {
        throw new ServiceException("阿里云OCR暂不支持驾驶证识别");
    }
}