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

import io.swagger.models.auth.In;
import me.zhengjie.modules.dm.device.domain.DmDevice;
import me.zhengjie.modules.dm.printingQueue.domain.DmPrintingQueue;
import me.zhengjie.modules.dm.printingQueue.service.DmPrintingQueueService;
import me.zhengjie.modules.dm.printingQueue.service.mapstruct.DmPrintingQueueMapper;
import me.zhengjie.modules.dm.printingRequest.repository.DmPrintingRequestRepository;
import me.zhengjie.modules.dm.printingRequest.service.dto.DmPrintingRequestQueryCriteria;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.dm.device.repository.DmDeviceRepository;
import me.zhengjie.modules.dm.device.service.DmDeviceService;
import me.zhengjie.modules.dm.device.service.dto.DmDeviceDto;
import me.zhengjie.modules.dm.device.service.dto.DmDeviceQueryCriteria;
import me.zhengjie.modules.dm.device.service.mapstruct.DmDeviceMapper;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.query.Param;
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.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xwx
* @date 2021-03-12
**/
@Service
@RequiredArgsConstructor
public class DmDeviceServiceImpl implements DmDeviceService {

    private final DmDeviceRepository dmDeviceRepository;
    private final DmDeviceMapper dmDeviceMapper;
    private final DmPrintingQueueService printingQueueService;
    private final DmPrintingQueueMapper dmPrintingQueueMapper;
    private final DmPrintingRequestRepository dmPrintingRequestRepository;


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

    @Override
    public List<DmDeviceDto> queryAll(DmDeviceQueryCriteria criteria){
        return dmDeviceMapper.toDto(dmDeviceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public List<DmDeviceDto> queryAll(){
        return dmDeviceMapper.toDto(dmDeviceRepository.findAll());
    }

    @Override
    @Transactional
    public DmDeviceDto findById(Long id) {
        DmDevice dmDevice = dmDeviceRepository.findById(id).orElseGet(DmDevice::new);
        ValidationUtil.isNull(dmDevice.getId(),"DmDevice","id",id);
        return dmDeviceMapper.toDto(dmDevice);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmDeviceDto create(DmDevice resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId());
        //获取设备编号
//        resources.setCode(getCode());

        return dmDeviceMapper.toDto(dmDeviceRepository.save(resources));
    }

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

    @Override
    public Map<String,Object> deleteAll(Long[] ids) {
        Map<String,Object> map= new HashMap<>();
        List name=dmPrintingRequestRepository.selectDeviceName(ids);
        for (Long id : ids) {
            Integer count = dmPrintingRequestRepository.selecIsNotDevice(id);
            if(count<=0){
                dmDeviceRepository.deleteById(id);
            }else {
                map.put("lose",name+"已申请任务,不能删除");
                map.put("type", "device");
            }
        }
        return map;
    }

    @Override
    public void download(List<DmDeviceDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmDeviceDto dmDevice : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("设备编号", dmDevice.getCode());
            map.put("设备名称", dmDevice.getName());
            map.put("产品类型", dmDevice.getStyle());
            map.put("设备安装位置", dmDevice.getFloor().getFloorName());
            map.put("设备状态", dmDevice.getStatus());
            map.put("安装时间", dmDevice.getBuildDate());
            map.put("保修期", dmDevice.getWarranty());
            map.put("最新维修日期", dmDevice.getLastGuarantee());
            map.put("运维人员", dmDevice.getOperator());
            map.put("联系方式", dmDevice.getLinkType());
            map.put("备注", dmDevice.getRemark());
            map.put("创建者", dmDevice.getCreateBy());
            map.put("更新者", dmDevice.getUpdatedBy());
            map.put("创建日期", dmDevice.getCreateTime());
            map.put("更新时间", dmDevice.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Map<String, Object> selectList(DmDeviceQueryCriteria criteria, Pageable pageable) {
        Page<DmDevice> page = dmDeviceRepository.selectList(criteria,pageable);
        return PageUtil.toPage(page.map(dmDeviceMapper::toDto));
    }
    @Override
    public DmDeviceDto findInfo(Long id){
        DmDeviceDto dto = this.findById(id);
        List<DmPrintingQueue> queueList = printingQueueService.findUnprint(id);
        dto.setQueueList(dmPrintingQueueMapper.toDto(queueList));
        return dto;
    }

    @Override
    public  Map<String,Object> firstDevice() {
        Integer countSum=dmDeviceRepository.countSumDevice();
        Integer countYun=dmDeviceRepository.countYunDevice();
        Integer countTing=dmDeviceRepository.countTingDevice();
        Integer countDay=dmDeviceRepository.countDayDevice();
        String state=dmDeviceRepository.StateDevice();
        String end=dmDeviceRepository.EndDevice();
        Map<String,Object> map =new HashMap<>();
        map.put("countSum",countSum);
        map.put("countYun",countYun);
        map.put("countTing",countTing);
        map.put("countDay",countDay);
        map.put("state",state);
        map.put("end",end);
        return map;
    }

    @Override
    public List<Map<String, String>> YunDeviceRequest() {
        return dmDeviceRepository.YunDeviceRequest();
    }

    @Override
    public Map<String, Object> selectDevice(String buildStateDate,  String buildEndDate, Pageable pageable) {
        Page<DmDevice> page = dmDeviceRepository.selectDevice(buildStateDate,buildEndDate,pageable);
        return PageUtil.toPage(page.map(dmDeviceMapper::toDto));
    }

    @Override
    public Long findDeviceCount() {
        return dmDeviceRepository.findDeviceCount();
    }

    ;
    @Override
    public String getMaxCode() {
        return dmDeviceRepository.getMaxCode();
    }

    public String getCode(){
       String code = "";
       String maxCode = getMaxCode();
       if(maxCode == null || maxCode.isEmpty()){
           code="001";
       }else {
           int codeMax = Integer.parseInt(maxCode) +1;
           switch ((codeMax+"").length()){
               case 1:code = "00"+codeMax; break;
               case 2:code = "0"+codeMax; break;
               default:code = codeMax +"";
           }
       }
        return code;
    }

    @Override
    public List<Map<String, Object>> deviceList() {
        return dmDeviceRepository.deviceList();
    }

    @Override
    public Map<String, Object> deviceDetail(Long deviceId) {
        return dmDeviceRepository.deviceDetail(deviceId);
    }

    @Override
    public void updateStatus(String cardIp, String status) {
        dmDeviceRepository.updateStatus(cardIp,status);
    }
}
