package com.mortals.xhx.module.device.service.impl;

import cn.hutool.core.util.IdUtil;
import com.mortals.framework.model.Context;
import com.mortals.framework.util.DateUtils;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
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.queue.*;
import com.mortals.xhx.queue.provider.TbCoreQueueProducerProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDCacheServiceImpl;
import com.mortals.xhx.module.device.dao.DeviceDao;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.service.DeviceService;
import org.springframework.util.ObjectUtils;

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

/**
 * DeviceService
 * 设备 service实现
 *
 * @author zxfei
 * @date 2022-03-09
 */
@Service("deviceService")
public class DeviceServiceImpl extends AbstractCRUDCacheServiceImpl<DeviceDao, DeviceEntity, Long> implements DeviceService {

    @Autowired
    private TbCoreQueueProducerProvider producerProvider;

    @Override
    protected String getExtKey(DeviceEntity data) {
        return data.getDeviceCode();
    }


    @Override
    public ApiResp<String> sendDeviceMessage(Long deviceId, String topic, String message, Context context) {
        ApiResp<String> resp = new ApiResp<>();
        resp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        resp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        //发送消息
        send(topic, message, context, resp, deviceId);
        return resp;
    }

    @Override
    public ApiResp<String> sendDeviceMessage(List<Long> deviceIds, String topic, String message, Context context) {
        ApiResp<String> resp = new ApiResp<>();
        resp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        resp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());

        for (Long deviceId : deviceIds) {
            send(topic, message, context, resp, deviceId);
        }
        return resp;
    }

    private void send(String topic, String message, Context context, ApiResp<String> resp, Long deviceId) {
        DeviceEntity deviceEntity = this.get(deviceId, context);
        if (!ObjectUtils.isEmpty(deviceEntity)) {
            TbQueueProducer<TbQueueMsg> producer = producerProvider.getTbCoreMsgProducer();
            TopicPartitionInfo info = TopicPartitionInfo.builder().topic(topic + deviceEntity.getDeviceMac()).build();
            TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
            header.put(MessageHeader.CLIENTID, deviceEntity.getDeviceCode());
            header.put(MessageHeader.TIMESTAMP, DateUtils.getCurrStrDateTime());
            TbQueueMsg queueMsg = new DefaultTbQueueMsg(IdUtil.fastUUID(), message == null ? "".getBytes() : message.getBytes(), header);

            producer.send(info, queueMsg, new TbQueueCallback() {
                @Override
                public void onSuccess(TbQueueMsgMetadata metadata) {
                    log.info("消息投递成功,设备通道编码:" + deviceEntity.getDeviceMac());
                }

                @Override
                public void onFailure(Throwable t) {
                    log.error("消息投递成功,设备通道编码:" + deviceEntity.getDeviceMac(), t);

                }
            });
        } else {
            log.error(String.format("设备Id查询不到设备，deviceId:%s", deviceId));
            resp.setCode(ApiRespCodeEnum.FAILED.getValue());
            resp.setMsg(String.format("设备Id查询不到设备，deviceId:%s", deviceId));
        }
    }


}