package com.mushiny.wms.slam;

import com.mushiny.wms.application.domain.MushinyMessage;
import com.mushiny.wms.application.domain.WmsSlamTrip;
import com.mushiny.wms.common.utils.DateTimeUtil;
import com.mushiny.wms.common.utils.JSONUtil;
import org.apache.http.client.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.AsyncRestOperations;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/slamTest")
public class SlamTestController {

    /*mushiny.midea.slam.url: http://localhost:12008/api/wms/sync/mes
      mushinymidea.slam.mes.callBack: http://localhost:8888/slam/api*/
    private static final Logger logger = LoggerFactory.getLogger(SlamTestController.class);

    @Value("${mushiny.midea.slam.appSecret}")
    private String appSecret;

    @Value("${mushiny.midea.slam.url}")
    private String mideaUrl;

    private final SlamTestService slamTestService;

    private final RestTemplateBuilder builder;

    public SlamTestController(SlamTestService slamTestService, RestTemplate restTemplate, RestTemplateBuilder builder) {
        this.slamTestService = slamTestService;
        this.builder = builder;
    }

    //mushiny.midea.slam.mes.callBack
    @PostMapping(value = "/mesCallBack", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<MushinyMessage> mesCallBack(@RequestBody String callBack) {
        Map reqData = JSONUtil.jsonToMap(callBack);
        logger.debug("mesCallBack: " + reqData);
        MushinyMessage res = new MushinyMessage();
        /*Map data = new HashMap();
        data.put("state", WmsSlamTrip.PROCESS);
        data.put("taskDateTime", DateTimeUtil.getNowFormat());
        data.put("carNo", "1");
        res.setData(data);*/
        res.setCode("0");
        res.setCode("ok");

        return ResponseEntity.ok(res);
    }


    @PostMapping(value = "/agvTaskAssign", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<MushinyMessage> agvTaskConfirm(@RequestBody String taskConfirm) {
        Map reqData = JSONUtil.jsonToMap(taskConfirm);
        logger.debug("SlamTestController_agvTaskAssign reqData:" + reqData);
            /*String state = (String) data.get("state");
        Integer iState = Integer.parseInt(state);
        String taskDateTime = (String) data.get("taskDateTime");
        wmsSlamTrip.setTripState(iState);
        wmsSlamTrip.setCarNo((String) data.get("carNo"));*/


        MushinyMessage res = new MushinyMessage();
        Map data = new HashMap();
        data.put("state", WmsSlamTrip.PROCESS);
        data.put("taskDateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        data.put("carNo", "1");
        res.setData(data);
        res.setCode("0");
        res.setCode("ok");

        /*this.slamTestService.setFlag(true);
        this.slamTestService.setParam(reqData);
        this.slamTestService.setState(WmsSlamTrip.PROCESS);*/

        return ResponseEntity.ok(res);
    }


    public static final String AGV_TASK_CONFIRM = "http://localhost:12003/slam/agvTaskConfirm";
    public static final String AGV_TASK_FINISH = "http://localhost:12003/slam/agvTaskFinish";

    @GetMapping(path = "/agvRespone")
    public String response(HttpServletRequest request, HttpServletResponse response) {
        String state = request.getParameter("state");
        Map params = new HashMap();
        params.put("taskId", request.getParameter("taskId"));
        params.put("areaCode","NANSHA");
        params.put("warehouseCode","NANSHA");
        params.put("taskType","0");
        params.put("startTag","");
        params.put("endTag", "");
        params.put("storageNo","");
        params.put("priority",99);
        params.put("carNo","1");
        params.put("state",Integer.parseInt(state));
        params.put("taskDateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        RestTemplate restTemplate = this.builder.build();

        try {
            logger.debug("params:" + params);
            //res = restTemplate.getForObject(this.rfidUrl_podOut,String.class, podId,moInfo,addrCode);
            HttpHeaders headers = new HttpHeaders();
            MediaType type2 = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type2);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> httpEntity = new HttpEntity<String>(JSONUtil.mapToJSon(params), headers);
            String res = restTemplate.postForEntity(AGV_TASK_CONFIRM, httpEntity, String.class).getBody();
            return res;
        } catch (RestClientException e) {
            return "fail: " + e.getMessage();
        }
    }

    @GetMapping(path = "/agvFinish")
    public String agvFinish(HttpServletRequest request, HttpServletResponse response) {
        //String state = request.getParameter("state");
        Map params = new HashMap();
        params.put("tagName", request.getParameter("tagName"));
        params.put("mesId", request.getParameter("mesId"));


        RestTemplate restTemplate = this.builder.build();

        try {
            logger.debug("params:" + params);
            //res = restTemplate.getForObject(this.rfidUrl_podOut,String.class, podId,moInfo,addrCode);
            HttpHeaders headers = new HttpHeaders();
            MediaType type2 = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type2);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> httpEntity = new HttpEntity<String>(JSONUtil.mapToJSon(params), headers);
            String res = restTemplate.postForEntity(AGV_TASK_FINISH, httpEntity, String.class).getBody();
            return res;
        } catch (RestClientException e) {
            return "fail: " + e.getMessage();
        }
    }

    @GetMapping(path = "/agvStart")
    public String agvStart(HttpServletRequest request, HttpServletResponse response) {
        //String state = request.getParameter("state");
        Map params = new HashMap();
        //String id = CommonUtils.genUUID();
        params.put("taskId", CommonUtils.genUUID());
        params.put("areaCode","NANSHA");
        params.put("warehouseCode","NANSHA");
        params.put("taskType",0);
        params.put("startTag",request.getParameter("startTag"));
        //String instrutId = CommonUtils.parseString(MideaConstants.INSTRUCT,data);
        //String targetTag = this.getEndTag(instrutId);
        params.put("endTag", request.getParameter("startTag"));
        params.put("storageNo","0066f6c6-34a5-466c-a79f-9bbbc7320829");
        params.put("priority",99);
        params.put("taskDateTime", DateUtils.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss zzz"));

        String sign = this.exportSign(params);

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("sign",sign);
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> httpEntity = new HttpEntity<String>(JSONUtil.mapToJSon(params), headers);
            RestTemplate restTemplate = this.builder.build();
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(this.mideaUrl, httpEntity, String.class);
            logger.info("Slam服务器返回数据是:"+responseEntity.getBody());
            return responseEntity.getBody();
        } catch (Exception e) {
            logger.error("发送到激光AGV出错!", e);
        }

        return "发送出错 params:"+params;
    }

    private String exportSign(Map params) {
        logger.info("输入参数:"+params);
        List keys = new ArrayList();
        keys.addAll(params.keySet());
        Collections.sort(keys);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(this.appSecret);
        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);
            stringBuilder.append(key).append(CommonUtils.parseString(key,params));
        }
        stringBuilder.append(this.appSecret);

        logger.debug("拼接后的字符串是:"+stringBuilder);
        String md5Str = CommonUtils.md5(stringBuilder.toString());
        logger.debug("MD5的字符串是:"+stringBuilder);
        return md5Str;
    }

}
