package web.VehicleRelated;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.api.gateway.demo.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

@WebServlet(urlPatterns = "/main/recoPlate")
public class RecoPlateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从请求中获取图像数据
        String imageData = request.getParameter("image");
        JSONObject res  = apiRequest(imageData);
        boolean success = res.getBoolean("success");
        String txt = res.getJSONArray("plates").getJSONObject(0).getString("txt");
        if(success && txt.length() == 7) {

            response.setContentType("text/plain; charset=UTF-8");
            PrintWriter out = response.getWriter();
            String urlToSendBack = request.getContextPath() + "/main/admin/adminUpdateRecord?plate=" + txt; // 构造返回的URL
            out.print(urlToSendBack); // 写入URL到响应体
            out.flush(); // 清空输出流，完成响应
        }
    }

    public static JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONObject apiRequest(String imgBase64){

        String host = "https://ocrcp.market.alicloudapi.com";//
        String path = "/rest/160601/ocr/ocr_vehicle_plate.json";
        String appcode = "9a887597dbf04dc1a2f26ceee6227f5a";
//        String imgFile = "/ParkingLotManagementSystem/static/images/vehicle_plate.png";
        Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("multi_crop", true);
        String config_str = configObj.toString();
        //            configObj.put("min_size", 5);
        //String config_str = "";

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();

        // 对图像进行base64编码
//        String imgBase64 = "";
//        try {
//            File file = new File(imgFile);
//            byte[] content = new byte[(int) file.length()];
//            FileInputStream finputstream = new FileInputStream(file);
//            finputstream.read(content);
//            finputstream.close();
//            imgBase64 = new String(encodeBase64(content));
//        } catch (IOException e) {
//            e.printStackTrace();
//            return;
//        }
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if(is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", getParam(50, imgBase64));
                if(config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            }else{
                requestObj.put("image", imgBase64);
                if(config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();
        JSONObject res_obj = new JSONObject();
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            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()));
                return null;
            }

            String res = EntityUtils.toString(response.getEntity());
            res_obj = JSON.parseObject(res);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return res_obj;
    }
}
