package org.dromara.zjk.event.custom;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.resource.api.RemoteSmsService;
import org.dromara.zjk.domain.ZjkSmsInfo;
import org.dromara.zjk.domain.dto.SmsSendYsdDto;
import org.dromara.zjk.event.SmsSendEvent;
import org.dromara.zjk.mapper.ZjkSmsInfoMapper;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : yanguohua
 * @version : 1.0
 * @date : 2024/11/7 16:24
 */
@Component
@Slf4j
public class SmsSendListener implements ApplicationListener<SmsSendEvent> {
    @DubboReference(timeout = 60000)
    private RemoteSmsService remoteSmsService;
    @Resource
    private ZjkSmsInfoMapper zjkSmsInfoMapper;

    @Override
    public void onApplicationEvent(SmsSendEvent event) {
        SmsSendYsdDto smsSendYsdDto = event.getSmsSendYsdDto();
        sendSms(smsSendYsdDto);

    }

    /**
     * 保存系统日志记录
     */
    @EventListener
    public void sendSms(SmsSendYsdDto dto) {
        List<Map<String, String>> data = dto.getReceiveUserTels().stream().map(item -> {
            Map<String, String> stringStringMap = remoteSmsService.sendYsdSingleSms(dto.getContent(), item);
            return stringStringMap;
        }).collect(Collectors.toList());
        //数据库信息回改
        handleData(data, dto);
    }

    private void handleData(List<Map<String, String>> data, SmsSendYsdDto dto) {
        //发送短信后的数据入库
        List<ZjkSmsInfo> collect = data.stream().map(item -> {
            //更新短信发送状态，发送返回码，发送次数
            String status = item.get("status");
            ZjkSmsInfo smsInfo = zjkSmsInfoMapper.selectSmsByBatchAndTel(dto.getBatchNum(), item.get("tel"));
            smsInfo.setSendStatus(Integer.valueOf(status));
            smsInfo.setStatusId(item.get("resultId"));
            smsInfo.setReturnMsg(item.get("msg"));
            smsInfo.setReturnCode(item.get("msg"));
            smsInfo.setSendNum(1);
            return smsInfo;
        }).collect(Collectors.toList());
        zjkSmsInfoMapper.updateById(collect);
    }
}
