package org.dromara.zjk.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.core.domain.R;
import org.dromara.common.encrypt.utils.EncryptUtils;
import org.dromara.zjk.domain.ZjkExpert;
import org.dromara.zjk.domain.ZjkSmsInfo;
import org.dromara.zjk.domain.ZjkSmsTemplate;
import org.dromara.zjk.domain.dto.*;
import org.dromara.zjk.enums.SmsUpContentEnum;
import org.dromara.zjk.event.SmsUpEvent;
import org.dromara.zjk.mapper.ZjkSmsInfoMapper;
import org.dromara.zjk.service.IZjkExpertService;
import org.dromara.zjk.service.ZjkSmsInfoService;
import org.dromara.zjk.service.ZjkSmsTemplateService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author EDY
 * @description 针对表【zjk_sms_info】的数据库操作Service实现
 * @createDate 2024-12-13 11:22:06
 */
@Service
@Slf4j
public class ZjkSmsInfoServiceImpl extends ServiceImpl<ZjkSmsInfoMapper, ZjkSmsInfo>
    implements ZjkSmsInfoService {
    @Resource
    private ZjkSmsTemplateService zjkSmsTemplateService;
    @Resource
    private ApplicationEventPublisher eventPublisher;
    @Resource
    private IZjkExpertService zjkExpertService;

    @Override
    public R<Void> sendSms(SmsSendDto dto) {
        //1进行发送短信内容渲染
        ZjkSmsTemplate tml = zjkSmsTemplateService.getById(dto.getTemplateId());
        if (tml == null || tml.getTmlContent() == null) {
            return R.fail("短信模板未配置，请先配置短信模板！");
        }
        if (dto.getParamJson() == null) {
            return R.fail("短信内容参数为空！");
        }
        List<Long> receiveUserIds = dto.getReceiveUserIds();
        if (CollectionUtils.isEmpty(receiveUserIds)) {
            return R.fail("短信接收人参数为空！");
        }
        if (dto.getBatchType() == null) {
            return R.fail("短信批次类型（1：群发；0单发）参数为空！");
        }
        // 生成短信发送批次号
        String batchNum = RandomUtil.randomString(32);
        String content = renderSmsTemplate(tml.getTitle(), tml.getTmlContent(), dto.getParamJson());
        //2进行数据落库
        List<ZjkExpert> experts = zjkExpertService.getPhonesById(receiveUserIds);
        if (!CollectionUtils.isEmpty(experts)) {
            List<ZjkSmsInfo> smsInfos = receiveUserIds.stream().map(item -> {
                String contact = experts.stream().filter(ze -> ze.getUserId().equals(item)).findFirst().get().getContact();
                ZjkSmsInfo info = new ZjkSmsInfo();
                info.setSendBy(dto.getSendBy());
                info.setReceiveUserId(item);
                info.setBatchNum(batchNum);
                info.setSmsContent(content);
                info.setParamJson(dto.getParamJson().toJSONString());
                info.setTemplateId(dto.getTemplateId());
                //TODO 短信发送暂定我的手机
                info.setReceivePhone("18171199132");
                return info;
            }).collect(Collectors.toList());
            baseMapper.insert(smsInfos);
            //3进行短信事件发布
            List<String> phones = smsInfos.stream().map(ZjkSmsInfo::getReceivePhone).collect(Collectors.toList());
            SmsSendYsdDto sendDto = new SmsSendYsdDto();
            sendDto.setContent(content);
            sendDto.setBatchNum(batchNum);
            sendDto.setReceiveUserTels(phones);

            eventPublisher.publishEvent(sendDto);
        }
        //发布后调用起定时任务去刷新短信状态
        //更新短信发送状态
        return R.ok();
    }
//    deliver=VEQ=|1019383343238|13211111111|2021-12-28 13:43:03|500191232
//    多条:deliver=VEQ=|1019383343238|13211111111|2021-12-28 13:43:03|500191232;VEQ=|1019383343238|13211111111|2021-12-28 13:43:03|500191232
   /* @Override
    @Async
    public void handleUpData(SmsUpDto dto) {
        SmsUpInfoDto smsUpInfoDto = new SmsUpInfoDto();
        List<SmsUpEventDto> result = new ArrayList<>();
        String deliver = dto.getDeliver();
        log.info("===》上行短信内容为:"+deliver);
        if(!StringUtils.isEmpty(deliver)){
            String[] nn = deliver.split(";");
            result = Arrays.stream(nn).map(item -> handleSingle(deliver)).collect(Collectors.toList());
        }
        smsUpInfoDto.setInfo(result);
        eventPublisher.publishEvent(smsUpInfoDto);

    }

    private SmsUpEventDto handleSingle( String deliver) {
        SmsUpEventDto smsUpEventDto = new SmsUpEventDto();

        String[] split = deliver.split("\\|");
        //处理内容
        String content = split[0];
        if(StringUtils.isNotBlank(content)){
            content = EncryptUtils.decryptByBase64(content);
            smsUpEventDto.setContent(content);
            if(SmsUpContentEnum.CQQR.getCode().equalsIgnoreCase(content)){
                smsUpEventDto.setUpType(1);
            }
        }

        //处理手机号用户信息
        String tel = split[2];
        if(StringUtils.isNotBlank(tel)){
           Long userId= zjkExpertService.getUserIdByPhone(tel);
            smsUpEventDto.setUserId(userId);
            smsUpEventDto.setMobile(tel);
        }

        //处理发送时间
        String sendTime = split[3];
        if(StringUtils.isNotBlank(tel)){
        smsUpEventDto.setSendTime(DateUtil.parse(sendTime));
        }
        String loginName = split[4];
        smsUpEventDto.setLoginName(loginName);
        return smsUpEventDto;
    }

    public String renderSmsTemplate(String title, String templateContent, JSONObject data) {
        // 遍历JSONObject中的所有键值对，并替换模板中的变量
        for (String key : data.keySet()) {
            templateContent = templateContent.replace("{{" + key + "}}", data.getString(key) == null ? "" : data.getString(key));
        }
        return title + templateContent;
    }
*/
public String renderSmsTemplate(String title, String templateContent, JSONObject data) {
    // 遍历JSONObject中的所有键值对，并替换模板中的变量
    for (String key : data.keySet()) {
        templateContent = templateContent.replace("{{" + key + "}}", data.getString(key) == null ? "" : data.getString(key));
    }
    return title + templateContent;
}
    @Override
    @Async
    public void handleUpData(SmsUpDto dto) {
        SmsUpInfoDto smsUpInfoDto = new SmsUpInfoDto();
        List<SmsUpEventDto> result = new ArrayList<>();
        String deliver = dto.getDeliver();
        log.info("===》上行短信内容为:"+deliver);
        if(!StringUtils.isEmpty(deliver)){
            String[] nn = deliver.split(";");
            result = Arrays.stream(nn)
                .map(this::handleSingle)
                .filter(item -> item != null)
                .collect(Collectors.toList());
        }
        smsUpInfoDto.setInfo(result);
        eventPublisher.publishEvent(new SmsUpEvent(this, smsUpInfoDto));
    }

    private SmsUpEventDto handleSingle(String deliver) {
        String[] split = deliver.split("\\|");
        if (split.length < 5) {
            log.warn("上行短信格式异常，字段不足：{}", deliver);
            return null;
        }
        SmsUpEventDto smsUpEventDto = new SmsUpEventDto();

        String content = split[0];
        if (StringUtils.isNotBlank(content)) {
            content = EncryptUtils.decryptByBase64(content);
            smsUpEventDto.setContent(content);
        }

        // 设置默认 upType，避免 null
        smsUpEventDto.setUpType(0);

        // 特殊内容时覆盖默认值
        if (SmsUpContentEnum.CQQR.getCode().equalsIgnoreCase(content)) {
            smsUpEventDto.setUpType(1);
        }

        String tel = split[2];
        if (StringUtils.isNotBlank(tel)) {
            Long userId = zjkExpertService.getUserIdByPhone(tel);
            smsUpEventDto.setUserId(userId);
            smsUpEventDto.setMobile(tel);
        }

        String sendTime = split[3];
        if (StringUtils.isNotBlank(sendTime)) {
            smsUpEventDto.setSendTime(DateUtil.parse(sendTime));
        }

        String loginName = split[4];
        smsUpEventDto.setLoginName(loginName);

        return smsUpEventDto;
    }


    public static void main(String[] args) {
        String ss="deliver=VEQ=|1019383343238|13211111111|2021-12-28 13:43:03|500191232";
        System.out.println(EncryptUtils.encryptByBase64("CQQR"));
        String dd="VEQ=|1019383343238|13211111111|2021-12-28 13:43:03|500191232;VEQ=|1019383343238|13211111111|2021-12-28 13:43:03|500191232\n";
        String[] nn = dd.split(";");
        Arrays.stream(nn).forEach(item->{
            String[] split = item.split("\\|");
            System.out.println(DateUtil.parse(split[3]));
        });


    }
}




