package com.hotwj.platform.integration.ocr;

import cn.hutool.http.HttpUtil;
import com.hotwj.platform.integration.ocr.baidu.BaiduOcrService;
import com.hotwj.platform.integration.ocr.baidu.domain.bo.HandwritingRecognizeBo;
import com.hotwj.platform.integration.ocr.baidu.domain.vo.HandwritingOcrVo;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.service.ISysOssService;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;

@Service
@RequiredArgsConstructor
public class SignatureVerifyServiceImpl implements SignatureVerifyService {

    private final ISysOssService ossService;
    private final OcrProperties ocrProperties;
    private final BaiduOcrService baiduOcrService;

    @Override
    public void validateSelfSignature(Long signatureOssId, String userName) {

//        if (signatureOssId == null) {
//            throw new ServiceException("签名文件不能为空");
//        }
//        if (StringUtils.isBlank(userName)) {
//            throw new ServiceException("提交人姓名不能为空");
//        }
//        SysOssVo ossVo = ossService.getById(signatureOssId);
//        if (ossVo == null || StringUtils.isBlank(ossVo.getUrl())) {
//            throw new ServiceException("签名文件不存在");
//        }
//        byte[] imageBytes = downloadImageBytes(ossVo.getUrl());
//        HandwritingRecognizeBo bo = new HandwritingRecognizeBo();
//        bo.setImage(Base64.encode(imageBytes));
//        HandwritingOcrVo ocrVo = recognizeByProvider(bo);
//        int sameCount = countSameChars(StringUtils.defaultString(ocrVo.getWords()), userName);
//        if (sameCount < 2) {
//            throw new ServiceException("签名校验失败");
//        }
    }

    protected byte[] downloadImageBytes(String url) {
        try {
            return HttpUtil.downloadBytes(url);
        } catch (Exception e) {
            throw new ServiceException("下载签名图片失败");
        }
    }

    private HandwritingOcrVo recognizeByProvider(HandwritingRecognizeBo bo) {
        String provider = StringUtils.defaultIfBlank(ocrProperties.getProvider(), "baidu");
        if ("baidu".equalsIgnoreCase(provider)) {
            return baiduOcrService.recognizeHandwriting(bo);
        }
        throw new ServiceException("当前OCR厂商暂不支持手写签名校验");
    }

    private int countSameChars(String recognizeText, String userName) {
        if (StringUtils.isBlank(recognizeText) || StringUtils.isBlank(userName)) {
            return 0;
        }
        String target = userName.replaceAll("\\s+", "");
        String source = recognizeText.replaceAll("\\s+", "");
        LinkedHashSet<String> matchedChars = new LinkedHashSet<>();
        for (int i = 0; i < target.length(); i++) {
            String ch = String.valueOf(target.charAt(i));
            if (source.contains(ch)) {
                matchedChars.add(ch);
            }
        }
        return matchedChars.size();
    }
}
