package com.ozs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ozs.common.constant.UserConstants;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.bean.BeanUtils;
import com.ozs.common.utils.stateSecrets.SM4Utils;
import com.ozs.entity.MonitorSystem;
import com.ozs.entity.MsgAlarm;
import com.ozs.entity.SkynetHeartbeatLog;
import com.ozs.entity.SvcAddress;
import com.ozs.entity.VehiclePosition;
import com.ozs.entity.vo.AlarmHeartbeatLog;
import com.ozs.entity.vo.MonitorSystemVo;
import com.ozs.mapper.AlarmHeartbeatLogMapper;
import com.ozs.mapper.MonitorSystemMapper;
import com.ozs.mapper.MsgAlarmMapper;
import com.ozs.mapper.SvcAddressMapper;
import com.ozs.service.MonitorSystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wyy
 * @subject
 * @creat 2023/7/25
 */
@Service
public class MonitorSystemServiceImpl extends ServiceImpl<MonitorSystemMapper, MonitorSystem> implements MonitorSystemService {

    @Autowired
    private MonitorSystemMapper monitorSystemMapper;
    @Autowired
    private SvcAddressMapper svcAddressMapper;
    public static final String KEY = "58792429c08c43e9";
    @Autowired
    private MsgAlarmMapper msgAlarmMapper;

    @Override
    public int insertMonitorSystem(MonitorSystem monitorSystem) {
        int row = monitorSystemMapper.insertMonitorSystem(monitorSystem);
        Integer grantType = 1;

        SvcAddress svc = new SvcAddress();
        svc.setClientId(monitorSystem.getClientId());
        svc.setClientSecret(SM4Utils.encryptData_ECB(monitorSystem.getClientSecret(), KEY));//正式环境
        svc.setGrantType(grantType);
        svc.setEnv(2);
        int row1 = svcAddressMapper.insert(svc);
        SvcAddress svc1 = new SvcAddress();
        svc1.setClientId(monitorSystem.getClientId());
        svc1.setClientSecret(SM4Utils.encryptData_ECB(monitorSystem.getTestSecret(), KEY));//测试环境
        svc1.setGrantType(grantType);
        svc1.setEnv(1);
        int row2 = svcAddressMapper.insert(svc1);
        return row + row1 + row2;
    }

    @Override
    public void deleteByIds(Long[] ids) {
        for (Long id : ids) {
            MonitorSystem monitorSystem = monitorSystemMapper.selectById(id);
            LambdaQueryWrapper<SvcAddress> wrapper = new LambdaQueryWrapper<SvcAddress>();
            wrapper.eq(SvcAddress::getClientId, monitorSystem.getClientId());
            svcAddressMapper.delete(wrapper);
            monitorSystemMapper.deleteById(id);
        }
    }

    @Override
    public int updateMonitorSystem(MonitorSystem monitorSystem) {
        //原
        MonitorSystem monitor = monitorSystemMapper.selectById(monitorSystem.getId());
        List<SvcAddress> list = svcAddressMapper.svcList(monitor.getClientId());
        if (!CollectionUtils.isEmpty(list) && Objects.nonNull(list.get(0))) {
            list.forEach(l -> {
                if (l.getEnv().equals(1)) {//测试环境
                    monitor.setTestSecret(SM4Utils.decryptData_ECB(l.getClientSecret(), KEY));
//                } else if (l.getEnv().equals(2)) {//正式环境
//                    monitor.setClientSecret(SM4Utils.decryptData_ECB(l.getClientSecret(), KEY));
                }
            });
        }
        Integer grantType = 1;
        int row1 = 0;
        int row2 = 0;
        if (!monitorSystem.getClientId().equals(monitor.getClientId()) || !monitorSystem.getTestSecret().equals(monitor.getTestSecret())) {//客户端编号或者正式环境密钥或者测试环境密钥改变
            LambdaQueryWrapper<SvcAddress> wrapper = new LambdaQueryWrapper<SvcAddress>();
            wrapper.eq(SvcAddress::getClientId, monitor.getClientId());
            svcAddressMapper.delete(wrapper);

//            SvcAddress svc = new SvcAddress();
//            svc.setClientId(monitorSystem.getClientId());
//            svc.setClientSecret(SM4Utils.encryptData_ECB(monitorSystem.getClientSecret(), KEY));//正式环境
//            svc.setGrantType(grantType);
//            svc.setEnv(2);
//            row1 = svcAddressMapper.insert(svc);
            SvcAddress svc1 = new SvcAddress();
            svc1.setClientId(monitorSystem.getClientId());
            svc1.setClientSecret(SM4Utils.encryptData_ECB(monitorSystem.getTestSecret(), KEY));//测试环境
            svc1.setGrantType(grantType);
            svc1.setEnv(1);
            row2 = svcAddressMapper.insert(svc1);
        }
        int row = monitorSystemMapper.updateById(monitorSystem);
        return row + row1 + row2;
    }

    @Override
    public String checkClientIdUnique(MonitorSystem monitorSystem) {
        Long id = StringUtils.isNull(monitorSystem.getId()) ? -1L : monitorSystem.getId();
        MonitorSystem monitor = monitorSystemMapper.checkClientIdUnique(monitorSystem.getClientId());
        if (StringUtils.isNotNull(monitor) && monitor.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkSystemOnline(MonitorSystem monitorSystem) {
        Long id = StringUtils.isNull(monitorSystem.getId()) ? -1L : monitorSystem.getId();
        MonitorSystem monitor = monitorSystemMapper.checkSystemOnline(id);
        if (StringUtils.isNotNull(monitor.getStatus()) && monitor.getStatus().equals(1)) {
            return UserConstants.EXCEPTION;
        }
        return UserConstants.NORMAL;
    }

    @Override
    public MonitorSystem getMonitorSystem(Long id) {
        MonitorSystem monitor = monitorSystemMapper.checkSystemOnline(id);
        List<SvcAddress> list = svcAddressMapper.svcList(monitor.getClientId());
        if (!CollectionUtils.isEmpty(list) && Objects.nonNull(list.get(0))) {
            list.forEach(l -> {
                if (l.getEnv().equals(1)) {//测试环境
                    monitor.setTestSecret(SM4Utils.decryptData_ECB(l.getClientSecret(), KEY));
                } else if (l.getEnv().equals(2)) {//正式环境
                    monitor.setClientSecret(SM4Utils.decryptData_ECB(l.getClientSecret(), KEY));
                }
            });
        }
        return monitor;
    }

    @Override
    public IPage<MonitorSystemVo> pageList(MonitorSystemVo monitorSystemVo) {
        LambdaQueryWrapper<MonitorSystem> wrapper = new LambdaQueryWrapper<MonitorSystem>();
        wrapper.like(!Objects.isNull(monitorSystemVo.getMonitorSystemName()), MonitorSystem::getMonitorSystemName, monitorSystemVo.getMonitorSystemName());
        wrapper.eq(!Objects.isNull(monitorSystemVo.getStatus()), MonitorSystem::getStatus, monitorSystemVo.getStatus());
        int pageNum = Integer.parseInt(monitorSystemVo.getPageNum().toString());
        int pageSize = Integer.parseInt(monitorSystemVo.getPageSize().toString());
        com.github.pagehelper.Page<MonitorSystem> page = PageHelper
                .startPage(pageNum, pageSize).doSelectPage(() -> monitorSystemMapper.selectList(wrapper));
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<MonitorSystemVo> pageR =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
        if (!ObjectUtils.isEmpty(page) && page.getResult().size() > 0) {
            List<MonitorSystemVo> dto1 = page.getResult().stream().map(o -> {
                MonitorSystemVo monitorSystemVo1 = new MonitorSystemVo();
                BeanUtils.copyProperties(o, monitorSystemVo1);
                return monitorSystemVo1;
            }).collect(Collectors.toList());
            pageR.setRecords(dto1);
            pageR.setTotal(page.getTotal());
        }
        return pageR;
    }

    @Override
    public MonitorSystem selectByClientId(String clientId) {
        LambdaQueryWrapper<MonitorSystem> wrapper = new LambdaQueryWrapper<MonitorSystem>();
        wrapper.eq(MonitorSystem::getClientId, clientId);
        MonitorSystem monitorSystem = monitorSystemMapper.selectOne(wrapper);
        return monitorSystem;
    }

    @Override
    public Map<String, Object> monitorSystem() {
        // Map<String, Object> mapCount = monitorSystemMapper.monitorSystemCount();
        Map<String, Object> mapCount = new HashMap<>();
        List<MonitorSystem> monitorSystemList = monitorSystemMapper.monitorSystemList();
        int offlineMonitor = 0;
        int onlineMonitor = 0;
        for (MonitorSystem monitorSystem : monitorSystemList) {
            if (!StringUtils.isEmptySunhh(monitorSystem) && !StringUtils.isEmptySunhh(monitorSystem.getClientId())) {
                AlarmHeartbeatLog alarmHeartbeatLog = monitorSystemMapper.selectAlarmHeartbeatLogByClientId(monitorSystem.getClientId());
                if (StringUtils.isEmptySunhh(alarmHeartbeatLog)) {
                    offlineMonitor++;
                    monitorSystem.setStatus(2);
                } else {
                    long timeNow = System.currentTimeMillis();
                    long createTime = alarmHeartbeatLog.getCreateTime().getTime();
                    long thereHourMillis = 60 * 60 * 1000 * 3;
                    long timeNew = timeNow - thereHourMillis;
                    if (timeNew <= createTime) {
                        onlineMonitor++;
                        monitorSystem.setStatus(1);
                    } else {
                        offlineMonitor++;
                        monitorSystem.setStatus(2);
                    }
                }
                monitorSystemMapper.updateById(monitorSystem);
            }
        }
        mapCount.put("monitorSystemList", monitorSystemList);
        mapCount.put("countAllMonitor", monitorSystemList.size());
        mapCount.put("offlineMonitor", offlineMonitor);
        mapCount.put("onlineMonitor", onlineMonitor);
        return mapCount;
    }

    @Override
    public IPage listToPage(List list, int pageNum, int pageSize) {
        List pageList = new ArrayList<>();
        int curIdx = pageNum > 1 ? (pageNum - 1) * pageSize : 0;
        for (int i = 0; i < pageSize && curIdx + i < list.size(); i++) {
            pageList.add(list.get(curIdx + i));
        }
        IPage page = new Page<>(pageNum, pageSize);
        page.setRecords(pageList);
        page.setTotal(list.size());
        return page;
    }

    @Override
    public List<MonitorSystem> monitorSystemPage(MonitorSystemVo monitorSystemVo) {
        List<MonitorSystem> monitorSystemList = monitorSystemMapper.monitorSystemPage(monitorSystemVo);
        for (MonitorSystem monitorSystem : monitorSystemList) {
            LambdaQueryWrapper<MonitorSystem> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(MonitorSystem::getClientId,monitorSystem.getClientId());
            MonitorSystem monitorSystem1 = monitorSystemMapper.selectOne(queryWrapper);
            if (!ObjectUtils.isEmpty(monitorSystem1.getStatus())) {
                monitorSystem.setStatusName(monitorSystem1.getStatus() == 1 ? "已联通" : "未联通");
            }
            if (!ObjectUtils.isEmpty(monitorSystem1.getMonitorSystemName())) {
                monitorSystem.setMonitorSystemName(monitorSystem1.getMonitorSystemName());
            }
            QueryWrapper<MsgAlarm> wrapper = new QueryWrapper<>();
            wrapper.eq("source",monitorSystem.getClientId());
            List<MsgAlarm> msgAlarms = msgAlarmMapper.selectList(wrapper);
            List<MsgAlarm> collect = msgAlarms.stream().filter(msgAlarm -> msgAlarm.getIsRelease() == 2).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(msgAlarms)) {
                monitorSystem.setCountAll(msgAlarms.size());
            }
            if (!ObjectUtils.isEmpty(collect)) {
                monitorSystem.setFailureToReport(collect.size());
            }
        }
        return monitorSystemList;
    }
}
