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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySmsTemplateRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySmsTemplateResponse;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hys.app.converter.erp.SmsMailConverter;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.mapper.erp.SmsMailMapper;
import com.hys.app.model.erp.enums.MsgTypeEnum;
import com.hys.app.model.system.dos.SmsMailTemplate;
import com.hys.app.model.system.dto.SmsMailTemplateDTO;
import com.hys.app.model.system.vo.SmsMailTemplateQuery;
import com.hys.app.model.system.vo.SmsMailTemplateVO;
import com.hys.app.service.erp.SmsMailManager;
import com.hys.app.util.AliSmsUtil;
import com.hys.app.util.ValidateUtil;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 平台管理员业务类
 *
 * @author zh
 * @version v7.0
 * @since v7.0.0
 * 2018-06-20 20:38:26
 */
@Service
@AllArgsConstructor
public class SmsMailManagerImpl extends ServiceImpl<SmsMailMapper, SmsMailTemplate> implements SmsMailManager {

    @Override
    public Long createTemplate(SmsMailTemplateDTO smsMailTemplateDTO) {
        SmsMailTemplate convert = SmsMailConverter.INSTANCE.convert(smsMailTemplateDTO);
        checkParam(convert);
        //如果是短信模板向短信平台提交申请
        String smsTemplateCode = AliSmsUtil.createSmsTemplate(smsMailTemplateDTO.getTemplateType(), smsMailTemplateDTO.getName(), smsMailTemplateDTO.getContent(), smsMailTemplateDTO.getRemark());
        convert.setTemplateCode(smsTemplateCode);
        save(convert);
        return convert.getId();
    }

    @Override
    public Long updateTemplate(SmsMailTemplateDTO smsMailTemplateDTO, Long id) {
        SmsMailTemplate template = ValidateUtil.getOne(baseMapper, SmsMailTemplate::getId, id, "模板");
        if (template.getType().equals(MsgTypeEnum.SMS) && template.getAuditStatus()) {
            throw new ServiceException("已审核通过的模板不允许修改，如有需求变动另建模板");
        }
        BeanUtil.copyProperties(smsMailTemplateDTO, template);
        if (template.getType().equals(MsgTypeEnum.SMS)) {
            //如果是短信模板向短信平台提交申请
            String smsTemplateCode = AliSmsUtil.createSmsTemplate(smsMailTemplateDTO.getTemplateType(), smsMailTemplateDTO.getName(), smsMailTemplateDTO.getContent(), smsMailTemplateDTO.getRemark());
            template.setTemplateCode(smsTemplateCode);
            updateById(template);
            return template.getId();
        }
        return null;
    }
    @Override
    public IPage<SmsMailTemplateVO> queryTemplate(SmsMailTemplateQuery query) {
        Page<SmsMailTemplate> page = page(new Page<>(query.getPageNo(), query.getPageSize()), new LambdaQueryWrapper<SmsMailTemplate>()
                .eq(ObjectUtil.isNotNull(query.getType()), SmsMailTemplate::getType, query.getType())
                .eq(ObjectUtil.isNotNull(query.getEnableStatus()), SmsMailTemplate::getEnableStatus, query.getEnableStatus())
                .like(StrUtil.isNotBlank(query.getCode()), SmsMailTemplate::getCode, query.getCode())
                .like(StrUtil.isNotBlank(query.getName()), SmsMailTemplate::getName, query.getName()));
        return SmsMailConverter.INSTANCE.convert(page);
    }

    @Override
    public void delete(Long id) {
        SmsMailTemplate template = ValidateUtil.getOne(baseMapper, SmsMailTemplate::getId, id, "模板");
        if (template.getType().equals(MsgTypeEnum.SMS) && template.getAuditStatus()) {
            throw new ServiceException("已审核通过的模板不允许修改和删除");
        }
        removeById(id);
    }

    private void checkParam(SmsMailTemplate smsMailTemplate) {
        if (Pattern.matches(".*[\\u4e00-\\u9fa5\\p{P}].*", smsMailTemplate.getCode())) {
            throw new ServiceException("自定义编码不能包含中文和特殊符号");
        }
        if (ValidateUtil.checkRepeat(baseMapper, SmsMailTemplate::getCode, smsMailTemplate.getCode(), SmsMailTemplate::getId, smsMailTemplate.getId())) {
            throw new ServiceException("编码已存在");
        }
        if (ValidateUtil.checkRepeat(baseMapper, SmsMailTemplate::getName, smsMailTemplate.getName(), SmsMailTemplate::getId, smsMailTemplate.getId())) {
            throw new ServiceException("模板名称重复");
        }
        if (smsMailTemplate.getType().equals(MsgTypeEnum.MAIL)) {
            smsMailTemplate.setAuditStatus(true);
        }
    }


    @Scheduled(cron = "0 0 1 * * ?")  // 每天凌晨1点执行查看哪些没有审核通过的模板的查询
    public void updateTemplateStatus() throws Exception {
        List<SmsMailTemplate> list = list(new LambdaQueryWrapper<SmsMailTemplate>()
                .eq(SmsMailTemplate::getType, MsgTypeEnum.SMS).eq(SmsMailTemplate::getAuditStatus, false)
                .eq(SmsMailTemplate::getEnableStatus, true));
        for (SmsMailTemplate template : list) {
            // 初始化客户端
            IAcsClient client = AliSmsUtil.getIAcsClient();
            // 创建查询请求并设置参数
            QuerySmsTemplateRequest request = new QuerySmsTemplateRequest();
            request.setTemplateCode(template.getTemplateCode());
            // 发起请求并处理响应
            QuerySmsTemplateResponse response = client.getAcsResponse(request);
            if ("OK".equals(response.getCode())) {
                System.out.println("查询成功");
                if (response.getTemplateStatus() == 1) {
                    template.setAuditStatus(true);
                    template.setFailReason("");
                }
                if (response.getTemplateStatus() == 2) {
                    template.setAuditStatus(false);
                    template.setFailReason(response.getReason());
                }
            }
        }
        updateBatchById(list);
    }
}
