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

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.BizLogPdu;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.service.IMessageProduceService;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.common.code.LogTypeEnum;
import com.mortals.xhx.module.device.dao.DeviceLogDao;
import com.mortals.xhx.module.device.model.DeviceLogEntity;
import com.mortals.xhx.module.device.service.DeviceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

/**
 * DeviceLogService
 * 设备日志 service实现
 *
 * @author zxfei
 * @date 2022-06-27
 */
@Service("deviceLogService")
public class DeviceLogServiceImpl extends AbstractCRUDServiceImpl<DeviceLogDao, DeviceLogEntity, Long> implements DeviceLogService {

    @Value("${spring.application.name:''}")
    private String appName;

    @Autowired
    private IMessageProduceService messageProducer;

    @Override
    protected void findAfter(DeviceLogEntity params, PageInfo pageInfo, Context context, List<DeviceLogEntity> list) throws AppException {
        list.stream().forEach(item -> {
            try {
                item.setContent(Base64.decodeStr(item.getContent()));
            } catch (Exception e) {
                log.error("content:" + item.getContent());
            }

        });
    }


    @Override

    protected void saveAfter(DeviceLogEntity entity, Context context) throws AppException {
        log.debug("业务日志保存成功！");
        BizLogPdu bizLogPdu = new BizLogPdu();
        bizLogPdu.initAttrValue();
        bizLogPdu.setAppName(appName);
        bizLogPdu.setTraceID(IdUtil.objectId());
        bizLogPdu.setUserCode("system");
        bizLogPdu.setDeviceCode(entity.getDeviceCode());
        bizLogPdu.setEventTopic(entity.getMessageHead());
        bizLogPdu.setEventTopicName(LogTypeEnum.下发服务.name());
        bizLogPdu.setMsg(entity.getContent());
        bizLogPdu.setLogLevel("INFO");
        bizLogPdu.setLogTime(new Date());
        messageProducer.syncBizSend(bizLogPdu);
    }
}