package com.union.ai.api.controller.body;

import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.util.Base64Util;
import com.google.protobuf.ByteString;
import com.union.ai.api.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * Author: xingxin.jing
 * Date: 2019/3/30
 * Time: 下午1:48
 */
@Slf4j
@RestController
@RequestMapping(value = "/rest/2.0/image-classify/v1", method = RequestMethod.POST)
public class BodyController {

    /**
     * 人体关键点识别
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "body_analysis")
    public String bodyAnalysis(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, String> param = getParam(request);
        String url = Config.getInstance().getBodyAnalysisUrl();
        return HttpClientUtil.sendPostJSON(url, convertParam(param));

    }

    /**
     * 人体检测和属性识别
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "body_attr")
    public String bodyAttr(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, String> param = getParam(request);
        String url = Config.getInstance().getBodyAttrUrl();
        return HttpClientUtil.sendPostJSON(url, convertParam(param));

    }

    /**
     * 人流量统计
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "body_num")
    public String bodyNum(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, String> param = getParam(request);
        String url = Config.getInstance().getBodyNumUrl();
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(param));
        if (param.get("show") != null) {
            jsonObject.put("show", jsonObject.getInteger("show"));
        }
        return HttpClientUtil.sendPostJSON(url, convertParam(jsonObject));

    }

    /**
     * 手势识别
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "gesture")
    public String bodyGesture(HttpServletRequest request, HttpServletResponse response) throws Exception
    {

        log.error("bodyGesture- request-image: "+request.getParameter("image"));

        String url = Config.getInstance().getBodyGestureUrl();
        String params = getGestureParam(request);
//        log.error("bodyGesture- request: "+params);
        return HttpClientUtil.sendPostJSON(url, params);

    }

    private String getGestureParam(HttpServletRequest request) throws UnsupportedEncodingException
    {
        Map<String, String[]> parameterMap = request.getParameterMap();
        JSONObject object = new JSONObject();
        if (!CollectionUtils.isEmpty(parameterMap))
        {
            ProtoData.GesureParams.Builder builder = ProtoData.GesureParams.newBuilder();
            for (String key : parameterMap.keySet())
            {
                String[] values = parameterMap.get(key);
                if (key.equals("access_token") || CheckUtil.isNull(values))
                {
                    continue;
                }
                String value = values[0];
                if ("image".equals(key))
                {
                    try
                    {
//                        log.error("bodyGesture- getGestureParam: "+value);
                        value = URLDecoder.decode(value, "UTF-8");
                        byte[] decode = Base64Util.decode(value);
                        builder.setImgFormat("RGB");
                        builder.setImage(ByteString.copyFrom(decode));
                    }
                    catch (UnsupportedEncodingException e)
                    {
                        log.error("bodyGesture- getGestureParam-解码失败,value=" + value, e);
                        throw e;
                    }
                }
                if ("width".equals(key)){
                    builder.setWidth(Integer.valueOf(value));
                }
                if ("height".equals(key)) {
                    builder.setHeight(Integer.valueOf(value));
                }
                if ("left".equals(key)) {
                    builder.setLeft(Integer.valueOf(value));
                }
                if ("top".equals(key)) {
                    builder.setTop(Integer.valueOf(value));
                }
                if ("right".equals(key)) {
                    builder.setRight(Integer.valueOf(value));
                }
                if ("bottom".equals(key)) {
                    builder.setBottom(Integer.valueOf(value));
                }
            }
            ProtoData.GesureParams gesureParams = builder.build();
            String objBase64 = Base64Util.encode(gesureParams.toByteArray());
            object.put("data",objBase64);
        }
        return object.toJSONString();
    }


    private Map<String, String> getParam(HttpServletRequest request) throws IOException
    {
        Map<String, String[]> parameterMap = request.getParameterMap();

        BufferedReader reader = request.getReader();
        String line;
        StringBuilder jb = new StringBuilder();
        while ((line = reader.readLine()) != null)
        {
            jb.append(line);
        }
        String jbstring=jb.toString();

        Map<String, String> param = new HashMap<>();
        if (!CollectionUtils.isEmpty(parameterMap))
        {
            for (String key : parameterMap.keySet())
            {
                String[] values = parameterMap.get(key);
                if (key.equals("access_token") || CheckUtil.isNull(values))
                {
                    continue;
                }
                String value = values[0];
                if ("image".equals(key))
                {
                    try
                    {
                        value = value.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                        value = value.replaceAll("\\+", "%2B");
                        value = URLDecoder.decode(value, "UTF-8");
                    }
                    catch (UnsupportedEncodingException e)
                    {
                        log.error("解码失败,value=" + value, e);
                        throw e;
                    }
                }
                param.put(key, value);
            }
        }
        return param;
    }


    private String convertParam(Map param) throws UnsupportedEncodingException {
        String json = GsonUtils.toJson(param);
        String encode = Base64Util.encode(json.getBytes("UTF-8"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", encode);
        return jsonObject.toJSONString();
    }
}
