package com.njcn.csharmonic.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import com.njcn.access.pojo.dto.NoticeUserDto;
import com.njcn.access.utils.SendMessageUtil;
import com.njcn.csdevice.api.DeviceMessageFeignClient;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.user.pojo.po.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

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

/**
 * @author xy
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AppNotificationService {

    private final EpdFeignClient epdFeignClient;
    private final SendMessageUtil sendMessageUtil;
    private final DeviceMessageFeignClient deviceMessageClient;
    private final CsEventUserPOService csEventUserPOService;

    @Async("eventNotificationExecutor")
    public void asyncSaveEventUserAndNotify(String eventId
            , List<String> eventUser
            , DevDetailDTO devDetailDto
            , LocalDateTime time
            , Integer eventType
            , Double amplitude
            , Double persistTime) {
        NoticeUserDto noticeUserDto = new NoticeUserDto();
        NoticeUserDto.Payload payload = new NoticeUserDto.Payload();
        List<CsEventUserPO> result = new ArrayList<>();

        eventUser.forEach(item -> {
            CsEventUserPO csEventUser = new CsEventUserPO();
            csEventUser.setUserId(item);
            csEventUser.setStatus(0);
            csEventUser.setEventId(eventId);
            result.add(csEventUser);
        });

        DeviceMessageParam param = new DeviceMessageParam();
        param.setUserList(eventUser);
        param.setEventType(0);
        List<User> users = deviceMessageClient.getSendUserByType(param).getData();
        if (CollectionUtil.isNotEmpty(users)) {
            List<String> devCodeList = users.stream().map(User::getDevCode).distinct().collect(Collectors.toList());
            noticeUserDto.setPushClientId(devCodeList);
            noticeUserDto.setTitle("暂态事件");
        }

        String eventName = epdFeignClient.findByName(getTag(eventType)).getData().getShowName();
        String content = devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName()
                + "于" + time.format(DatePattern.NORM_DATETIME_MS_FORMATTER) + "发生暂态事件，事件类型："
                + eventName
                + "，特征幅值：" + amplitude + "%"
                + "，持续时间：" + persistTime + "s";
        noticeUserDto.setContent(content);
        payload.setType(0);
        payload.setPath("/pages/index/message1?type=" + payload.getType());
        noticeUserDto.setPayload(payload);

        if (CollectionUtil.isNotEmpty(noticeUserDto.getPushClientId())) {
            List<String> filteredList = noticeUserDto.getPushClientId().stream()
                    .filter(s -> s != null && !s.isEmpty())
                    .distinct()
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(filteredList)) {
                noticeUserDto.setPushClientId(filteredList);
                sendMessageUtil.sendEventToUser(noticeUserDto);
            }
        }
        if (CollectionUtil.isNotEmpty(result)) {
            csEventUserPOService.saveBatch(result);
        }
    }

    public String getTag(Integer type) {
        String tag;
        switch (type) {
            case 1:
                tag = "Evt_Sys_DipStr";
                break;
            case 2:
                tag = "Evt_Sys_SwlStr";
                break;
            case 3:
                tag = "Evt_Sys_IntrStr";
                break;
            case 4:
                tag = "Transient";
                break;
            default:
                tag = "Un_Know";
                break;
        }
        return tag;
    }
}
