package com.njcn.csharmonic.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.njcn.csdevice.api.SmsSendFeignClient;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.cssystem.api.AppMsgSetFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xy
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SmsNotificationService {
    private final AppMsgSetFeignClient appMsgSetFeignClient;
    private final UserFeignClient userFeignClient;
    private final SmsSendFeignClient smsSendFeignClient;
    @Value("${msg.msg_sign:南京灿能电力}")
    private String msgSign;

    @Async("smsNotificationExecutor")
    public void asyncSendSmsNotification(String deviceId
            , DevDetailDTO devDetailDto
            , LocalDateTime eventTime
            , Double amplitude
            , Double persistTime) {
        List<String> userIdList = appMsgSetFeignClient.queryUserIdsByDeviceId(deviceId).getData();
        if (CollectionUtil.isNotEmpty(userIdList)) {
            List<User> userList = userFeignClient.getUserListByIds(userIdList).getData();
            if (CollectionUtil.isNotEmpty(userList)) {
                List<User> userList1 = userList.stream()
                        .filter(item -> StrUtil.isNotBlank(item.getPhone()) && Objects.equals(item.getSmsNotice(), 1))
                        .collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(userList1)) {
                    String msgContent = "【" + msgSign + "】" + devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName()
                            + "于" + eventTime.format(DatePattern.NORM_DATETIME_MS_FORMATTER) + "发生暂降事件"
                            + "，特征幅值：" + amplitude + "%"
                            + "，持续时间：" + persistTime + "s";
                    userList1.forEach(item -> {
                        smsSendFeignClient.sendSmsSimple(item.getPhone(), msgContent, "verify_code");
                    });
                }
            }
        }
    }
}
