package com.mortals.xhx.daemon;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.util.DateUtils;
import com.mortals.xhx.base.system.message.MessageService;
import com.mortals.xhx.busiz.req.UploadDeviceReq;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.common.code.OneThingRespCodeEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.model.DefaultTbQueueMsgHeaders;
import com.mortals.xhx.common.model.MessageHeader;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.module.platform.model.PlatformEntity;
import com.mortals.xhx.module.platform.service.PlatformService;
import com.mortals.xhx.module.product.model.ProductEntity;
import com.mortals.xhx.module.product.service.ProductService;
import com.mortals.xhx.queue.TbQueueMsg;
import com.mortals.xhx.queue.TbQueueMsgHeaders;
import com.mortals.xhx.queue.TbQueueProducer;
import com.mortals.xhx.queue.TopicPartitionInfo;
import com.mortals.xhx.queue.provider.TbCoreQueueProducerProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 一件事微信对外服务接口
 *
 * @author: zxfei
 * @date: 2021/8/24 20:28
 */
@CrossOrigin(origins = "*")
@RestController
@Slf4j
@RequestMapping("/test/")
public class DemoApiController {

    @Autowired
    private TbCoreQueueProducerProvider producerProvider;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ProductService productService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private MessageService messageService;

    @PostMapping("/sentry")
    public String sentry(@RequestBody String body) {
        log.info("body==>{}",body);

        return "success";
    }

    @PostMapping("/getToken")
    public String getToken() {
       return messageService.getBasePlatformToken();
    }


    @PostMapping("/siteTree")
    public String siteTree() {
        return messageService.siteTree();
    }


    @GetMapping("/exception")
    public String exception() {
        throw new RuntimeException("直接抛出异常");
    }

    @GetMapping("/appexception")
    public String appexception() {
        throw new AppException("自定义异常");
    }

    /**
     * 发送消息
     *
     * @return
     */
    @PostMapping("produceMsg")
    public String produceMsg() {
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(OneThingRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(OneThingRespCodeEnum.SUCCESS.getValue());
        try {
            TbQueueProducer<TbQueueMsg> producer = producerProvider.getTbCoreMsgProducer();

            TopicPartitionInfo info = TopicPartitionInfo.builder().topic("demoTopic").build();
            TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
            header.put(MessageHeader.CLIENTID, "aaa");


            Map<String, Object> headers = new HashMap<>();
            headers.put(MessageHeader.TIMESTAMP, DateUtils.getCurrStrDateTime().getBytes());
            String payLoad = "12313";

//            TbQueueMsg queueMsg = new DefaultTbQueueMsg(UUID.randomUUID().toString(), payLoad.getBytes(), header);
//
//
//            for (int i = 0; i < 10; i++) {
//                producer.send(info, queueMsg, new TbQueueCallback() {
//                    @Override
//                    public void onSuccess(TbQueueMsgMetadata metadata) {
//                        // logger.info("消息发送成功");
//                    }
//
//                    @Override
//                    public void onFailure(Throwable t) {
//
//                    }
//                });
//            }

        } catch (Exception e) {
            log.error("消息提交失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }

        log.info("响应【消息发送】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return JSON.toJSONString(rsp);
    }


    /**
     * 设备数据上报
     *
     * @param
     * @return
     */
    @PostMapping("upload")
    public String upload(@RequestParam(value = "deviceId") Long deviceId ) {
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            //根据设备编码查询设备
            DeviceEntity deviceEntity = deviceService.get(deviceId);
            if (!ObjectUtils.isEmpty(deviceEntity)) {
                //将上报信息转发到mq中

                PlatformEntity platformEntity = platformService.get(deviceEntity.getPlatformId());
                if (ObjectUtils.isEmpty(platformEntity)) {
                    throw new AppException("当前设备未配置所属系统平台，请在后台配置后再激活！");
                }
                // authInfo.setHost(platformEntity.getPlatformSn());
                ProductEntity productEntity = productService.get(deviceEntity.getProductId());
                if (ObjectUtils.isEmpty(productEntity)) {
                    throw new AppException("当前设备未配置所属产品，请在后台配置后再激活！");
                }
                String exchangeName = platformEntity.getPlatformSn() + Constant.EXCHANGE_SPLIT + productEntity.getProductCode();

                TopicPartitionInfo info = TopicPartitionInfo.builder().exchangeName(exchangeName).topic(Constant.UPLOAD_TOPIC + deviceEntity.getDeviceMac()).build();
                TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
                header.put(MessageHeader.MESSAGETYPE, Constant.MESSAGETYPE_HEARTBEAT);
                UploadDeviceReq uploadDeviceReq = new UploadDeviceReq();
                //uploadDeviceReq.setDeviceMac(deviceEntity.getDeviceMac());
                uploadDeviceReq.setDeviceCode(deviceEntity.getDeviceCode());

                for (int i = 0; i < 100; i++) {
                    deviceService.sendDeviceMessage(deviceEntity, info, header, JSON.toJSONString(deviceEntity), null,null);
                }

            }
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }

        log.debug("响应【设备数据上报】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return JSON.toJSONString(rsp);
    }

}
