/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.youchain.jamod.service.impl;

import com.youchain.jamod.domain.ModbusInfo;
import com.youchain.jamod.repository.ModbusInfoRepository;
import com.youchain.jamod.service.ModbusInfoService;
import com.youchain.jamod.service.dto.ModbusInfoDto;
import com.youchain.jamod.service.dto.ModbusInfoQueryCriteria;
import com.youchain.jamod.service.mapstruct.ModbusInfoMapper;
import com.youchain.utils.FileUtil;
import com.youchain.utils.PageUtil;
import com.youchain.utils.QueryHelp;
import com.youchain.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author huojin
* @date 2025-03-21
**/
@Service
@RequiredArgsConstructor
public class ModbusInfoServiceImpl implements ModbusInfoService {

    private final ModbusInfoRepository modbusInfoRepository;
    private final ModbusInfoMapper modbusInfoMapper;

    @Override
    public Map<String,Object> queryAll(ModbusInfoQueryCriteria criteria, Pageable pageable){
        Page<ModbusInfo> page = modbusInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(modbusInfoMapper::toDto));
    }

    @Override
    public List<ModbusInfoDto> queryAll(ModbusInfoQueryCriteria criteria){
        return modbusInfoMapper.toDto(modbusInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public ModbusInfoDto findById(Integer id) {
        ModbusInfo modbusInfo = modbusInfoRepository.findById(id).orElseGet(ModbusInfo::new);
        ValidationUtil.isNull(modbusInfo.getId(),"ModbusInfo","id",id);
        return modbusInfoMapper.toDto(modbusInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModbusInfoDto create(ModbusInfo resources) {
        return modbusInfoMapper.toDto(modbusInfoRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ModbusInfo resources) {
        ModbusInfo modbusInfo = modbusInfoRepository.findById(resources.getId()).orElseGet(ModbusInfo::new);
        ValidationUtil.isNull( modbusInfo.getId(),"ModbusInfo","id",resources.getId());
        modbusInfo.copy(resources);
        modbusInfoRepository.save(modbusInfo);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            modbusInfoRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ModbusInfoDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ModbusInfoDto modbusInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("Modbus 设备的名称，用于直观识别设备", modbusInfo.getDeviceName());
            map.put("Modbus 设备的 IP 地址", modbusInfo.getDeviceIp());
            map.put("Modbus 设备的端口号", modbusInfo.getDevicePort());
            map.put("Modbus 设备的详细描述信息，如设备用途、型号等", modbusInfo.getDeviceDescription());
            map.put("Modbus 数据的类型", modbusInfo.getDataType());
            map.put("批量读取数据的起始地址", modbusInfo.getStartAddress());
            map.put("批量读取的数据长度", modbusInfo.getDataLength());
            map.put("批量读取的数据值集合，以特定格式存储，如逗号分隔的字符串", modbusInfo.getDataValues());
            map.put("最后一次读取该数据的时间", modbusInfo.getLastReadTime());
            map.put("最后一次修改该数据的时间", modbusInfo.getLastModifyTime());
            map.put("数据的版本号，每次数据修改时版本号递增，用于数据追溯", modbusInfo.getDataVersion());
            map.put("数据的状态，normal 表示正常，abnormal 表示异常，warning 表示警告，maintenance 表示维护中", modbusInfo.getDataStatus());
            map.put("是否触发报警，TRUE 表示触发，FALSE 表示未触发", modbusInfo.getAlarmStatus());
            map.put("记录设备连接状态，TRUE 表示连接成功，FALSE 表示连接失败", modbusInfo.getIsConnected());
            map.put("异常重试次数", modbusInfo.getMaxRetries());
            map.put("状态：1启用、0禁用", modbusInfo.getEnabled());
            map.put("报错原因", modbusInfo.getDescription());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}