package org.dromara.zjk.event.custom;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.zjk.domain.ZjkSmsUp;
import org.dromara.zjk.domain.dto.SmsUpEventDto;
import org.dromara.zjk.domain.dto.SmsUpInfoDto;
import org.dromara.zjk.enums.SmsUpTypeEnum;
import org.dromara.zjk.event.SmsUpEvent;
import org.dromara.zjk.mapper.ZjkSmsUpMapper;
import org.dromara.zjk.service.IZjkExpertItemService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

/**
 * @author : yanguohua
 * @version : 1.0
 * @date : 2024/11/7 16:24
 */
@Component
@Slf4j
public class SmsUpListener implements ApplicationListener<SmsUpEvent> {

    @Resource
    private ZjkSmsUpMapper zjkSmsUpMapper;
    @Resource
    private IZjkExpertItemService zjkExpertItemService;

    @Override
    public void onApplicationEvent(SmsUpEvent event) {
        SmsUpInfoDto smsUpInfoDto = event.getSmsUpInfoDto();
        handleSms(smsUpInfoDto);

    }

    /**
     * 保存系统日志记录
     */
    @EventListener
    public void handleSms(SmsUpInfoDto smsUpInfoDto) {
        List<SmsUpEventDto> smsUpEventDtos = smsUpInfoDto.getInfo();
        //1.上行短信入库
        if (!CollectionUtils.isEmpty(smsUpEventDtos)) {
            List<ZjkSmsUp> collect = smsUpEventDtos.stream().map(item -> {
                ZjkSmsUp zjkSmsUp = new ZjkSmsUp();
                BeanUtil.copyProperties(item, zjkSmsUp);
                zjkSmsUp.setCreateTime(new Date());
                return zjkSmsUp;
            }).collect(Collectors.toList());
            zjkSmsUpMapper.insert(collect);
        }
        //2.处理相关业务
        for (SmsUpEventDto smsUpEventDto : smsUpEventDtos) {
            // 类型为专家申请的时候进行处理
            if (smsUpEventDto.getUpType().equals(SmsUpTypeEnum.ZJSQ.getCode())){
                zjkExpertItemService.handleSmsReply(smsUpEventDto);
            }
        }
    }

}
