/*
*  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 me.zhengjie.modules.dm.modbus.device.service.impl;

import me.zhengjie.modules.dm.modbus.device.domain.DmModbusDevice;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.dm.modbus.device.repository.DmModbusDeviceRepository;
import me.zhengjie.modules.dm.modbus.device.service.DmModbusDeviceService;
import me.zhengjie.modules.dm.modbus.device.service.dto.DmModbusDeviceDto;
import me.zhengjie.modules.dm.modbus.device.service.dto.DmModbusDeviceQueryCriteria;
import me.zhengjie.modules.dm.modbus.device.service.mapstruct.DmModbusDeviceMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

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

/**
* @website https://el-admin.vip
* @description 服务实现
* @author wld
* @date 2022-05-20
**/
@Service
@RequiredArgsConstructor
public class DmModbusDeviceServiceImpl implements DmModbusDeviceService {

    private final DmModbusDeviceRepository dmModbusDeviceRepository;
    private final DmModbusDeviceMapper dmModbusDeviceMapper;

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

    @Override
    public List<DmModbusDeviceDto> queryAll(DmModbusDeviceQueryCriteria criteria){
        return dmModbusDeviceMapper.toDto(dmModbusDeviceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DmModbusDeviceDto findById(Long deviceId) {
        DmModbusDevice dmModbusDevice = dmModbusDeviceRepository.findById(deviceId).orElseGet(DmModbusDevice::new);
        ValidationUtil.isNull(dmModbusDevice.getDeviceId(),"DmModbusDevice","deviceId",deviceId);
        return dmModbusDeviceMapper.toDto(dmModbusDevice);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmModbusDeviceDto create(DmModbusDevice resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setDeviceId(snowflake.nextId()); 
        return dmModbusDeviceMapper.toDto(dmModbusDeviceRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DmModbusDevice resources) {
        DmModbusDevice dmModbusDevice = dmModbusDeviceRepository.findById(resources.getDeviceId()).orElseGet(DmModbusDevice::new);
        ValidationUtil.isNull( dmModbusDevice.getDeviceId(),"DmModbusDevice","id",resources.getDeviceId());
        dmModbusDevice.copy(resources);
        dmModbusDeviceRepository.save(dmModbusDevice);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long deviceId : ids) {
            dmModbusDeviceRepository.deleteById(deviceId);
        }
    }

    @Override
    public void download(List<DmModbusDeviceDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmModbusDeviceDto dmModbusDevice : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("设备名称", dmModbusDevice.getDeviceName());
            map.put("从站站号", dmModbusDevice.getSalveStationNumber());
            map.put("采集通讯站号", dmModbusDevice.getStationNumber());
            map.put("采集通讯请求帧间隔(毫秒)", dmModbusDevice.getRequestFrameInterval());
            map.put("采集通讯写值刷新间隔(毫秒)", dmModbusDevice.getWriteValueRefreshInterval());
            map.put("采集通讯2字节整数顺序", dmModbusDevice.getTwoByteIntOrder());
            map.put("采集通讯4字节整数顺序", dmModbusDevice.getFourByteIntOrder());
            map.put("单精度浮点数顺序", dmModbusDevice.getFloatOrder());
            map.put("批量传输模拟量组包间隔", dmModbusDevice.getAnalogQuantityGroupPacketInterval());
            map.put("批量传输模拟量组包最大长度", dmModbusDevice.getAnalogQuantityGroupPacketMaxlength());
            map.put("批量传输数字量组包间隔", dmModbusDevice.getDigitalQuantityGroupPacketInterval());
            map.put("批量传输数字量组包最大长度", dmModbusDevice.getDigitalQuantityGroupPacketMaxlength());
            map.put("关联的通道channel_id", dmModbusDevice.getChannelId());
            map.put("创建人", dmModbusDevice.getCreateBy());
            map.put("更新人", dmModbusDevice.getUpdateBy());
            map.put("创建时间", dmModbusDevice.getCreateTime());
            map.put("更新时间", dmModbusDevice.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Long getModbusCount(Integer status) {
        return dmModbusDeviceRepository.getModbusCount(status);
    }

    @Override
    public int updateDeviceStatus(Timestamp timestamp, Long deviceId, String status) {
        return dmModbusDeviceRepository.updateDeviceStatus(timestamp,deviceId,status);
    }
}