package cn.timer.api.utils.resumesdk;

import cn.timer.api.dto.resumesdk.ResumeSdkDto;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wuqingjun
 * @email 284718418@qq.com
 * @date 2022/4/22
 */
@Component
public class ResumeSDKUtil {

    public String getResumeByCvParser(ResumeSdkDto resumeSdkDto, String appCode) throws Exception {
        String url = "http://resumesdk.market.alicloudapi.com/ResumeParser";
        // 设置头字段
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Authorization", "APPCODE " + appCode);
        httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
        httpPost.addHeader("Content-Type", "application/json");


        // 设置内容信息
        JSONObject json = new JSONObject();
        json.put("file_name", resumeSdkDto.getFile_name());	// 文件名
        json.put("file_cont", resumeSdkDto.getFile_cont());	// 经base64编码过的文件内容
        json.put("need_avatar", 0);		// 是否需要解析头像
        json.put("ocr_type", 1);		// 1为高级ocr
        StringEntity params = new StringEntity(json.toString(), Consts.UTF_8);
        httpPost.setEntity(params);

        // 发送请求
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httpPost);

        // 处理返回结果
        return unicodeToCN(EntityUtils.toString(response.getEntity(), Consts.UTF_8));
    }
    /**
     * Unicode转 汉字字符串
     *
     * @param str
     * @return
     */
    private static String unicodeToCN(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }

}