package com.clx.performance.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.clx.performance.common.MqWrapper;
import com.clx.performance.dao.vehiclewarn.VehicleWarnUserDao;
import com.clx.performance.enums.SmsTemplateEnum;
import com.clx.performance.model.vehiclewarn.VehicleWarnUser;
import com.clx.performance.param.mq.SendSmsNoticeParam;
import com.clx.performance.service.SendSmsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.clx.performance.constant.RabbitKeyConstants.NOTICE_SEND_SMS_QUEUE_EXCHANGE;
import static com.clx.performance.constant.RabbitKeyConstants.NOTICE_SEND_SMS_QUEUE_ROUTING_KEY;

/**
 * @ClassName SendSmsServiceImpl
 * @Description
 * @Author kavin
 * @Date 2024/11/6 10:14
 * @Version 1.0
 */
@Service
@Slf4j
@AllArgsConstructor
public class SendSmsServiceImpl implements SendSmsService {

    private final RabbitTemplate rabbitTemplate;
    private final VehicleWarnUserDao vehicleWarnUserDao;


    @Override
    public void sendChildWarnConfigSmsNotice(Integer warnTypeCode, SmsTemplateEnum.Type smsTemplateType,
            List<String> paramList){
        String params = replaceContent(smsTemplateType.getParam(), paramList);
        List<String> targets = getTargets(warnTypeCode);
        SendSmsNoticeParam param = new SendSmsNoticeParam();
        param.setCode(smsTemplateType.getCode());
        param.setMobileList(targets);
        param.setParams(JSON.parseObject(params));
        log.info("开始运单预警通知配置短信消息,短信模版code:{},请求参数：{}",smsTemplateType.getCode(),JSON.toJSONString(param));
        Message body = MessageBuilder.withBody(JSON.toJSONString(new MqWrapper<>(param)).getBytes()).build();
        rabbitTemplate.send(NOTICE_SEND_SMS_QUEUE_EXCHANGE,NOTICE_SEND_SMS_QUEUE_ROUTING_KEY, body);
        log.info("结束运单预警通知配置短信消息,短信模版code:{},", smsTemplateType.getCode());
    }


    private List<String> getTargets(int code){
        return vehicleWarnUserDao.listAllEnable()
                .stream()
                .filter(item -> JSONUtil.toList(item.getWarnTypeJson(), Integer.class).contains(code))
                .map(VehicleWarnUser::getMobile).collect(Collectors.toList());
    }

    //构建站内信中的内容，替换变量
    private static String replaceContent(String content,List<String> list){
        int listSize = 0;
        int times = countCharTimes(content, "%s");
        if(CollectionUtils.isNotEmpty(list)){
            listSize = list.size();
        }
        if(times != listSize){
            log.error("替换的变量和字符串中需要的变量数量不一致");
            return null;
        }
        return String.format(content, list.toArray());
    }


    //查找字符在字符串出现的次数
    public static int countCharTimes(String mainStr,String subStr){
        // 声明一个要返回的变量
        int count = 0;
        // 声明一个初始的下标，从初始位置开始查找
        int index = 0;
        // 获取主数据的长度
        int mainStrLength = mainStr.length();
        // 获取要查找的数据长度
        int subStrLength = subStr.length();
        // 如果要查找的数据长度大于主数据的长度则返回0
        if (subStrLength > mainStrLength){
            return 0;
        }
        // 循环使用indexOf查找出现的下标，如果出现一次则count++

        while ((index = mainStr.indexOf(subStr, index)) != -1) {
            count++;
            index += subStrLength;
        }
        return count;
    }
}
