package com.bonus.canteen.core.supply.purchase.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.supply.purchase.constants.DrpNoticeStyleEnum;
import com.bonus.canteen.core.supply.purchase.constants.DrpPurNoticeStatusEnum;
import com.bonus.canteen.core.supply.purchase.constants.NoticeTemplateKeyEnum;
import com.bonus.canteen.core.supply.purchase.constants.NoticeTemplateTypeEnum;
import com.bonus.canteen.core.supply.purchase.domain.bo.*;
import com.bonus.canteen.core.supply.purchase.domain.param.DrpNoticeParam;
import com.bonus.canteen.core.supply.purchase.domain.vo.DrpPurNoticePageVO;
import com.bonus.canteen.core.supply.purchase.mapper.DrpPurchasePurNoticeMapper;
import com.bonus.canteen.core.supply.purchase.mapper.DrpPurchaseSupplierMapper;
import com.bonus.canteen.core.supply.purchase.service.DrpPurchasePurNoticeService;
import com.bonus.common.core.utils.sms.SmsUtils;
import com.bonus.common.houqin.constant.DelFlagEnum;
import com.bonus.common.houqin.utils.AesEncryptUtil;
import com.bonus.common.houqin.utils.SM4EncryptUtils;
import com.bonus.common.houqin.utils.id.Id;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class DrpPurchasePurNoticeServiceImpl extends ServiceImpl<DrpPurchasePurNoticeMapper, DrpPurNotice> implements DrpPurchasePurNoticeService {
   private static final Logger log = LoggerFactory.getLogger(DrpPurchasePurNoticeServiceImpl.class);
   @Autowired
   @Lazy
   private DrpPurchasePurNoticeMapper drpPurchasePurNoticeMapper;
   @Autowired
   @Lazy
   private DrpPurchaseSupplierMapper drpPurchaseSupplierMapper;
   @Autowired
   @Lazy
   private DrpPurchasePurNoticeService drpPurchasePurNoticeService;
//   @Autowired
//   @Lazy
//   private JavaMailSender javaMailSender;
//   @Value("${spring.mail.username}")
//   private String from;

   public Page<DrpPurNoticePageVO> pagePurNotice(DrpPurNoticePageDTO content) {
      Page<DrpPurNoticePageVO> resultPage = new Page(content.getCurrent(), content.getSize());
      QueryWrapper<DrpPurNotice> queryWrapper = new QueryWrapper();
      queryWrapper.ge("dpn.notice_time", content.getStartTime());
      queryWrapper.le("dpn.notice_time", content.getEndTime());
      if (CharSequenceUtil.isNotBlank(content.getPlanId())) {
         queryWrapper.eq("dpn.plan_id", content.getPlanId());
      }

      if (CharSequenceUtil.isNotBlank(content.getSupplierName())) {
         queryWrapper.like("ds.supplier_name", content.getSupplierName());
      }

      if (null != content.getNoticeStatus()) {
         queryWrapper.eq("dpn.notice_status", content.getNoticeStatus());
      }

      if (CharSequenceUtil.isNotBlank(content.getSupplierSingleId())) {
         queryWrapper.eq("dpn.supplier_single_id", content.getSupplierSingleId());
      }

      if (null != content.getNoticeProcess()) {
         queryWrapper.eq("dpn.notice_process", content.getNoticeProcess());
      }

      if (null != content.getNoticeStyle()) {
         queryWrapper.eq("dpn.notice_style", content.getNoticeStyle());
      }

      resultPage = this.drpPurchasePurNoticeMapper.pagePurNotice(resultPage, queryWrapper);
      return resultPage;
   }

   public void sendMsgToSupplier(List<DrpNoticeParam> drpNoticeParamList) {
      Iterator var2 = drpNoticeParamList.iterator();

      while(var2.hasNext()) {
         DrpNoticeParam drpNoticeParam = (DrpNoticeParam)var2.next();
         DrpSupplier drpSupplier = this.drpPurchaseSupplierMapper.selectOne(((Wrappers.lambdaQuery(DrpSupplier.class).eq(DrpSupplier::getSupplierId, drpNoticeParam.getSupplierId())).eq(DrpSupplier::getDelFlag, DelFlagEnum.DEL_FALSE.key())).select(DrpSupplier::getNoticeStyle, DrpSupplier::getIfReceiveNotice, DrpSupplier::getEmail, DrpSupplier::getLinkmanNumber, DrpSupplier::getSupplierId, DrpSupplier::getSupplierUserId));
         drpNoticeParam.setPhone(drpSupplier.getLinkmanNumber());
         drpNoticeParam.setSupplierName(drpSupplier.getSupplierName());
         if (drpSupplier.getNoticeStyle().equals(DrpNoticeStyleEnum.SMS_NOTICE.key())) {
            this.drpPurchasePurNoticeService.sendSmsNotice(drpNoticeParam);
         }

         if (drpSupplier.getIfReceiveNotice() != 1) {
            this.noticeErrorSave(drpNoticeParam, DrpNoticeStyleEnum.NOT_NOTICE.key(), "未启用邮件通知!");
         } else {
            this.sendEmailNotice(drpNoticeParam.getContentId(), drpSupplier);
         }
      }

   }

   protected void noticeErrorSave(DrpNoticeParam drpNoticeParam, Integer noticeStyle, String msg) {
      DrpPurNotice drpPurNotice = new DrpPurNotice();
      drpPurNotice.setNoticeId(Id.next());
      drpPurNotice.setPlanId(drpNoticeParam.getMainId());
      drpPurNotice.setNoticeTime(LocalDateTime.now());
      drpPurNotice.setNoticeType(drpNoticeParam.getNoticeType());
      drpPurNotice.setNoticeProcess(drpNoticeParam.getNoticeProcess());
      drpPurNotice.setNoticeStyle(noticeStyle);
      drpPurNotice.setSupplierId(drpNoticeParam.getSupplierId());
      drpPurNotice.setSupplierSingleId(drpNoticeParam.getContentId());
      drpPurNotice.setNoticeStatus(DrpPurNoticeStatusEnum.ERROR.key());
      drpPurNotice.setErrorReason(msg);
      this.drpPurchasePurNoticeMapper.insert(drpPurNotice);
   }

   public void sendSmsNotice(DrpNoticeParam drpNoticeParam) {
      log.info("采购通知短信通知!");
      DrpPurNotice drpPurNotice = new DrpPurNotice();

      try {
         Long noticeId = Id.next();
         drpPurNotice.setNoticeId(noticeId);
         drpPurNotice.setPlanId(drpNoticeParam.getMainId());
         drpPurNotice.setNoticeTime(LocalDateTime.now());
         drpPurNotice.setNoticeType(drpNoticeParam.getNoticeType());
         drpPurNotice.setNoticeProcess(drpNoticeParam.getNoticeProcess());
         drpPurNotice.setNoticeStyle(DrpNoticeStyleEnum.SMS_NOTICE.key());
         drpPurNotice.setSupplierId(drpNoticeParam.getSupplierId());
         drpPurNotice.setSupplierSingleId(drpNoticeParam.getContentId());
         if (CharSequenceUtil.isBlank(drpNoticeParam.getPhone())) {
            log.info("手机号不存在");
            drpPurNotice.setNoticeStatus(DrpPurNoticeStatusEnum.ERROR.key());
            drpPurNotice.setErrorReason("手机号不存在!");
            this.drpPurchasePurNoticeMapper.insert(drpPurNotice);
            return;
         }

         drpPurNotice.setNoticeStatus(DrpPurNoticeStatusEnum.WAITING_TO_SEND.key());
         this.drpPurchasePurNoticeMapper.insert(drpPurNotice);
         DrpNoticeGeneralMqDTO dto = new DrpNoticeGeneralMqDTO();
         dto.setNoticeType(NoticeTemplateTypeEnum.SMS.getKey());
         dto.setNoticeId(noticeId);
         dto.setRecipientList(Collections.singletonList(drpNoticeParam.getPhone()));
         dto.setCode(drpNoticeParam.getCode());
         dto.setSupplierName(drpNoticeParam.getSupplierName());
         dto.setDrpInquirySendNoticeType(drpNoticeParam.getDrpInquirySendNoticeType());
         log.info("供货单mq发送消息完成");
      } catch (Exception var5) {
         log.info("供货单：{},短信通知异常", drpNoticeParam.getContentId());
         drpPurNotice.setNoticeStatus(DrpPurNoticeStatusEnum.ERROR.key());
         drpPurNotice.setErrorReason("异常错误");
         this.drpPurchasePurNoticeMapper.insert(drpPurNotice);
      }

   }

   public void sendEmailNotice(String supplierSingleId, DrpSupplier drpSupplier) {
   }

//   protected void sendJavaEmail(String subject, String text, String receiver, InputStream in, String fileName) throws IOException, MessagingException {
//      MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
//      MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//      helper.setSubject(subject);
//      helper.setFrom(this.from);
//      helper.setTo(receiver);
//      helper.setSentDate(new Date());
//      if (CharSequenceUtil.isBlank(text)) {
//         text = "正文";
//      }
//
//      helper.setText(text);
//      ByteArrayResource byteArrayResource = new ByteArrayResource(IOUtils.toByteArray(in));
//      helper.addAttachment(fileName, byteArrayResource);
//      helper.setCc(receiver);
//      this.javaMailSender.send(mimeMessage);
//      log.info("邮件携带附件发送成功!");
//   }

   public void sendSmsNoticeGeneral(Long supplierId, String phone, String mainId, String key) {
      DrpNoticeGeneralMqDTO dto = new DrpNoticeGeneralMqDTO();
      Long noticeId = Id.next();
      if (supplierId != null) {
         DrpSupplier drpSupplier = this.drpPurchaseSupplierMapper.selectOne(((Wrappers.lambdaQuery(DrpSupplier.class).eq(DrpSupplier::getSupplierId, supplierId)).eq(DrpSupplier::getDelFlag, DelFlagEnum.DEL_FALSE.key())).select(DrpSupplier::getNoticeStyle, DrpSupplier::getIfReceiveNotice, DrpSupplier::getEmail, DrpSupplier::getLinkmanNumber, DrpSupplier::getSupplierId, DrpSupplier::getSupplierUserId, DrpSupplier::getSupplierName));
         dto.setSupplierName(drpSupplier.getSupplierName());
         if (phone == null) {
            if (drpSupplier.getNoticeStyle() != 2) {
               log.info("当前供应商不存在或未配置短信通知！");
               return;
            }

            phone = drpSupplier.getLinkmanNumber();
         }
      }

      phone = SM4EncryptUtils.sm4Decrypt(phone);
      phone = AesEncryptUtil.aesDecode(phone);
      dto.setNoticeType(NoticeTemplateTypeEnum.SMS.getKey());
      dto.setNoticeId(noticeId);
      dto.setRecipientList(Collections.singletonList(phone));
      dto.setCode(mainId);
      dto.setDrpInquirySendNoticeType(key);
      SmsUtils.smsToken(phone, MessageFormat.format(NoticeTemplateKeyEnum.getNoticeTemplateByKey(key), mainId), "");
      DrpPurNotice drpPurNotice = new DrpPurNotice();
      drpPurNotice.setNoticeId(noticeId);
      drpPurNotice.setPlanId(mainId);
      drpPurNotice.setNoticeTime(LocalDateTime.now());
      drpPurNotice.setNoticeType(1);
      drpPurNotice.setNoticeProcess(1);
      drpPurNotice.setNoticeStyle(DrpNoticeStyleEnum.SMS_NOTICE.key());
      drpPurNotice.setSupplierId(supplierId);
      drpPurNotice.setSupplierSingleId(key);
      if (CharSequenceUtil.isBlank(phone)) {
         log.info("手机号不存在");
         drpPurNotice.setNoticeStatus(DrpPurNoticeStatusEnum.ERROR.key());
         drpPurNotice.setErrorReason("手机号不存在!");
         this.drpPurchasePurNoticeMapper.insert(drpPurNotice);
      } else {
         drpPurNotice.setNoticeStatus(DrpPurNoticeStatusEnum.WAITING_TO_SEND.key());
         this.drpPurchasePurNoticeMapper.insert(drpPurNotice);
      }
   }
}
