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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.dos.SmsMailTemplate;
import com.hys.app.model.erp.dto.SmsMailTemplateDTO;
import com.hys.app.model.erp.enums.MsgTypeEnum;

import com.hys.app.model.erp.vo.SmsMailTemplateQuery;
import com.hys.app.model.erp.vo.SmsMailTemplateVO;
import com.hys.app.service.erp.SmsMailManager;
import com.hys.app.controller.erp.use.msg.AliSmsUtil;
import com.hys.app.util.ValidateUtil;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 平台管理员业务类
 *
 * @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);
        //如果是短信模板向短信平台提交申请
//        if (convert.getType().equals(MsgTypeEnum.SMS)){
//            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();
//        }
        updateById(template);
        return null;
    }

//    private static WxMpService wxService;
//
//    static {
//        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
//        config.setAppId("你的AppID");
//        config.setSecret("你的AppSecret");
//        wxService = new WxMpServiceImpl();
//        wxService.setWxMpConfigStorage(config);
//    }
//
//    public static String applyTemplate(String shortTemplateId) throws WxErrorException {
//        String templateId = wxService.getTemplateMsgService().addTemplate(shortTemplateId);
//        System.out.println("成功添加模板，模板ID: " + templateId);
//        return templateId;
//    }


    @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);
    }

    @Override
    public List<SmsMailTemplate> getSysNotBand(MsgTypeEnum type) {
        //查询这个消息类型
        List<SmsMailTemplate> list = list(new LambdaQueryWrapper<SmsMailTemplate>()
                .select(SmsMailTemplate::getPid)
                .eq(SmsMailTemplate::getType,type)
                .eq(SmsMailTemplate::getEnableStatus,true));
        Set<Long> set = list.stream().map(SmsMailTemplate::getPid).collect(Collectors.toSet());
        LambdaQueryWrapper<SmsMailTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SmsMailTemplate::getType,MsgTypeEnum.SYSTEM);
        if (CollUtil.isNotEmpty(set)){
            wrapper.notIn(SmsMailTemplate::getId,set);
        }
        return list(wrapper);
    }

    private void checkParam(SmsMailTemplate smsMailTemplate) {
        if (smsMailTemplate.getType().equals(MsgTypeEnum.SMS) || smsMailTemplate.getType().equals(MsgTypeEnum.MAIL) ){
            if (ObjectUtil.isNull(smsMailTemplate.getPid())){
                throw new ServiceException("短信模板，邮件模板，公众号模板必须挂在消息模板下面");
            }
        }
//        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);
        }
        //短信模板和消息模板在每个系统消息下面,并且盛和通过的智能有一条
        if (!smsMailTemplate.getType().equals(MsgTypeEnum.SYSTEM) && ObjectUtil.isNotNull(smsMailTemplate.getPid())){
            SmsMailTemplate one = getOne(new LambdaQueryWrapper<SmsMailTemplate>()
                    .eq(SmsMailTemplate::getPid,smsMailTemplate.getPid())
                    .eq(SmsMailTemplate::getEnableStatus,true)
                    .eq(SmsMailTemplate::getType,smsMailTemplate.getType())
                    .ne(ObjectUtil.isNotNull(smsMailTemplate.getId()),SmsMailTemplate::getId,smsMailTemplate.getId()));
            if (ObjectUtil.isNotNull(one)){
                throw new ServiceException("一个系统消息下面只能同时挂载一个已起用的"+smsMailTemplate.getType().getLabel()+"消息");
            }
        }
    }


//    @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);
    }
}
