package com.ruoyi.web.work.api.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.web.work.domain.User;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class AppUtil {
    public static User getUser() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        return (User) request.getAttribute("user");
    }
    /**
     * 身份证OCR文字识别
     *
     * @param imgUrl
     * @param side
     * @return
     */
    public static JSONObject idCard(String imgUrl, String side) {
        String host = "https://cardnumber.market.alicloudapi.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "9f9f3a419d0e4e0bbe1bed74813328e2";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> query = new HashMap<String, String>();
        //configure配置
        JSONObject configObj = new JSONObject();
        configObj.put("side", side);
        String config_str = configObj.toString();
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgUrl);
        if (configObj.size() > 0) {
            requestObj.put("configure", config_str);
        }
        String body = requestObj.toString();
        try {
            HttpResponse response = HttpUtils.doPost(host, path, "POST", headers, query, body);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                System.out.println("Http code: " + stat);
                System.out.println("http header error msg: " + response.getFirstHeader("X-Ca-Error-Message"));
                System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                throw new ServiceException("身份证识别失败");
            }
            String res = EntityUtils.toString(response.getEntity());
            System.out.println("身份证识别成功");
            return JSON.parseObject(res);
        } catch (Exception e) {
            System.out.println("身份证识别失败");
            throw new ServiceException(e.getMessage());
        }
    }
}
