package com.mortals.xhx.busiz.web;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.util.DateUtils;
import com.mortals.xhx.base.system.message.impl.MessageProducer;
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.LogTypeEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.key.QueueKey;
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.model.DeviceLogEntity;
import com.mortals.xhx.module.device.model.DeviceQuery;
import com.mortals.xhx.module.device.service.DeviceLogService;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.queue.DefaultTbQueueMsg;
import com.mortals.xhx.queue.TbQueueMsg;
import com.mortals.xhx.queue.TbQueueMsgHeaders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.mortals.xhx.common.key.Constant.MESSAGETYPE_NOTIFY_REFRESH;

@RestController
@Slf4j
@RequestMapping("/notify")
public class DeviceSendMsgController {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MessageProducer messageProducer;
    @Autowired
    private DeviceLogService deviceLogService;


    @PostMapping("refreshMessage")
    @UnAuth
    public String refreshMessage(@RequestBody UploadDeviceReq req) {
        log.info("【设备通知刷新数据】【请求体】-->  " + JSONObject.toJSONString(req));
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            //查询站点设备并通知每个设备
            List<DeviceEntity> deviceList = deviceService.find(new DeviceQuery().siteId(req.getSiteId()));
            Runnable runnable = () -> {
                try {
                    List<List<DeviceEntity>> partition = ListUtil.partition(deviceList, 10);
                    for (List<DeviceEntity> deviceEntities : partition) {
                        for (DeviceEntity deviceEntity : deviceEntities) {
                            TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
                            header.put(MessageHeader.MESSAGETYPE, MESSAGETYPE_NOTIFY_REFRESH);
                            header.put(MessageHeader.DEVICECODE, deviceEntity.getDeviceCode());
                            header.put(MessageHeader.TIMESTAMP, DateUtils.getCurrStrDateTime());
                            TbQueueMsg queueMsg = new DefaultTbQueueMsg(IdUtil.fastUUID(), "W10=", header);
                            messageProducer.sendMsg(QueueKey.DEFAULT_EXCHANGE, Constant.DOWN_TOPIC + deviceEntity.getDeviceCode(), JSON.toJSONString(queueMsg));

                            DeviceLogEntity deviceLogEntity = new DeviceLogEntity();
                            deviceLogEntity.initAttrValue();
                            deviceLogEntity.setTraceID(IdUtil.fastSimpleUUID());
                            deviceLogEntity.setSiteId(deviceEntity.getSiteId());
                            deviceLogEntity.setDeviceId(deviceEntity.getId());
                            deviceLogEntity.setDeviceName(deviceEntity.getDeviceName());
                            deviceLogEntity.setDeviceCode(deviceEntity.getDeviceCode());
                            deviceLogEntity.setMessageHead(MESSAGETYPE_NOTIFY_REFRESH);
                            deviceLogEntity.setContent("W10=");
                            deviceLogEntity.setLogType(LogTypeEnum.下发服务.getValue());
                            deviceLogEntity.setCreateUserId(1L);
                            deviceLogEntity.setCreateTime(new Date());
                            deviceLogService.save(deviceLogEntity, null);
                        }
                        TimeUnit.SECONDS.sleep(1);
                    }
                } catch (InterruptedException e) {
                    log.error("异常", e);
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
        } 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);
    }


    /**
     * 下发消息
     *
     * @param req
     * @return
     */
    @PostMapping("downMsg")
    @UnAuth
    public String downMsg(@RequestBody UploadDeviceReq req) {
        log.info("【设备通知数据】【请求体】-->  " + JSONObject.toJSONString(req));
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            if (!ObjectUtils.isEmpty(req.getDeviceCodeList())) {
                DeviceQuery deviceQuery = new DeviceQuery();
                deviceQuery.setDeviceCodeList(req.getDeviceCodeList());
                //查询站点设备并通知每个设备
                List<DeviceEntity> deviceList = deviceService.find(deviceQuery);
                String content = "W10=";
                if (!ObjectUtils.isEmpty(req.getContent())) {
                    content = Base64.encode(req.getContent());
                }
                try {
                    for (DeviceEntity deviceEntity : deviceList) {
                        TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
                        header.put(MessageHeader.MESSAGETYPE, req.getAction());
                        header.put(MessageHeader.DEVICECODE, deviceEntity.getDeviceCode());
                        header.put(MessageHeader.TIMESTAMP, DateUtils.getCurrStrDateTime());
                        TbQueueMsg queueMsg = new DefaultTbQueueMsg(IdUtil.fastUUID(), content, header);
                        messageProducer.sendMsg(QueueKey.DEFAULT_EXCHANGE, Constant.DOWN_TOPIC + deviceEntity.getDeviceCode(), JSON.toJSONString(queueMsg));

                        DeviceLogEntity deviceLogEntity = new DeviceLogEntity();
                        deviceLogEntity.initAttrValue();
                        deviceLogEntity.setTraceID(IdUtil.fastSimpleUUID());
                        deviceLogEntity.setSiteId(deviceEntity.getSiteId());
                        deviceLogEntity.setDeviceId(deviceEntity.getId());
                        deviceLogEntity.setDeviceName(deviceEntity.getDeviceName());
                        deviceLogEntity.setDeviceCode(deviceEntity.getDeviceCode());
                        deviceLogEntity.setMessageHead(req.getAction());
                        deviceLogEntity.setContent(content);
                        deviceLogEntity.setLogType(LogTypeEnum.下发服务.getValue());
                        deviceLogEntity.setCreateUserId(1L);
                        deviceLogEntity.setCreateTime(new Date());
                        deviceLogService.save(deviceLogEntity, null);
                    }
                } catch (Exception e) {
                    log.error("异常", e);
                }
            }
        } 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);
    }


}
