package com.ho.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ho.business.entity.Device;
import com.ho.business.entity.DeviceTypeCol;
import com.ho.business.entity.VirtualDeviceCol;
import com.ho.business.mapper.VirtualDeviceColMapper;
import com.ho.business.service.DeviceService;
import com.ho.business.service.DeviceTypeColService;
import com.ho.business.service.VirtualDeviceColService;
import com.ho.business.vo.req.VirtualDeviceColReq;
import com.ho.business.vo.req.deviceModel.SynchronousReqVo;
import com.ho.business.vo.resp.VirtualDeviceColResp;
import com.ho.business.vo.resp.point.Point;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.hutool.core.text.StrPool.UNDERLINE;

@Service
@Slf4j
public class VirtualDeviceColServiceImpl implements VirtualDeviceColService {

    @Autowired
    VirtualDeviceColMapper virtualDeviceColMapper;

    @Autowired
    DeviceService deviceService;

    @Autowired
    DeviceTypeColService deviceTypeColService;

    @Override
    public PageResult<VirtualDeviceColResp> getPageList(VirtualDeviceColReq vo) {
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        VirtualDeviceCol virtualDeviceCol = new VirtualDeviceCol();
        BeanUtils.copyProperties(vo, virtualDeviceCol);
        List<VirtualDeviceColResp> virtualDeviceCols = virtualDeviceColMapper.selectVirtualDeviceCol(virtualDeviceCol);
        return PageUtils.getPageResult(new PageInfo<>(virtualDeviceCols));
    }

    @Override
    public List<VirtualDeviceColResp> getList(VirtualDeviceCol vo) {
        List<VirtualDeviceColResp> virtualDeviceCols = virtualDeviceColMapper.selectVirtualDeviceCol(vo);
        return virtualDeviceCols;
    }

    @Override
    public int insertVirtualDeviceCol(VirtualDeviceCol virtualDeviceCol) {
        int result = virtualDeviceColMapper.insertVirtualDeviceCol(virtualDeviceCol);
        return result;
    }

    @Override
    public int insertList(List<VirtualDeviceCol> virtualDeviceColList) {
        int result = virtualDeviceColMapper.insertList(virtualDeviceColList);
        return result;
    }

    @Override
    public int updateVirtualDeviceCol(VirtualDeviceCol virtualDeviceCol) {
        int result = virtualDeviceColMapper.updateVirtualDeviceCol(virtualDeviceCol);
        return result;
    }

    @Override
    public int updateList(List<VirtualDeviceCol> virtualDeviceColList) {
        int result = virtualDeviceColMapper.updateList(virtualDeviceColList);
        return result;
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        int result = virtualDeviceColMapper.deleteByPrimaryKey(id);
        return result;
    }

    @Override
    public int deleteByList(List<Integer> ids) {
        int result = virtualDeviceColMapper.deleteByList(ids);
        return result;
    }

    @Override
    public VirtualDeviceCol selectByColId(Point point) {
        return virtualDeviceColMapper.selectByColId(point);
    }

    @Override
    public void getSynchronousV(SynchronousReqVo vo) {
        List<VirtualDeviceCol> virtualDeviceColList = null;
        //根据模板模板电站Id，查出虚拟设备的已关联数据
        VirtualDeviceCol record = new VirtualDeviceCol();
        record.setStationId(vo.getModelStationId());
        List<VirtualDeviceColResp> virtualDeviceColRespList = virtualDeviceColMapper.selectVirtualDeviceCol(record);
        //再根据要同步的电站Id查询出自己的设备数据(先查询到该电站下的虚拟设备，将数据以fromid进行过滤（重复数据），
        Device device = new Device();
        device.setStationId(vo.getStationId());
        device.setVirtual(CommonConstant.ONE);
        List<Device> list = deviceService.getRealDevice(device);
        Map<Integer, List<Device>> collect = list.stream().collect(Collectors.groupingBy(Device::getFromId));
        // 根据SrcId和电站Id进行查询，拿到deviceType,在根据deviceType去device_type_col表中进行查询)
        for (Map.Entry<Integer, List<Device>> entry : collect.entrySet()) {
            System.out.println("key:" + entry.getKey() + ";value:" + entry.getValue());
            Device deviceValue = deviceService.selectByStationIdAndSrcId(vo.getModelStationId(), entry.getKey());
            if (deviceValue == null || deviceValue.getDeviceType() == null) {
                continue;
            }
            virtualDeviceColList = new ArrayList<>();
            String deviceType = deviceValue.getDeviceType().replace(UNDERLINE + vo.getModelStationId(), UNDERLINE + vo.getStationId());
            List<DeviceTypeCol> deviceTypeCols = deviceTypeColService.selectByDeviceType(deviceType,null);
            Map<String, List<DeviceTypeCol>> modelMap = deviceTypeCols.stream().collect(Collectors.groupingBy(DeviceTypeCol::getCol));
            //根据col进行数据对比，更换device_col_id
            for (VirtualDeviceColResp virtualDeviceColResp : virtualDeviceColRespList) {
                if (modelMap.get(virtualDeviceColResp.getCol()) != null) {
                    VirtualDeviceCol virtualDeviceCol = new VirtualDeviceCol();
                    //取到Id set到（modelDeviceColRespVo）
                    List<DeviceTypeCol> deviceTypeCols1 = modelMap.get(virtualDeviceColResp.getCol());
                    virtualDeviceCol.setDeviceColId(deviceTypeCols1.get(0).getId());
                    virtualDeviceCol.setStationId(vo.getStationId());
                    virtualDeviceCol.setSrcId(virtualDeviceColResp.getSrcId());
                    virtualDeviceCol.setCol(virtualDeviceColResp.getCol());
                    virtualDeviceCol.setColName(virtualDeviceColResp.getColName());
                    virtualDeviceCol.setType(virtualDeviceColResp.getType());
                    virtualDeviceColList.add(virtualDeviceCol);
                }
            }
            //先判断是否有重复数据，防止二次入库
            record.setStationId(vo.getStationId());
            List<VirtualDeviceColResp> virtualList = virtualDeviceColMapper.selectVirtualDeviceCol(record);
            if (!virtualList.isEmpty()) {
                //如果存在，全部删掉
                List<Integer> ids = virtualList.stream().map(VirtualDeviceColResp::getId).collect(Collectors.toList());
                virtualDeviceColMapper.deleteByList(ids);
            }
            log.info("同步虚拟设备virtualDeviceColList {}", virtualDeviceColList.size());
            if (!virtualDeviceColList.isEmpty()) {
                virtualDeviceColMapper.insertList(virtualDeviceColList);
            }
        }
    }

    @Override
    public List<VirtualDeviceCol> selectBySrcId(Integer stationId, List<Integer> collect,String type) {
        return virtualDeviceColMapper.selectBySrcId(stationId, collect,type);
    }
}
