package com.casic.missiles.controller;

import com.alibaba.fastjson.JSON;
import com.casic.missiles.core.base.controller.BaseController;
import com.casic.missiles.core.base.response.ResponseData;
import com.casic.missiles.core.util.ToolUtil;
import com.casic.missiles.invoke.app.request.ParamsCasicBean;
import com.casic.missiles.invoke.config.InvokeConfigProperties;
import com.casic.missiles.invoke.util.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

/**
 * app调用前置开发
 */
@Controller
@RequestMapping("/app")
public class CommonSyncController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CommonSyncController.class);
    @Value("${server.port}")
    private String port;

    @Autowired
    private InvokeConfigProperties invokeConfigProperties;

    /**
     * 公安总线前置调用
     */
    @PostMapping(value = "/prepositionInvoke")
    @ResponseBody
    public Object prepositionInvoke(HttpServletRequest request, @RequestBody ParamsCasicBean requestBaseBean) {
        try {


            /***这里是业务逻辑处理***/
            logger.info(JSON.toJSONString(requestBaseBean));
            Map<String, String> map = requestBaseBean.getParams();
            String json = null;
            String localhostIp = invokeConfigProperties.getLocalhostIp() + ":" + port + "/";

            if (RequestMethod.POST.name().equals(requestBaseBean.getType())) {

                json = HttpUtils.sendPost(localhostIp + requestBaseBean.getMethodName(), map, requestBaseBean.getToken());
            } else {
                json = HttpUtils.sendGet(localhostIp + requestBaseBean.getMethodName(), map, requestBaseBean.getToken());
            }
            if (ToolUtil.isEmpty(json)) {
                return getResult(ResponseData.error("请求失败"));
            }
            return getResult(JSON.parse(json));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return getResult(ResponseData.error("请求失败"));
    }

    private Object getResult(Object jsonObj) {
        return jsonObj;
    }
}
