package com.mortals.xhx.thread;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.AbstractThread;
import com.mortals.xhx.base.system.message.impl.MessageProducer;
import com.mortals.xhx.busiz.req.DeviceMsgReq;
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.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.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.mortals.xhx.common.key.RedisKey.KEY_DEVICE_DOWN_MSG_QUEUE;


/**
 * 发送第三方服务线程
 *
 * @author zxfei
 */
@Slf4j
@Service
@Order(value = 3)
public class DeviceDownMsgThread extends AbstractThread {

    @Autowired
    private ICacheService cacheService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceLogService deviceLogService;
    @Autowired
    private MessageProducer messageProducer;


    @Override
    protected int getSleepTime() {
        return 1000;
    }

    @Override
    protected void process() {
        //log.info("DeviceDownMsgThread process");
        List<DeviceMsgReq> deviceMsgReqs = new ArrayList<>();
        while (true) {
            DeviceMsgReq deviceMsgReq = cacheService.lpop(KEY_DEVICE_DOWN_MSG_QUEUE, DeviceMsgReq.class);
            if (ObjectUtils.isEmpty(deviceMsgReq)) {
               // log.info("deviceMsgReq:{}", deviceMsgReq == null);
                break;
            }
            deviceMsgReqs.add(deviceMsgReq);

        }
        if (!ObjectUtils.isEmpty(deviceMsgReqs)) {
            log.info("消息下发数量:{}", deviceMsgReqs.size());
            ArrayList<DeviceLogEntity> deviceLogList = new ArrayList<>();

            for (DeviceMsgReq item : deviceMsgReqs) {
                //根据设备编码查询设备
                DeviceEntity deviceEntity = null;
                try {
                    deviceEntity = deviceService.getExtCache(item.getDeviceCode());
                } catch (Exception e) {
                    log.info("deviceCode:{}", item.getDeviceCode());
                    log.error("redis 获取设备异常！", e);
                    continue;
                }
                if (!ObjectUtils.isEmpty(deviceEntity)) {
                    TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
                    header.put(MessageHeader.MESSAGETYPE, item.getMessageType());
                    header.put(MessageHeader.DEVICECODE, item.getDeviceCode());
                    header.put(MessageHeader.TIMESTAMP, item.getTimestamp().toString());

                    TbQueueMsg queueMsg = new DefaultTbQueueMsg(IdUtil.fastUUID(), item.getData(), 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(item.getMessageType());
                    deviceLogEntity.setContent(item.getData());
                    deviceLogEntity.setLogType(LogTypeEnum.下发服务.getValue());
                    deviceLogEntity.setCreateUserId(1L);
                    deviceLogEntity.setCreateTime(new Date());
                    deviceLogList.add(deviceLogEntity);
                    // deviceLogService.save(deviceLogEntity, null);
                } else {
                    log.info("未找到设备，deviceCode:{}", item.getDeviceCode());
                }
            }
            if (!ObjectUtils.isEmpty(deviceLogList)) {
                List<List<DeviceLogEntity>> partition = ListUtil.partition(deviceLogList, 100);
                for (List<DeviceLogEntity> deviceLogEntities : partition) {
                    deviceLogService.save(deviceLogEntities);
                }
            }
        }
    }


    @Override
    protected void threadClosed() {
        // TODO Auto-generated method stub
        super.close();
    }


}
