package com.hys.app.service.erp.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hys.app.converter.erp.MailSmsCompanyConverter;
import com.hys.app.framework.context.user.AdminUserContext;
import com.hys.app.framework.database.mybatisplus.base.BaseServiceImpl;
import com.hys.app.mapper.erp.MailSmsCountMapper;
import com.hys.app.model.erp.dos.MailSmsCountDO;
import com.hys.app.model.erp.entity.MailSmsCountQuery;
import com.hys.app.model.erp.vo.MailSmsCountVO;
import com.hys.app.service.erp.MailSmsCountManager;
import com.hys.app.controller.erp.use.msg.AliSmsUtil;
import com.hys.app.controller.erp.use.msg.MailSmtpUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 订单业务层实现
 *
 * @author 张崧
 * 2024-01-24 15:58:31
 */
@Service
@AllArgsConstructor
public class MailSmsCountManagerImpl extends BaseServiceImpl<MailSmsCountMapper, MailSmsCountDO> implements MailSmsCountManager {

    @Override
    public IPage<MailSmsCountVO> getPage(MailSmsCountQuery query) {
        Page<MailSmsCountDO> page = page(new Page<>(query.getPageNo(), query.getPageSize()),
                new LambdaQueryWrapper<MailSmsCountDO>()
                        .eq(ObjectUtil.isNotNull(query.getCompanyId()), MailSmsCountDO::getCompanyId, query.getCompanyId()));
        return MailSmsCompanyConverter.INSTANCE.convert(page);
    }

    @Override
    public void sendSms(String rePhone, String templateCode, Map<String, String> map) {
        try {
            if (AliSmsUtil.sendSms(rePhone, templateCode, JSON.toJSONString(map) )) {
                addNum("mail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendEmail(String toMail, String subject, String content) {
        if (MailSmtpUtil.sendEmail(toMail, subject, content)) {
            addNum("sms");
        }
    }

    private void addNum(String type) {
        Long companyId = AdminUserContext.getCompanyId();
        MailSmsCountDO mailSmsCountDO = getOne(new LambdaQueryWrapper<MailSmsCountDO>().eq(MailSmsCountDO::getCompanyId, companyId));
        if (ObjectUtil.isNull(mailSmsCountDO)) {
            mailSmsCountDO = new MailSmsCountDO();
            mailSmsCountDO.setCompanyId(companyId);
        }
        if ("sms".equals(type)) {
            mailSmsCountDO.setSmsNum(mailSmsCountDO.getSmsNum() + 1);
        } else if ("mail".equals(type)) {
            mailSmsCountDO.setMailNum(mailSmsCountDO.getMailNum() + 1);
        }
        saveOrUpdate(mailSmsCountDO);
    }

}

