package com.fastbee.data.controller.anfang.controller;

import com.alibaba.fastjson.JSON;
import com.fastbee.common.model.bto.WebhookMessage;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/yinghsiyun")
@Api(tags = "萤石云信息推送")
public class YingshiMsgRecController {

    @RequestMapping(value = "/webhook")
    public ResponseEntity<String> webhook(@RequestHeader HttpHeaders header, @RequestBody String body) {
        final List<String> t = header.get("t");
        WebhookMessage receiveMessage = null;
        log.info("消息获取时间:{}, 请求头:{},请求体:{}",System.currentTimeMillis(), JSON.toJSONString(header),body);
        System.out.println("收到的消息:"+body);
        try {
            receiveMessage = JSON.parseObject(body, WebhookMessage.class);
            //todo:对收到的消息进行处理,最好发送到其他中间件,或者写到数据库中,不要影响回调地址的处理

        } catch (Exception e) {
            e.printStackTrace();
        }
        //必须进行返回
        Map<String, String> result = new HashMap<>(1);
        assert receiveMessage != null;
        String messageId = receiveMessage.getHeader().getMessageId();
        result.put("messageId", messageId);
        final ResponseEntity<String> resp = ResponseEntity.ok(JSON.toJSONString(result));
        log.info("返回的信息:{}",JSON.toJSONString(result));
        return resp;
    }

}
