package cn.axzo.msg.center.notices.manager;

import cn.axzo.msg.center.dal.MNSBatchMessageDao;
import cn.axzo.msg.center.dal.MNSMessageDao;
import cn.axzo.msg.center.domain.entity.MNSBatchMessage;
import cn.axzo.msg.center.domain.entity.MNSMessage;
import cn.axzo.msg.center.domain.query.BatchMessageQuery;
import cn.axzo.msg.center.notices.common.enums.BatchMessageStatusEnum;
import cn.axzo.msg.center.notices.common.enums.MessageStatusEnum;
import cn.axzo.msg.center.notices.common.enums.MessageTypeEnum;
import cn.axzo.msg.center.notices.common.enums.NotifyTypeEnum;
import cn.axzo.msg.center.notices.common.lang.Page;
import cn.axzo.msg.center.notices.manager.api.SmsSendManager;
import cn.axzo.msg.center.notices.manager.api.dto.request.BatchMessageRequestDto;
import cn.axzo.msg.center.notices.manager.api.BatchMessageManger;
import cn.axzo.msg.center.notices.manager.api.dto.request.BatchMessageSendRequestDto;
import cn.axzo.msg.center.notices.manager.api.dto.request.SmsContentDto;
import cn.azxo.framework.common.utils.LogUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Classname BatchMessageMangerImpl
 * @Author: szg
 * @Date: 2021年08月09日 17:17
 * @Description:
 */
@Service("batchMessageManger")
@Slf4j
public class BatchMessageMangerImpl implements BatchMessageManger {

  @Resource
  private MNSMessageDao mnsMessageDao;

  @Resource
  private MNSBatchMessageDao mnsBatchMessageDao;

  @Resource(name = "transactionTemplate")
  private TransactionTemplate transactionTemplate;

  @Resource(name = "smsSendManagerComposite")
  private SmsSendManager smsSendManagerComposite;

  @Resource(name = "genericConversionService")
  private GenericConversionService genericConversionService;

  @Override
  public Page<MNSBatchMessage> queryByPage(BatchMessageRequestDto requestDto) {
    BatchMessageQuery query = new BatchMessageQuery();
    BeanUtils.copyProperties(requestDto, query);
    IPage<MNSBatchMessage> messagePage = mnsBatchMessageDao.queryByPage(query);
    if (messagePage == null) {
      log.info("BatchMessageMangerImpl.queryByPage result is null");
      return null;
    }
    Page<MNSBatchMessage> result = new Page<>();
    result.setPageNum(messagePage.getCurrent());
    result.setPageSize(messagePage.getSize());
    result.setTotalElements(messagePage.getTotal());
    result.setList(messagePage.getRecords());
    return result;
  }

  @Override
  public MNSBatchMessage queryBatchMessage(String batchNo) {
    return mnsBatchMessageDao.queryBatchMessage(batchNo);
  }

  @Override
  public boolean batchMessageSplitToMessage(MNSBatchMessage batchMessage) {
    List<MNSMessage> messages = initMessageList(batchMessage);
    if (CollectionUtils.isEmpty(messages)) {
      log.info("BatchMessageMangerImpl.batchMessageSplitToMessage initMessageList result is null ");
      return false;
    }
    return transactionTemplate.execute(status -> {
      Boolean updateRes = mnsBatchMessageDao
          .updateStatusById(batchMessage.getId(), BatchMessageStatusEnum.SPLIT_COMPLETED.getCode());
      if (updateRes) {
        return mnsMessageDao.saveBatch(messages);
      }
      return false;
    });
  }

  @Override
  public void sendBatchMessageAndHandleReceipt(MNSBatchMessage batchMessage) {
    if (Objects.isNull(batchMessage)) {
      log.info("BatchMessageMangerImpl.sendBatchMessageAndHandleReceipt batchMessage is null");
      return;
    }
    BatchMessageSendRequestDto requestDto = genericConversionService
        .convert(batchMessage, BatchMessageSendRequestDto.class);
    //1.变更状态
    mnsBatchMessageDao.updateStatusById(batchMessage.getId(),BatchMessageStatusEnum.PROCESSING.getCode());
    //2.发送消息
    try {
      log.info("开始发送短信批次->BatchMessageMangerImpl.sendBatchMessageAndHandleReceipt BatchMessage = {}",
          JSON.toJSONString(requestDto));
      smsSendManagerComposite.sendBatchMessage(requestDto);
    }catch (Exception e){
      LogUtil.error(
          "发送短信批次失败->BatchMessageMangerImpl.sendBatchMessageAndHandleReceipt BatchMessage = {} ",
          JSON.toJSONString(requestDto));
    }
  }

  /**
   * 初始化短信模板
   *
   * @param request
   * @return
   */
  private List<MNSMessage> initMessageList(MNSBatchMessage request) {

    String smsContent = request.getSmsContent();
    if (StringUtils.isEmpty(smsContent)) {
      return null;
    }
    List<SmsContentDto> totalList = JSON.parseArray(smsContent, SmsContentDto.class);
    if (CollectionUtils.isEmpty(totalList)) {
      return null;
    }
    List<MNSMessage> messageList = new ArrayList<>();
    for (SmsContentDto smsContentDto : totalList) {
      if (Objects.isNull(smsContentDto)) {
        continue;
      }

      MNSMessage message = new MNSMessage();
      message.setAppNo(request.getAppNo());
      message.setRequestNo(request.getRequestNo());
      message.setBatchNo(request.getRequestNo());
      message.setMessageOrderNo(IdUtil.simpleUUID());
      message.setMessageType(MessageTypeEnum.S.name());
      message.setNotifyType(NotifyTypeEnum.BATCH.name());
      message.setStatus(MessageStatusEnum.INIT.getCode());
      message.setChannelCode("batch");
      message.setChannelName("batch");
      message.setTemplateNo(request.getTemplateNo());
      message.setSubject(JSON.toJSONString(smsContentDto.getTemplateParams()));
      message.setTargetAddress(smsContentDto.getPhoneNo());
      message.setBatchNo(request.getBatchNo());
      message.setNotifyRule("");
      message.setRemark("");
      messageList.add(message);
    }

    return messageList;
  }
}
