package com.njcn.cssystem.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.njcn.access.pojo.dto.NoticeUserDto;
import com.njcn.access.utils.SendMessageUtil;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.api.DeviceMessageFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.api.EventLogsFeignClient;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.po.CsEventSendMsg;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.cssystem.api.AppMsgSetFeignClient;
import com.njcn.cssystem.pojo.param.MsgSendParam;
import com.njcn.cssystem.service.ICsEventUserService;
import com.njcn.cssystem.service.IMsgSendService;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.user.api.SmsSendFeignClient;
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.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 徐扬
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class IMsgSendServiceImpl implements IMsgSendService {

    private final DeviceMessageFeignClient deviceMessageFeignClient;
    private final EquipmentFeignClient equipmentFeignClient;
    private final EpdFeignClient epdFeignClient;
    private final ICsEventUserService csEventUserService;
    private final SendMessageUtil sendMessageUtil;
    private final EventLogsFeignClient eventLogsFeignClient;
    private final CsLedgerFeignClient csLedgerFeignClient;
    private final AppMsgSetFeignClient appMsgSetFeignClient;
    private final UserFeignClient userFeignClient;
    private final SmsSendFeignClient smsSendFeignClient;
    private final CsLedgerFeignClient csLedgerFeignclient;
    @Value("${msg.msg_sign:南京灿能电力}")
    private String msgSign;

    @Override
    @Async("eventNotificationExecutor")
    public void sendAppNotification(MsgSendParam param) {
        int code;
        List<User> users = new ArrayList<>();
        List<String> eventUser;
        List<String> devCodeList;
        List<String> userList = new ArrayList<>();
        List<CsEventSendMsg> csEventSendMsgList = new ArrayList<>();
        NoticeUserDto noticeUserDto = new NoticeUserDto();
        NoticeUserDto.Payload payload = new NoticeUserDto.Payload();
        String content = null;
        List<CsEventUserPO> result = new ArrayList<>();
        //获取设备类型 true:治理设备 false:其他类型的设备
        boolean devModel = equipmentFeignClient.judgeDevModel(param.getNDid()).getData();
        if (devModel) {
            DevDetailDTO devDetailDto = csLedgerFeignClient.queryDevDetail(param.getDevId()).getData();
            //事件处理
            if (param.getEventType() == 1){
                param.setEventName(epdFeignClient.findByName(param.getEventName()).getData().getShowName());
                switch (param.getType()) {
                    case "1":
                        code = 3;
                        //设备自身事件 不推送给用户，推送给业务管理
                        eventUser = deviceMessageFeignClient.getEventUserByDeviceId(param.getDevId(),false).getData();
                        if (CollectionUtil.isNotEmpty(eventUser)) {
                            eventUser.forEach(item->{
                                CsEventUserPO csEventUser = new CsEventUserPO();
                                csEventUser.setUserId(item);
                                csEventUser.setStatus(0);
                                csEventUser.setEventId(param.getId());
                                result.add(csEventUser);
                            });

                            DeviceMessageParam param1 = new DeviceMessageParam();
                            param1.setUserList(eventUser);
                            param1.setEventType(2);
                            users = deviceMessageFeignClient.getSendUserByType(param1).getData();
                            if (CollectionUtil.isNotEmpty(users)){
                                for (User user : users){
                                    userList.add(user.getDevCode());
                                }
                                noticeUserDto.setPushClientId(userList);
                                noticeUserDto.setTitle("运行事件");
                            }
                        }
                        break;
                    case "2":
                        code = 0;
                        //暂态事件
                        eventUser = deviceMessageFeignClient.getEventUserByDeviceId(param.getDevId(),true).getData();
                        if (CollectionUtil.isNotEmpty(eventUser)) {
                            eventUser.forEach(item->{
                                CsEventUserPO csEventUser = new CsEventUserPO();
                                csEventUser.setUserId(item);
                                csEventUser.setStatus(0);
                                csEventUser.setEventId(param.getId());
                                result.add(csEventUser);
                            });
                            DeviceMessageParam param1 = new DeviceMessageParam();
                            param1.setUserList(eventUser);
                            param1.setEventType(0);
                            users = deviceMessageFeignClient.getSendUserByType(param1).getData();
                            if (CollectionUtil.isNotEmpty(users)){
                                devCodeList = users.stream().map(User::getDevCode).distinct().collect(Collectors.toList());
                                noticeUserDto.setPushClientId(devCodeList);
                                noticeUserDto.setTitle("暂态事件");
                                content = devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName()
                                        + "于" + param.getEventTime().format(DatePattern.NORM_DATETIME_MS_FORMATTER) + "发生暂态事件，事件类型："
                                        + param.getEventName()
                                        + "，特征幅值：" + param.getAmplitude() + "%"
                                        + "，持续时间：" + param.getPersistTime() + "s"
                                        + "，落点区域：" + (Objects.isNull(param.getDropZone())?"未知":param.getDropZone());
                            }
                        }
                        break;
//                    case "3":
//                        code = 1;
//                        //稳态事件
//                        eventUser = getEventUser(devId,true);
//                        if (CollectionUtil.isNotEmpty(eventUser)) {
//                            eventUser.forEach(item->{
//                                CsEventUserPO csEventUser = new CsEventUserPO();
//                                csEventUser.setUserId(item);
//                                csEventUser.setStatus(0);
//                                csEventUser.setEventId(id);
//                                result.add(csEventUser);
//                            });
//                            users = getSendUser(eventUser,1);
//                            if (CollectionUtil.isNotEmpty(users)){
//                                devCodeList = users.stream().map(User::getDevCode).distinct().collect(Collectors.toList());
//                                noticeUserDto.setPushClientId(devCodeList);
//                                noticeUserDto.setTitle("稳态事件");
//                            }
//                        }
//                        break;
                    default:
                        code = 0;
                        break;
                }
                //获取台账信息
                if (Objects.isNull(content)) {
                    content = devDetailDto.getEngineeringName()
                            + "-" + devDetailDto.getProjectName()
                            + "-" + devDetailDto.getEquipmentName()
                            + "于" + param.getEventTime().format(DatePattern.NORM_DATETIME_MS_FORMATTER)
                            + "发生" + param.getEventName();
                }
                noticeUserDto.setContent(content);
                payload.setType(code);
                payload.setPath("/pages/index/message1?type="+payload.getType());
                noticeUserDto.setPayload(payload);
            }
//            //告警处理
//            else if (eventType == 2){
//                switch (type) {
//                    case "1":
//                        //Ⅰ级告警 不推送给用户，推送给业务管理
//                        eventUser = getEventUser(devId,false);
//                        if (CollectionUtil.isNotEmpty(eventUser)) {
//                            eventUser.forEach(item->{
//                                CsEventUserPO csEventUser = new CsEventUserPO();
//                                csEventUser.setUserId(item);
//                                csEventUser.setStatus(0);
//                                csEventUser.setEventId(id);
//                                result.add(csEventUser);
//                            });
//                            users = getSendUser(eventUser,3);
//                            if (CollectionUtil.isNotEmpty(users)){
//                                eventName = epdFeignClient.findByName(eventName).getData().getShowName();
//                                devCodeList = users.stream().map(User::getDevCode).distinct().collect(Collectors.toList());
//                                noticeUserDto.setPushClientId(devCodeList);
//                            }
//                        }
//                        break;
//                    case "2":
//                        eventName = epdFeignClient.findByName(eventName).getData().getShowName();
//                    case "3":
//                        //Ⅱ、Ⅲ级告警推送相关用户及业务管理员
//                        eventUser = getEventUser(devId,true);
//                        if (CollectionUtil.isNotEmpty(eventUser)) {
//                            eventUser.forEach(item->{
//                                CsEventUserPO csEventUser = new CsEventUserPO();
//                                csEventUser.setUserId(item);
//                                csEventUser.setStatus(0);
//                                csEventUser.setEventId(id);
//                                result.add(csEventUser);
//                            });
//                            users = getSendUser(eventUser,3);
//                            if (CollectionUtil.isNotEmpty(users)){
//                                devCodeList = users.stream().map(User::getDevCode).distinct().collect(Collectors.toList());
//                                noticeUserDto.setPushClientId(devCodeList);
//                            }
//                        }
//                        break;
//                    default:
//                        break;
//                }
//                noticeUserDto.setTitle("告警事件");
//                DevDetailDTO devDetailDto = csLedgerFeignclient.queryDevDetail(devId).getData();
//                content = devDetailDto.getEngineeringName() + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName() + "于" + eventTime.format(DatePattern.NORM_DATETIME_MS_FORMATTER) + "发生告警,告警信息:" + eventName;
//                noticeUserDto.setContent(content);
//                payload.setType(3);
//                payload.setPath("/pages/message/message?type="+payload.getType());
//                noticeUserDto.setPayload(payload);
//            }
            if (CollectionUtil.isNotEmpty(noticeUserDto.getPushClientId())) {
                List<String> filteredList = noticeUserDto.getPushClientId().stream()
                        .filter(Objects::nonNull)
                        .distinct()
                        .collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(filteredList)) {
                    noticeUserDto.setPushClientId(filteredList);
                    sendMessageUtil.sendEventToUser(noticeUserDto);
                }
            }
            //记录推送日志
            for (User item : users) {
                CsEventSendMsg csEventSendMsg = new CsEventSendMsg();
                csEventSendMsg.setUserId(item.getId());
                csEventSendMsg.setEventId(param.getId());
                csEventSendMsg.setSendTime(LocalDateTime.now());
                if (Objects.isNull(item.getDevCode())){
                    csEventSendMsg.setStatus(0);
                    csEventSendMsg.setRemark("用户设备识别码为空");
                } else {
                    csEventSendMsg.setDevCode(item.getDevCode());
                    csEventSendMsg.setStatus(1);
                }
                csEventSendMsgList.add(csEventSendMsg);
            }
            eventLogsFeignClient.addLogs(csEventSendMsgList);
            //事件用户关系入库
            if (CollectionUtil.isNotEmpty(result)){
                csEventUserService.saveBatch(result);
            }
        }
    }

    @Override
    @Async("smsNotificationExecutor")
    public void sendSmsForDipEvent(MsgSendParam param) {
        try {
            List<String> userIdList = appMsgSetFeignClient.queryUserIdsByDeviceId(param.getDevId()).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)) {
                        DevDetailDTO devDetailDto = csLedgerFeignclient.queryDevDetail(param.getDevId()).getData();
                        String msgContent = "【" + msgSign + "】" + devDetailDto.getEngineeringName()
                                + "-" + devDetailDto.getProjectName() + "-" + devDetailDto.getEquipmentName()
                                + "于" + param.getEventTime().format(DatePattern.NORM_DATETIME_MS_FORMATTER) + "发生暂降事件"
                                + "，特征幅值：" + param.getAmplitude() + "%"
                                + "，持续时间：" + param.getPersistTime() + "s"
                                + "，落点区域：" + (Objects.isNull(param.getDropZone())?"未知":param.getDropZone());
                        userList1.forEach(item -> {
                            try {
                                smsSendFeignClient.sendSmsSimple(item.getPhone(), msgContent, "verify_code");
                            } catch (Exception e) {
                                log.error("发送短信失败，手机号: {}", item.getPhone(), e);
                            }
                        });
                    }
                }
            }
        } catch (Exception e) {
            log.error("异步发送暂降事件短信失败，设备ID: {}", param.getDevId(), e);
        }
    }
}
