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

import me.zhengjie.ykt.domain.DmRoomDevice;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.ykt.repository.DmRoomDeviceRepository;
import me.zhengjie.ykt.service.DmRoomDeviceService;
import me.zhengjie.ykt.service.dto.DmRoomDeviceDto;
import me.zhengjie.ykt.service.dto.DmRoomDeviceQueryCriteria;
import me.zhengjie.ykt.service.mapstruct.DmRoomDeviceMapper;
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 org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zhirong
* @date 2021-11-19
**/
@Service
@RequiredArgsConstructor
public class DmRoomDeviceServiceImpl implements DmRoomDeviceService {

    private final DmRoomDeviceRepository dmRoomDeviceRepository;
    private final DmRoomDeviceMapper dmRoomDeviceMapper;


    @Override
    public List<Map<Object, Object>> importExcel(MultipartFile file) {
        List<Map<Object, Object>> list = OfficeUtils.readExcelContentz(file);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 将list里面的数据转成实体然后插入
        for(int i = 0;i < list.size();i ++) {
            Map<Object, Object> map = list.get(i);
            DmRoomDevice dmRoomDevice = new DmRoomDevice();
            dmRoomDevice.setCode(map.get("code").toString());
            dmRoomDevice.setName(map.get("name").toString());
            dmRoomDevice.setBuildAddress(map.get("buildAddress").toString());
            try {
                String str = map.get("registTime").toString();
                Date date = sdf.parse(map.get("registTime").toString());
                dmRoomDevice.setRegistTime(new Timestamp(sdf.parse(map.get("registTime").toString()).getTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            dmRoomDevice.setStatus(map.get("status").toString());
            dmRoomDevice.setRemark(map.get("remark").toString());
            dmRoomDevice.setCreateTime(new Timestamp(System.currentTimeMillis()));
            dmRoomDevice.setUpdateTime(new Timestamp(System.currentTimeMillis()));

            create(dmRoomDevice);
        }
        return list;
    }

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

    @Override
    public List<DmRoomDeviceDto> queryAll(DmRoomDeviceQueryCriteria criteria){
        return dmRoomDeviceMapper.toDto(dmRoomDeviceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DmRoomDeviceDto findById(Long id) {
        DmRoomDevice dmRoomDevice = dmRoomDeviceRepository.findById(id).orElseGet(DmRoomDevice::new);
        ValidationUtil.isNull(dmRoomDevice.getId(),"DmRoomDevice","id",id);
        return dmRoomDeviceMapper.toDto(dmRoomDevice);
    }

    @Override
    public List<DmRoomDevice> getDmRoomDeviceByUser(DmRoomDevice dmRoomDevice) {
        return dmRoomDeviceRepository.getDmRoomDeviceByUser(dmRoomDevice.getCode(), dmRoomDevice.getBuildAddress(),dmRoomDevice.getDeviceType());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmRoomDeviceDto create(DmRoomDevice resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId()); 
        return dmRoomDeviceMapper.toDto(dmRoomDeviceRepository.save(resources));
    }

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

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

    @Override
    public void download(List<DmRoomDeviceDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmRoomDeviceDto dmRoomDevice : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("设备编号", dmRoomDevice.getCode());
            map.put("设备名称", dmRoomDevice.getName());
            map.put("设备安装位置", dmRoomDevice.getBuildAddress());
            map.put("设备状态", dmRoomDevice.getStatus());
            map.put("登记时间", dmRoomDevice.getRegistTime());
            map.put("备注", dmRoomDevice.getRemark());
//            map.put("创建者", dmRoomDevice.getCreateBy());
//            map.put("更新者", dmRoomDevice.getUpdateBy());
//            map.put("创建时间", dmRoomDevice.getCreateTime());
//            map.put("更新时间", dmRoomDevice.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<DmRoomDevice> findByCode(String code,String doorId) {
        return dmRoomDeviceRepository.findByCode(code,doorId);
    }

    @Override
    public List<DmRoomDevice> findByCode(String code) {
        return dmRoomDeviceRepository.findByCode(code);
    }

}