/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2022 . All rights reserved.
 *
 */
package net.northking.cctp.attachment.bus;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.attachment.db.entity.Attachment;
import net.northking.cctp.attachment.db.service.AttachmentService;
import net.northking.cctp.common.enums.FileBusinessTypeEnum;
import net.northking.cctp.common.s3.AttachmentProducer;
import net.northking.cctp.common.s3.SimpleStorageService;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 附件消息消费者
 *
 * @author : xiusong.xie
 * @version : 1.0
 */
@Component
public class AttachmentMQConsumer implements AttachmentConsumer
{
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(AttachmentMQConsumer.class);

  @Autowired
  private AttachmentService attachmentService;

  @Autowired
  private ObjectMapper objectMapper;

  @Autowired
  private SimpleStorageService storageService;

  private final TypeReference<Attachment> typeReference = new TypeReference<Attachment>()
  {
  };


  @RabbitListener(queuesToDeclare = {@Queue(value = AttachmentProducer.RoutingKey)})
  @Override
  public void process(Message message)
  {
    try
    {
      Attachment attachment = objectMapper.readValue(message.getBody(), typeReference);
      logger.info("接收到文件消息：{}", JSON.toJSONString(attachment));
      if (StringUtils.hasText(attachment.getTenantId()))
      {
        if (attachment.isDeleted())
        {
          // 删除文件，同步删除文件服务器文件
          String fid = attachment.getId();
          if (fid.startsWith("/")) {
            fid = fid.substring(fid.indexOf("/") + 1);
          }
          storageService.deleteFile(fid);
          NKSecurityContext.setTenantId(attachment.getTenantId());  // 修改时需要设置当前线程的tenantId 2022.11.21 jieying.li
          attachment.setObjId("-1");
          attachmentService.updateByPrimaryKey(attachment);
        } else
        {
          String businessCode = attachment.getBusinessCode();
          FileBusinessTypeEnum fileBusinessTypeByCode = FileBusinessTypeEnum.getFileBusinessTypeByCode(businessCode);
          if (null != fileBusinessTypeByCode) {
            attachment.setOverTime(fileBusinessTypeByCode.getOverTime());
          }
          attachmentService.insertByBus(attachment);
        }
      } else
      {
        logger.error("租户ID为空，无法处理：" + new String(message.getBody()));
      }

    } catch (Exception e)
    {
      logger.error("记录附件信息发生异常。" + new String(message.getBody()), e);
    }
  }
}
