package cn.axzo.msg.center.inside.notices.service.impl;


import cn.axzo.msg.center.common.enums.TableIsDeleteEnum;
import cn.axzo.msg.center.dal.MessageTemplateDao;
import cn.axzo.msg.center.domain.dto.SearchTemplateDTO;
import cn.axzo.msg.center.domain.dto.SyncTemplateDataDTO;
import cn.axzo.msg.center.domain.entity.MessageTemplate;
import cn.axzo.msg.center.domain.persistence.BaseEntity;
import cn.axzo.msg.center.inside.notices.service.MessageTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 消息模板(MessageTemplate)表服务实现类
 *
 * @author zhangran
 * @since 2022-03-28 14:59:16
 */
@Service
@Slf4j
public class MessageTemplateServiceImpl implements MessageTemplateService {

  @Autowired
  private MessageTemplateDao messageTemplateDao;


  @Override
  public List<MessageTemplate> getAllTemplates() {
    return messageTemplateDao.lambdaQuery()
        .eq(MessageTemplate::getIsDelete, TableIsDeleteEnum.NORMAL.value)
        .select(BaseEntity::getId, MessageTemplate::getTitle, MessageTemplate::getContent,
            MessageTemplate::getUpdateAt)
        .list();
  }

  @Override
  public Boolean hasTemplateGtUpdateAt(LocalDateTime updateAt) {
    return messageTemplateDao.lambdaQuery()
        .gt(Objects.nonNull(updateAt), MessageTemplate::getUpdateAt, updateAt)
        .count() > 0;
  }

  @Override
  public void saveOrUpdateTemplate(MessageTemplate template) {
    messageTemplateDao.saveOrUpdate(template);
  }

  @Override
  public MessageTemplate getTemplateById(Long templateId) {
    return messageTemplateDao.getById(templateId);
  }

  @Override
  public List<MessageTemplate> getTemplateByIds(List<Long> templateIds) {
    if(CollectionUtils.isEmpty(templateIds)){
      return new ArrayList<>();
    }
    return messageTemplateDao.listByIds(templateIds);
  }

  @Override
  public void removeById(MessageTemplate mt) {
    messageTemplateDao.removeById(mt.getId());
  }

  @Override
  public void insertNativeSql(SyncTemplateDataDTO template) {
    messageTemplateDao.insertSql(template);
  }

  @Override
  public List<MessageTemplate> getListByTitleAndContent(SearchTemplateDTO dto) {
    return messageTemplateDao.lambdaQuery()
            .like(StringUtils.hasLength(dto.getTitle()), MessageTemplate::getTitle, dto.getTitle())
            .like(StringUtils.hasLength(dto.getContent()), MessageTemplate::getContent, dto.getContent())
            .list();
  }
}
