package com.njcn.cloud.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.cloud.mapper.AppDevMsgMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.cloud.pojo.dto.AppDevMsg;
import com.njcn.cloud.pojo.vo.DevComTJ;
import com.njcn.cloud.pojo.vo.DevMsgDetailInfo;
import com.njcn.cloud.service.IAppDevMsgService;
import com.njcn.device.pq.api.GeneralDeviceInfoClient;
import com.njcn.device.pq.pojo.param.OnlineRateParam;
import com.njcn.device.pq.pojo.po.TopMsgPO;
import com.njcn.device.pq.pojo.vo.DevDetail;
import com.njcn.web.pojo.param.BaseParam;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 终端消息 服务实现类
 * </p>
 *
 * @author wr
 * @since 2023-11-07
 */
@Service
@RequiredArgsConstructor
public class AppDevMsgServiceImpl extends ServiceImpl<AppDevMsgMapper, AppDevMsg> implements IAppDevMsgService {

    private final GeneralDeviceInfoClient generalDeviceInfoClient;

    @Override
    public Page<AppDevMsg> deviceMsgList(BaseParam param) {
        Page<AppDevMsg> page = this.page(new Page<>(param.getPageNum(), param.getPageSize()), new LambdaQueryWrapper<AppDevMsg>()
                .eq(AppDevMsg::getUserIndex, param.getSearchValue())
                .orderByDesc(AppDevMsg::getTimeId)
        );
        return page;
    }

    @Override
    public DevMsgDetailInfo deviceList(BaseParam param) {
        DevMsgDetailInfo dev = new DevMsgDetailInfo();
        int count = this.count(
                new LambdaQueryWrapper<AppDevMsg>()
                        .eq(AppDevMsg::getUserIndex, param.getSearchValue())
                        .eq(AppDevMsg::getState, 0)

        );
        dev.setUnstate(count);
        Page<AppDevMsg> page = this.page(new Page(param.getPageNum(), param.getPageSize()),
                new LambdaQueryWrapper<AppDevMsg>()
                        .eq(AppDevMsg::getUserIndex, param.getSearchValue())
                        .orderByDesc(AppDevMsg::getTimeId)
        );
        List<AppDevMsg> records = page.getRecords();
        List<DevMsgDetailInfo.Unstate> info = new ArrayList<>();
        if (CollUtil.isNotEmpty(records)) {
            List<String> topIds = records.stream().map(AppDevMsg::getTopId).collect(Collectors.toList());
            OnlineRateParam top = new OnlineRateParam();
            top.setIds(topIds);
            top.setType(0);
            List<TopMsgPO> data = generalDeviceInfoClient.getTopMsgInfoByIds(top).getData();
            Map<String, TopMsgPO> topMap = data.stream().collect(Collectors.toMap(TopMsgPO::getTopId, Function.identity()));
            DevMsgDetailInfo.Unstate msg;
            for (AppDevMsg record : records) {
                if (topMap.containsKey(record.getTopId())) {
                    TopMsgPO topMsgPO = topMap.get(record.getTopId());
                    msg = new DevMsgDetailInfo.Unstate();
                    msg.setDevmsgIndex(record.getDevmsgIndex());
                    msg.setComoutDesc(topMsgPO.getComOutDesc());
                    msg.setAlarmDesc(topMsgPO.getAlarmDesc());
                    msg.setTopId(topMsgPO.getTopId());
                    msg.setDevIndex(topMsgPO.getDevId());
                    msg.setGdName(topMsgPO.getCityName());
                    msg.setBdzName(topMsgPO.getSubName());
                    msg.setDevName(topMsgPO.getDeviceName());
                    msg.setIp(topMsgPO.getIp());
                    LocalDateTime time = LocalDateTimeUtil.parse(topMsgPO.getTime(), DatePattern.NORM_DATE_PATTERN);
                    msg.setTimeID(time);
                    msg.setAllNum(topMsgPO.getAlarmCount() + topMsgPO.getComOutCount());
                    msg.setAlarmNum(topMsgPO.getAlarmCount());
                    msg.setComOutNum(topMsgPO.getComOutCount());
                    msg.setFlowNum(topMsgPO.getFlowValue());
                    msg.setState(record.getState());
                    info.add(msg);
                }
            }
        }
        Page<DevMsgDetailInfo.Unstate> pageEvent = BeanUtil.copyProperties(page, Page.class);
        pageEvent.setRecords(info);
        dev.setPage(pageEvent);
        return dev;
    }

    @Override
    public Boolean updateDevMsgState(List<String> ids) {
        return this.update(new LambdaUpdateWrapper<AppDevMsg>()
                .set(AppDevMsg::getState, 1)
                .in(AppDevMsg::getDevmsgIndex, ids)
        );
    }

    @Override
    public DevComTJ getDevComTJ(String deptId) {
        DevComTJ devComTJ = new DevComTJ();
        //根据部门获取监测id
        List<String> userLine = generalDeviceInfoClient.deptGetRunDev(deptId).getData();
        List<DevDetail> devDetail = generalDeviceInfoClient.getDevInfoByIds(userLine).getData();
        if (CollUtil.isNotEmpty(devDetail)) {
            devComTJ.setAllDevCount(devDetail.size());
            devComTJ.setErrDevCount(Math.toIntExact(devDetail.stream().filter(x -> x.getComFlag() == 0).count()));
        } else {
            devComTJ.setAllDevCount(0);
            devComTJ.setErrDevCount(0);

        }
        return devComTJ;
    }

    @Override
    public List<DevDetail> getDevComInfo(String deptId) {
        List<String> userLine = generalDeviceInfoClient.deptGetRunDev(deptId).getData();
        List<DevDetail> devDetail = generalDeviceInfoClient.getDevInfoByIds(userLine).getData();
        devDetail.sort(Collections.reverseOrder(Comparator.comparing(DevDetail::getComFlag)));
        return devDetail;
    }


}
