package com.fs.common.utils.txocr;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.CommonClient;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @description:
 * @author: Guos
 * @time: 2025/11/18 上午9:57
 */
@Slf4j
public class TxOcrClient  {

    private static final String YPLS = "药品零售";

    public static IdCardVerificationResponse IdCardVerification(String name, String idNumber) {
        IdCardVerificationResponse map = new IdCardVerificationResponse();
        try {
            Credential cred = new Credential("AKIDviPyMZbRp24udCcpqjQxHOK4cx88ze6N", "97tVwEJE81sY0StDPPGukQ2ZvkU3QceY");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("faceid.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            CommonClient client = new CommonClient("faceid", "2018-03-01", cred, "", clientProfile);
            String params = "{\"IdCard\":\""+idNumber+"\",\"Name\":\""+name+"\"}";
            String resp = client.call("IdCardVerification", params);
            JSONObject jsonObject = new JSONObject(resp);
            JSONObject response = (JSONObject)jsonObject.get("Response");
            map.setDescription(response.get("Description").toString());
            map.setResult(Integer.parseInt(response.get("Result").toString()));
        } catch (TencentCloudSDKException e) {
            log.error("身份证识别请求异常：{}",e.getMessage());
            map.setDescription("识别失败");
            map.setResult(-8);
        }
        return map;
    }
    /**
     * 医疗器械url识别
     * @return
     */
    public ContainsResult medicalDeviceUrlOcr(String imageUrl){
        String ocr = ExtractDocBasic(imageUrl);
        return null;
    }


    /**
     * 营业执照识别
     * @param imageUrl
     * @return
     */
    public static String bizLicenseOCR(String imageUrl){
        try{
            Credential cred = new Credential("AKIDviPyMZbRp24udCcpqjQxHOK4cx88ze6N", "97tVwEJE81sY0StDPPGukQ2ZvkU3QceY");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            OcrClient client = new OcrClient(cred, "", clientProfile);
            BizLicenseOCRRequest req = new BizLicenseOCRRequest();
            req.setImageUrl(imageUrl);
            BizLicenseOCRResponse resp = client.BizLicenseOCR(req);
            String business = resp.getBusiness();
            return business;
        } catch (TencentCloudSDKException e) {
            log.info("营业执照OCR请求发生异常！异常信息是：{}",e.toString());
        }
        return null;
    }


    /**
     * 文档抽取(基础版)
     * @param imageUrl
     * @return
     */
    public static String ExtractDocBasic(String imageUrl){
        try {
            Credential cred = new Credential("AKIDviPyMZbRp24udCcpqjQxHOK4cx88ze6N", "97tVwEJE81sY0StDPPGukQ2ZvkU3QceY");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            CommonClient client = new CommonClient("ocr", "2018-11-19", cred, "", clientProfile);
            String params = "{\"ImageUrl\":\"" + imageUrl + "\"}";
            String resp = client.call("ExtractDocBasic", params);
            log.info("文档抽取成功!结果：{}", resp);
            String ocrStr = extractBusinessScope(resp);
            return ocrStr;
        } catch (TencentCloudSDKException e) {
            log.info("文档抽取失败：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 药品经营许可证识别(有概率识别不准)
     * @param imageUrl
     * @return
     */
    public static String enterpriseLicenseOCR(String imageUrl){
        try{
            Credential cred = new Credential("AKIDviPyMZbRp24udCcpqjQxHOK4cx88ze6N", "97tVwEJE81sY0StDPPGukQ2ZvkU3QceY");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            OcrClient client = new OcrClient(cred, "", clientProfile);
            EnterpriseLicenseOCRRequest req = new EnterpriseLicenseOCRRequest();
            req.setImageUrl(imageUrl);
            EnterpriseLicenseOCRResponse resp = client.EnterpriseLicenseOCR(req);
            Optional<EnterpriseLicenseInfo> jyfw = Arrays.stream(resp.getEnterpriseLicenseInfos())
                    .filter(enterpriseLicenseInfo -> enterpriseLicenseInfo.getName().equals("经营范围")).findAny();
            if(!jyfw.isPresent()){
                return null;
            }
            AtomicReference<String> value = new AtomicReference<>();
                    Arrays.stream(resp.getEnterpriseLicenseInfos()).forEach(enterpriseLicenseInfo -> {
                String name = enterpriseLicenseInfo.getName();
                if(name.equals("经营范围")){
                    value.set(enterpriseLicenseInfo.getValue());
                }
            });
            log.info("许可证书OCR请求识别成功！结果是：{}",AbstractModel.toJsonString(resp));
            return value.get();
        } catch (TencentCloudSDKException e) {
            log.info("证书识别失败！异常信息是：{}",e.toString());
        }
        return null;
    }

    /**
     * BizLicenseOCR
     * 本接口支持快速精准识别营业执照上的字段，包括统一社会信用代码、公司名称、主体类型、法定代表人、注册资本、组成形式、成立日期、营业期限和经营范围等字段。
     * 默认接口请求频率限制：10次/秒。
     * @param imageUrl 图片url
     * @param keywords 需要对比的关键字
     * @return ContainsResult
     */
    public static ContainsResult isContains(String imageUrl, String keywords) {
        ContainsResult result = new ContainsResult();
        result.setFlag(false);
        result.setImageUrl(imageUrl);
        result.setMessage("识别失败请重试！");
        try{
            Credential cred = new Credential("AKIDviPyMZbRp24udCcpqjQxHOK4cx88ze6N", "97tVwEJE81sY0StDPPGukQ2ZvkU3QceY");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            OcrClient client = new OcrClient(cred, "", clientProfile);
            BizLicenseOCRRequest req = new BizLicenseOCRRequest();
            req.setImageUrl(imageUrl);
            BizLicenseOCRResponse resp = client.BizLicenseOCR(req);
            log.info("营业执照OCR请求识别成功！结果是：{}",AbstractModel.toJsonString(resp));
            String business = resp.getBusiness();
            if(StringUtils.isEmpty(keywords) && StringUtils.isNotEmpty(business)){
                result.setBusinessStr(business);
                result.setKeywords(YPLS);
                result.setFlag(business.contains(YPLS));
                result.setMessage(result.getFlag()?"包含":"不包含");
                result.setPerson(resp.getPerson());
                result.setRegNum(resp.getRegNum());
                result.setAddress(resp.getAddress());
                result.setPeriod(resp.getPeriod());
                result.setSetDate(resp.getSetDate());
                return result;
            }
            if(StringUtils.isNotEmpty(keywords) && StringUtils.isNotEmpty(business)){
                result.setKeywords(keywords);
                result.setBusinessStr(business);
                result.setFlag(business.contains(keywords));
                result.setMessage(result.getFlag()?"包含":"不包含");
                result.setPerson(resp.getPerson());
                result.setRegNum(resp.getRegNum());
                result.setAddress(resp.getAddress());
                result.setPeriod(resp.getPeriod());
                result.setSetDate(resp.getSetDate());
                return result;
            }
        } catch (TencentCloudSDKException e) {
            log.error("营业执照OCR请求发生异常！异常信息是：{}",e.toString());
            result.setFlag(false);
            result.setMessage(e.getMessage());
            return result;
        }
        return result;
    }

    /**
     * EnterpriseLicenseOCR
     * 本接口支持智能化识别各类企业登记证书、许可证书、企业执照、三证合一类证书，结构化输出统一社会信用代码、公司名称、法定代表人、公司地址、注册资金、企业类型、经营范围、成立日期、有效期、开办资金、经费来源、举办单位等关键字段。
     * 默认接口请求频率限制：5次/秒。
     * @param imageUrl
     * @return EnterpriseLicenseOCRResponse
     */
    public static ContainsResult enterpriseLicenseOCR(String imageUrl, String cateName) {
        ContainsResult result = new ContainsResult();
        result.setFlag(false);
        result.setImageUrl(imageUrl);
        result.setKeywords(cateName);
        result.setMessage("许可证书经营范围不包含，请更换！");
        try{
            Credential cred = new Credential("AKIDviPyMZbRp24udCcpqjQxHOK4cx88ze6N", "97tVwEJE81sY0StDPPGukQ2ZvkU3QceY");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            OcrClient client = new OcrClient(cred, "", clientProfile);
            EnterpriseLicenseOCRRequest req = new EnterpriseLicenseOCRRequest();
            req.setImageUrl(imageUrl);
            EnterpriseLicenseOCRResponse resp = client.EnterpriseLicenseOCR(req);
            Arrays.stream(resp.getEnterpriseLicenseInfos()).forEach(enterpriseLicenseInfo -> {
                String name = enterpriseLicenseInfo.getName();
                if(name.equals("经营范围")){
                    String value = enterpriseLicenseInfo.getValue();
                    boolean contains = value.contains(cateName);
                    result.setBusinessStr(value);
                    result.setFlag(contains);
                    result.setMessage(contains?"包含":"当前店铺经营类别不包含"+cateName);
                }
            });
            log.info("许可证书OCR请求识别成功！结果是：{}",AbstractModel.toJsonString(resp));
            return result;
        } catch (TencentCloudSDKException e) {
            log.error("证书识别失败！异常信息是：{}",e.toString());
            result.setFlag(false);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    /**
     * 从OCR结果中提取经营范围字符串
     * @param jsonResponse OCR返回的JSON字符串
     * @return 经营范围内容
     */
    public static String extractBusinessScope(String jsonResponse) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(jsonResponse);
            JsonNode structuralList = rootNode.path("Response").path("StructuralList");

            // 遍历所有结构化文本块
            for (JsonNode block : structuralList) {
                JsonNode groups = block.path("Groups");
                for (JsonNode group : groups) {
                    JsonNode lines = group.path("Lines");
                    for (JsonNode line : lines) {
                        JsonNode key = line.path("Key");
                        String keyName = key.path("AutoName").asText();

                        // 查找"经营范围"相关的键
                        if ("经营范围".equals(keyName)) {
                            JsonNode value = line.path("Value");
                            return value.path("AutoContent").asText();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
//        ExtractDocBasic("https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/fs/20251118/d175ed9771324c56a126779ef89bb1e3.jpg");
        IdCardVerification("郭顺", "111");
    }




    /**
     * ClassifyDetectOCR
     * 支持身份证、护照、名片、银行卡、行驶证、驾驶证、港澳台通行证、户口本、港澳台来往内地通行证、港澳台居住证、不动产证、营业执照的智能分类。
     *  默认接口请求频率限制：20次/秒。
     * @param imageUrl ClassifyDetectOCRRequest
     * @return ClassifyDetectOCRResponse
     * @throws TencentCloudSDKException
     */
//    public static ClassifyDetectOCRResponse classifyDetectOCR(String imageUrl){
//        try{
//            Credential cred = new Credential("AKIDviPyMZbRp24udCcpqjQxHOK4cx88ze6N", "97tVwEJE81sY0StDPPGukQ2ZvkU3QceY");
//            HttpProfile httpProfile = new HttpProfile();
//            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
//            ClientProfile clientProfile = new ClientProfile();
//            clientProfile.setHttpProfile(httpProfile);
//            OcrClient client = new OcrClient(cred, "", clientProfile);
//            IDCardOCRRequest req = new IDCardOCRRequest();
//            req.setImageUrl(imageUrl);
//            IDCardOCRResponse resp = client.IDCardOCR(req);
//            System.out.println(AbstractModel.toJsonString(resp));
//        } catch (TencentCloudSDKException e) {
//            System.out.println(e.toString());
//        }
//        return null;
//    }

//    public static void main(String [] args) {
//        ContainsResult contains = enterpriseLicenseOCR("https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/fs/20251119/c97e794b896f4066878913821a1e3287.jpg", "乙类非处方");
//        System.out.println(contains.toString());
//    }


}
