package com.search.supersearch.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.search.supersearch.common.R;
import com.search.supersearch.model.OcrResult;
import com.search.supersearch.util.FileUtil;
import com.search.supersearch.util.HttpUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 喜欢番茄火锅
 * @date 2023/10/19 14:33
 */
@Service
@Slf4j
public class OcrService {

    private static String token = null;
    @Value("${ocr.serverUrl}")
    private String serverUrl;
    @Value("${ocr.tokenUrl}")
    private String tokenUrl;
    @Value("${ocr.ocrUrl}")
    private String ocrUrl;

    /**
     * @param file   解析文件
     * @param format 文件后缀
     * @return {@link R<?>}
     * @author 王瑞
     * @date 2023/10/19
     */
    @SneakyThrows
    public String ocr(File file, String format) {
        if (token == null) {
            log.info("token为空");
            token = getToken();
        }
        log.info("方法名:ocr,参数accessToken:{},参数filePath:{}", token, file);
        Map<String, String> parameters = new HashMap<>();
        parameters.put("format", format);
        Map<String, File> files = new HashMap<>();
        files.put("file", file);
        log.info("识别接口参数,ocrUrl:{},parameters:{},files:{},accessToken:{}", ocrUrl, parameters, files, token);
        String result = HttpUtils.post(ocrUrl, parameters, files, token);
        log.info("识别接口返回值,{}", result);
        if (result.contains("身份认证信息未提供")) {
            log.info("token已过期");
            result = HttpUtils.post(ocrUrl, parameters, files, getToken());
        }
        StringBuilder sb = new StringBuilder();
//        OcrResult ocrResult = JSONUtil.toBean(result, OcrResult.class);
//        OcrResult.OcrResultData ocrResultData = JSONUtil.toBean(ocrResult.getData(), OcrResult.OcrResultData.class);
        OcrResult.OcrResultData ocrResultData = JSONUtil.toBean(result, OcrResult.OcrResultData.class);
        List<OcrResult.OcrResultDataResult> ocrResultDataResults = JSONUtil.toList(ocrResultData.getResult(), OcrResult.OcrResultDataResult.class);
        for (OcrResult.OcrResultDataResult ocrResultDataResult : ocrResultDataResults) {
            List<OcrResult.OcrResultDataResultData> ocrResultDataResultData = JSONUtil.toList(ocrResultDataResult.getData(), OcrResult.OcrResultDataResultData.class);
            for (OcrResult.OcrResultDataResultData ocrResultDataResultDatum : ocrResultDataResultData) {
                sb.append(ocrResultDataResultDatum.getText());
            }

        }
        return sb.toString();
    }

    /**
     * @param file   解析文件
     * @param format 文件后缀
     * @return {@link R<?>}
     * @author 王瑞
     * @date 2023/10/19
     */
    @SneakyThrows
    public List<String> ocr(MultipartFile multipartFile, String format) {
        File file = FileUtil.MultipartFileToFile(multipartFile);

        if (token == null) {
            log.info("token为空");
            token = getToken();
        }
        log.info("方法名:ocr,参数accessToken:{},参数filePath:{}", token, file);
        Map<String, String> parameters = new HashMap<>();
        parameters.put("format", format);
        Map<String, File> files = new HashMap<>();
        files.put("file", file);
        log.info("识别接口参数,ocrUrl:{},parameters:{},files:{},accessToken:{}", ocrUrl, parameters, files, token);
        String result = HttpUtils.post(ocrUrl, parameters, files, token);
        log.info("识别接口返回值,{}", result);
        if (result.contains("身份认证信息未提供")) {
            log.info("token已过期");
            result = HttpUtils.post(ocrUrl, parameters, files, getToken());
        }
        List<String> list = new ArrayList<>();
//        OcrResult ocrResult = JSONUtil.toBean(result, OcrResult.class);
//        OcrResult.OcrResultData ocrResultData = JSONUtil.toBean(ocrResult.getData(), OcrResult.OcrResultData.class);
        OcrResult.OcrResultData ocrResultData = JSONUtil.toBean(result, OcrResult.OcrResultData.class);
        List<OcrResult.OcrResultDataResult> ocrResultDataResults = JSONUtil.toList(ocrResultData.getResult(), OcrResult.OcrResultDataResult.class);
        for (OcrResult.OcrResultDataResult ocrResultDataResult : ocrResultDataResults) {
            List<OcrResult.OcrResultDataResultData> ocrResultDataResultData = JSONUtil.toList(ocrResultDataResult.getData(), OcrResult.OcrResultDataResultData.class);
            for (OcrResult.OcrResultDataResultData ocrResultDataResultDatum : ocrResultDataResultData) {
                list.add(ocrResultDataResultDatum.getText());
            }

        }
        return list;
    }

    @SneakyThrows
    public String getToken() {

        Map<String, Object> toeknParameters = new HashMap<>();
        toeknParameters.put("client_id", "UZ81v8EYVWSckt787x0eQvIyTXVVGx4RHKVQ5riZ");
        toeknParameters.put("client_secret", "cZXylKpqgLoVHFSIeKZWJlTMBixQDN6n2HPvpeX2VFLPZqkt66PnSFtmA3Ad7OKi3ZIuY1rFjmFVd9DPYqj3WKiHcEQhcCNfrNllaUMPMnHTlN7qyiln2f15lepzRW31");
        toeknParameters.put("grant_type", "client_credentials");
        toeknParameters.put("scope", "review");

        String post = HttpUtil.post(tokenUrl, toeknParameters);
        log.info("获取 token接口返回值,{}", post);
        JSONObject entries = JSONUtil.parseObj(post);
        String accessToken = (String) entries.get("access_token");
        token = accessToken;
        return accessToken;
    }
}
