package com.ho.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ho.business.entity.DeviceTypeCol;
import com.ho.business.feignclient.FlowFeignClient;
import com.ho.business.mapper.DeviceMapper;
import com.ho.business.mapper.DeviceTypeColMapper;
import com.ho.business.service.DeviceTypeColService;
import com.ho.business.vo.DeviceTypeList;
import com.ho.business.vo.req.DeviceTypeColImportVO;
import com.ho.business.vo.req.DeviceTypeColReqVO;
import com.ho.business.vo.req.deviceModel.SynchronousReqVo;
import com.ho.business.vo.req.deviceTypeCol.DeviceTypeColQueryVo;
import com.ho.business.vo.resp.deviceTypeCol.DeviceTypeColCountResp;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.util.PageResult;
import com.ho.common.tools.util.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Description 针对表【device_type_col】的数据库操作Service实现类
 * @Author xueweizhi
 * @Date 2023/3/16 14:09
 */
@Service
@Slf4j
public class DeviceTypeColServiceImpl implements DeviceTypeColService {

    @Autowired
    DeviceTypeColMapper deviceTypeColMapper;

    @Autowired
    DeviceMapper deviceMapper;

    @Autowired
    FlowFeignClient flowFeignClient;

    @Override
    public int insertList(List<DeviceTypeColImportVO> srcList, Integer groupId) {
        //以deviceType分组
        Map<String, List<DeviceTypeColImportVO>> mapList = srcList.stream().filter(s -> s.getDeviceType() != null).collect(Collectors.groupingBy(i -> i.getDeviceType()));
        List<DeviceTypeColImportVO> list = null;
        DeviceTypeCol deviceTypeCol = null;
        for (Map.Entry<String, List<DeviceTypeColImportVO>> src : mapList.entrySet()) {
            //已经存在的
            List<DeviceTypeCol> isSaveList = deviceTypeColMapper.selectByDeviceType(src.getKey(),null);
            Map<String, DeviceTypeCol> isSaveMap = isSaveList.stream().collect(Collectors.toMap(k -> k.getDeviceType() + "_" + k.getCol(), DeviceTypeCol -> DeviceTypeCol));

            Map<Integer, List<DeviceTypeCol>> addMap = new HashMap<>();
            Map<Integer, List<DeviceTypeCol>> updateMap = new HashMap<>();
            List<DeviceTypeCol> deviceTypeColList = new ArrayList<>();
            List<DeviceTypeCol> updateList = new ArrayList<>();
            list = src.getValue();
            Integer num = 1;
            Integer updateNum = 1;
            for (DeviceTypeColImportVO deviceTypeColImportVO : list) {
                deviceTypeCol = isSaveMap.get(deviceTypeColImportVO.getDeviceType() + "_" + deviceTypeColImportVO.getCol());
                //走更新
                if (null != deviceTypeCol) {
                    BeanUtil.copyProperties(deviceTypeColImportVO, deviceTypeCol);
                    deviceTypeCol.setIsShow(CommonConstant.ONE);
                    updateList.add(deviceTypeCol);
                    if (updateList.size() % 999 == 998) {
                        updateList = new ArrayList<>();
                        updateNum++;
                    }
                    updateMap.put(updateNum, updateList);
                } else {
                    //走新增
                    deviceTypeCol = new DeviceTypeCol();
                    BeanUtil.copyProperties(deviceTypeColImportVO, deviceTypeCol);
                    deviceTypeCol.setIsShow(CommonConstant.ONE);
                    deviceTypeColList.add(deviceTypeCol);
                    if (deviceTypeColList.size() % 999 == 998) {
                        deviceTypeColList = new ArrayList<>();
                        num++;
                    }
                    addMap.put(num, deviceTypeColList);
                }
            }
            for (Map.Entry<Integer, List<DeviceTypeCol>> m : addMap.entrySet()) {
                deviceTypeColMapper.insertList(m.getValue());
                syncData(groupId, m);
            }
            for (Map.Entry<Integer, List<DeviceTypeCol>> m : updateMap.entrySet()) {
                deviceTypeColMapper.updateList(m.getValue());
                syncData(groupId, m);
            }

        }
        return 0;
    }

    /**
     * 同步数据（告警定义、告警配置）
     *
     * @param groupId
     * @param m
     */
    private void syncData(Integer groupId, Map.Entry<Integer, List<DeviceTypeCol>> m) {
        List<DeviceTypeCol> value = m.getValue();
        List<DeviceTypeCol> collect = value.stream().filter(i -> i.getAlarmLevel() != null).collect(Collectors.toList());
        //增加同步功能
        //先同步告警定义
        flowFeignClient.deviceColDefine(collect);
        //同步告警配置（区分遥测遥信 1遥信 2遥测）
        DeviceTypeList deviceTypeList = new DeviceTypeList();
        deviceTypeList.setList(collect);
        deviceTypeList.setGroupId(groupId);
        flowFeignClient.syncAlarmConfig(deviceTypeList);
    }

    @Override
    public List<DeviceTypeCol> selectByDeviceType(String deviceType,String lang) {
        List<DeviceTypeCol> deviceTypeColList = deviceTypeColMapper.selectByDeviceType(deviceType,lang);
        return deviceTypeColList;
    }

    @Override
    public DeviceTypeCol selectById(Integer id) {
        DeviceTypeCol deviceTypeCol = deviceTypeColMapper.selectById(id);
        return deviceTypeCol;
    }

    @Override
    public DeviceTypeCol selectTypeAndCol(String col, String deviceType,String lang) {
        DeviceTypeCol deviceTypeCol = deviceTypeColMapper.selectTypeAndCol(col, deviceType,lang);
        return deviceTypeCol;
    }

    @Override
    public List<DeviceTypeCol> selectDeviceTypeColList(String deviceType, List<String> collect,String lang) {
        List<DeviceTypeCol> deviceTypeCols = deviceTypeColMapper.selectSameCol(deviceType, collect,lang);
        return deviceTypeCols;
    }

    @Override
    public Integer selectCountByDeviceType(DeviceTypeCol deviceTypeCol) {
        Integer count = deviceTypeColMapper.selectCountByDeviceType(deviceTypeCol);
        return count;
    }

    @Override
    public PageResult<DeviceTypeCol> selectPage(DeviceTypeColQueryVo vo) {
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<DeviceTypeCol> deviceTypeCols = selectDeviceTypeCol(vo);
        PageResult pageResult = PageUtils.getPageResult(new PageInfo<>(deviceTypeCols));
        return pageResult;
    }

    @Override
    public List<DeviceTypeCol> selectDeviceTypeCol(DeviceTypeColQueryVo vo) {
        DeviceTypeColReqVO deviceTypeColReqVO = new DeviceTypeColReqVO();
        List<DeviceTypeCol> deviceTypeCols = new ArrayList<>();
        //全部为空的时候，根据电站id去匹配
        if(null == vo.getDeviceType()){
            deviceTypeCols = deviceTypeColMapper.selectDimType(CommonConstant.JOIN_STATION_ID+vo.getStationId());
        }else{
            List<String> typelist = new ArrayList<>();
            typelist.add(vo.getDeviceType());
            deviceTypeColReqVO.setDeviceTypeList(typelist);
            deviceTypeColReqVO.setName(vo.getName());
            deviceTypeCols = deviceTypeColMapper.selectByDeviceTypeList(deviceTypeColReqVO);
        }
        return deviceTypeCols;
    }

    @Override
    public void syPointTable(SynchronousReqVo vo) {
        //判断同步的电站是否存在点表
        String type = CommonConstant.JOIN_STATION_ID + vo.getStationId();
        List<DeviceTypeCol> list1 = deviceTypeColMapper.selectDimType(type);
        if (!list1.isEmpty()) {
            List<Integer> collect = list1.stream().map(DeviceTypeCol::getId)
                    .collect(Collectors.toList());
            deviceTypeColMapper.deleteBatchDevice(collect);
        }
        String deviceType = CommonConstant.JOIN_STATION_ID + vo.getModelStationId();
        List<DeviceTypeCol> list = deviceTypeColMapper.selectDimType(deviceType);
        List<DeviceTypeCol> desList = new ArrayList<>();
        Map<Integer, List<DeviceTypeCol>> addMap = new HashMap<>();
        Integer num = 1;
        for (DeviceTypeCol deviceTypeCol : list) {
            if (deviceTypeCol.getDeviceType() != null) {
                String newDeviceType = deviceTypeCol.getDeviceType();
                int index = newDeviceType.lastIndexOf("_");
                deviceTypeCol.setDeviceType(newDeviceType.substring(0, index + 1) + vo.getStationId());
                deviceTypeCol.setId(null);
                desList.add(deviceTypeCol);
                if (desList.size() % 999 == 998) {
                    desList = new ArrayList<>();
                    num++;
                }
                addMap.put(num,desList);
            }
        }
        for (Map.Entry<Integer, List<DeviceTypeCol>> m : addMap.entrySet()) {
            try{
                int result = deviceTypeColMapper.insertList(m.getValue());
                log.info("执行插入结果{}",result);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<String> selectType(Set<String> collect) {
        List<String> strings = deviceTypeColMapper.selectType(collect);
        return strings;
    }

    @Override
    public List<DeviceTypeCol> selectAllData(Integer colBeginId, Integer allNum) {
        List<DeviceTypeCol> list = deviceTypeColMapper.selectAllData(colBeginId,allNum);
        return list;
    }

    @Override
    public List<DeviceTypeCol> selectByBatchId(List<Integer> deviceTypeIdList) {
        List<DeviceTypeCol> list = deviceTypeColMapper.selectByBatchId(deviceTypeIdList);
        return list;
    }

    @Override
    public List<DeviceTypeColCountResp> countByDeviceType(List<String> typeList) {
        List<DeviceTypeColCountResp> result = deviceTypeColMapper.countByDeviceType(typeList);
        return result;
    }
}
