/*
*  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.data.service.impl;

import me.zhengjie.modules.dm.modbus.data.domain.DmModbusData;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.dm.modbus.data.repository.DmModbusDataRepository;
import me.zhengjie.modules.dm.modbus.data.service.DmModbusDataService;
import me.zhengjie.modules.dm.modbus.data.service.dto.DmModbusDataDto;
import me.zhengjie.modules.dm.modbus.data.service.dto.DmModbusDataQueryCriteria;
import me.zhengjie.modules.dm.modbus.data.service.mapstruct.DmModbusDataMapper;
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.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-21
**/
@Service
@RequiredArgsConstructor
public class DmModbusDataServiceImpl implements DmModbusDataService {

    private final DmModbusDataRepository dmModbusDataRepository;
    private final DmModbusDataMapper dmModbusDataMapper;

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

    @Override
    public List<DmModbusDataDto> queryAll(DmModbusDataQueryCriteria criteria){
        return dmModbusDataMapper.toDto(dmModbusDataRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DmModbusDataDto findById(Long dataId) {
        DmModbusData dmModbusData = dmModbusDataRepository.findById(dataId).orElseGet(DmModbusData::new);
        ValidationUtil.isNull(dmModbusData.getDataId(),"DmModbusData","dataId",dataId);
        return dmModbusDataMapper.toDto(dmModbusData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmModbusDataDto create(DmModbusData resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setDataId(snowflake.nextId()); 
        return dmModbusDataMapper.toDto(dmModbusDataRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DmModbusData resources) {
        DmModbusData dmModbusData = dmModbusDataRepository.findById(resources.getDataId()).orElseGet(DmModbusData::new);
        ValidationUtil.isNull( dmModbusData.getDataId(),"DmModbusData","id",resources.getDataId());
        dmModbusData.copy(resources);
        dmModbusDataRepository.save(dmModbusData);
    }

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

    @Override
    public void download(List<DmModbusDataDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmModbusDataDto dmModbusData : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("采集端（硬件）点名", dmModbusData.getCallTheRoll());
            map.put("采集端描述", dmModbusData.getDescribe());
            map.put("采集端数据类型", dmModbusData.getDataType());
            map.put("采集端寄存器类型", dmModbusData.getHardwareRegisterType());
            map.put("采集端寄存器地址", dmModbusData.getHardwareRegisterAddress());
            map.put("采集端启用取位用逗号分隔", dmModbusData.getIsFetchBit());
            map.put("采集端关联线性转换id", dmModbusData.getLinearConversionId());
            map.put("转发端(软件)寄存器类型", dmModbusData.getSoftwareRegisterType());
            map.put("转发端(软件)寄存器地址", dmModbusData.getSoftwareRegisterAddress());
            map.put("创建人", dmModbusData.getCreateBy());
            map.put("更新人", dmModbusData.getUpdateBy());
            map.put("创建时间", dmModbusData.getCreateTime());
            map.put("更新时间", dmModbusData.getUpdateTime());
            map.put("关联分组id", dmModbusData.getGroupId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}