/*
*  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.repository;

import me.zhengjie.modules.dm.device.domain.DmDevice;
import me.zhengjie.modules.dm.device.service.dto.DmDeviceDto;
import me.zhengjie.modules.dm.device.service.dto.DmDeviceQueryCriteria;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import javax.transaction.Transactional;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @author xwx
* @date 2021-03-12
**/
public interface DmDeviceRepository extends JpaRepository<DmDevice, Long>, JpaSpecificationExecutor<DmDevice> {

    /**
     * 查询最大的code
     * @return
     */
    @Query(value = "select max(code) from dm_device", nativeQuery = true)
    String getMaxCode();

    @Query(nativeQuery =true,value = "SELECT * from ( " +
            " SELECT " +
            " a.id,a.`code`,a.`name`,a.create_by,a.update_by,a.create_time,a.update_time,a.style,a.status,a.build_date,a.warranty,a.last_guarantee,null as 'operator',a.link_type,a.build_address, " +
            " b.floor_id as 'floor.floor_id' ,b.floor_name as 'floor.floor_name',null as 'floor.floor_pic',null as 'floor.contacts',null as 'floor.sort_index',null as 'floor.create_by',null as 'floor.update_by',null as 'floor.create_time',null as 'floor.update_time', " +
            " (SELECT count(*) from dm_printing_queue q LEFT JOIN dm_printing_request r on q.request_id = r.id where r.printer_code = a.id and q.`status` in ('00','01') ) as un_printing_count, " +
            " (SELECT count(*) from dm_printing_queue q LEFT JOIN dm_printing_request r on q.request_id = r.id where r.printer_code = a.id and q.`status` in ('02') ) as yi_printing_count,remark,is_common_printer " +
            " from dm_device a" +
            " LEFT JOIN dm_floor b on b.floor_id = a.build_address \n" +
            ") a ",
    countQuery =  "SELECT count(*) from ( " +
            " SELECT " +
            " a.id,a.`code`,a.`name`, " +
            " b.floor_name as \"floor.name\"," +
            " (SELECT count(*) from dm_printing_queue q LEFT JOIN dm_printing_request r on q.request_id = r.id where r.printer_code = a.id and q.`status` in ('00','01') ) as unPrintingCount, " +
            " (SELECT count(*) from dm_printing_queue q LEFT JOIN dm_printing_request r on q.request_id = r.id where r.printer_code = a.id and q.`status` in ('02') ) as yi_printing_count,remark " +
            " from dm_device a" +
            " LEFT JOIN dm_floor b on b.floor_id = a.build_address \n" +
            ") a ")
    Page<DmDevice> selectList (DmDeviceQueryCriteria criteria, Pageable pageable);

    /**
     * 查询总设备
     * @return
     */
    @Query(value = "SELECT COUNT(id) FROM dm_device",nativeQuery = true)
    Integer countSumDevice();

    /**
     * 查询正在运行的设备
     * @return
     */
    @Query(value = "SELECT COUNT(id) FROM dm_device WHERE `status`='true'",nativeQuery = true)
    Integer countYunDevice();

    /**
     * 查询闲置的设备
     * @return
     */
    @Query(value = "SELECT COUNT(id) FROM dm_device WHERE `status`='false'",nativeQuery = true)
    Integer countTingDevice();

    /**
     * 查询整体运行天数
     * @return
     */
    @Query(value = "select datediff((select if(`status`='true',curdate(),(DATE_FORMAT(build_date,'%Y-%m-%d'))) as build_date from dm_device  ORDER BY build_date DESC LIMIT 0,1)," +
            "(SELECT DATE_FORMAT(build_date,'%Y-%m-%d') FROM dm_device ORDER BY build_date ASC LIMIT 0,1))",nativeQuery = true)
    Integer countDayDevice();

    /**
     * 查询开始时间
     * @return
     */
    @Query(value = "SELECT DATE_FORMAT(build_date,'%Y-%m-%d') FROM dm_device WHERE `status`='true' ORDER BY build_date ASC LIMIT 0,1",nativeQuery = true)
    String StateDevice();

    /**
     * 查询结束时间
     * @return
     */
    @Query(value = "select if(`status`='true',curdate(),(DATE_FORMAT(build_date,'%Y-%m-%d'))) as build_date from dm_device  ORDER BY build_date DESC LIMIT 0,1",nativeQuery = true)
    String EndDevice();

    /**
     * 查询设备运行趋势
     * @return
     */
    @Query(value = "SELECT count(*) as num,DATE_FORMAT(d.build_date,'%Y-%m-%d') as date " +
            "FROM dm_device d " +
            "LEFT JOIN dm_printing_request r ON d.id=r.printer_code " +
            "WHERE d.`status`='true' and DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE(d.build_date) " +
            "GROUP BY d.build_date ",nativeQuery = true)
    List<Map<String,String>> YunDeviceRequest();

    /**
     * 设备打印任务
     * @param
     * @param pageable
     * @return
     */
    @Query(nativeQuery =true,value = "SELECT * from ( " +
            " SELECT  a.id,a.`code`,a.`name`,a.create_by,a.update_by,DATE_FORMAT(a.build_date,'%Y-%m-%d')as build_date,a.create_time,a.update_time," +
            "a.style,a.status,a.warranty,a.last_guarantee,null as 'operator',a.link_type,a.build_address, a.card_ip,a.printing_address,a.printing_ip,b.floor_id as 'floor.floor_id' ," +
            "b.floor_name as 'floor.floor_name',null as 'floor.floor_pic',null as 'floor.contacts',null as 'floor.sort_index',null as 'floor.create_by'," +
            "null as 'floor.update_by',null as 'floor.create_time',null as 'floor.update_time',  " +
            "(SELECT count(*) from dm_printing_queue q LEFT JOIN dm_printing_request r on q.request_id = r.id where r.printer_code = a.id and q.`status` in ('00','01') ) as un_printing_count,  " +
            "(SELECT count(*) from dm_printing_queue q LEFT JOIN dm_printing_request r on q.request_id = r.id where r.printer_code = a.id and q.`status` in ('02') ) as yi_printing_count,remark,is_common_printer " +
            "from dm_device a LEFT JOIN dm_floor b on b.floor_id = a.build_address where if(:buildStateDate != '' and :buildEndDate !='',build_date between :buildStateDate and :buildEndDate,1=1)) a ",
            countQuery =  " SELECT count(*) from ( " +
                    " SELECT a.id,a.`code`,a.`name`,b.floor_name," +
                    " (SELECT count(*) from dm_printing_queue q LEFT JOIN dm_printing_request r on q.request_id = r.id where r.printer_code = a.id and q.`status` in ('00','01')) AS unPrintingCount," +
                    " (SELECT count(*) from dm_printing_queue q LEFT JOIN dm_printing_request r on q.request_id = r.id where r.printer_code = a.id and q.`status` in ('02')) AS yi_printing_count,remark " +
                    " FROM dm_device a LEFT JOIN dm_floor b ON b.floor_id = a.build_address where if(:buildStateDate != '' and :buildEndDate !='',build_date between :buildStateDate and :buildEndDate,1=1)) a ")
    Page<DmDevice> selectDevice (@Param("buildStateDate") String buildStateDate,@Param("buildEndDate") String buildEndDate, Pageable pageable);

    /**
     * 查询
     * @return
     */
    @Query(value = "SELECT COUNT(1) FROM dm_device WHERE build_address = ?1",nativeQuery = true)
    Integer selecIsNotfloor(Long floorId);

    @Query(value = "SELECT DISTINCT floor_name FROM dm_floor WHERE floor_id in (?1)",nativeQuery = true)
    List selectfloorName(Long[] floorId);
    @Query(value = "SELECT COUNT(1) FROM dm_device ",nativeQuery = true)
    Long findDeviceCount();

    /**
     * 打印设备列表(运营)
     * @return
     */
    @Query(value = "select d.id,d.`code`,d.`name`,(select sum(file_page_num) from dm_printing_request where to_days(update_time) = to_days(now()) and status ='01' and printer_code = d.id) as pageTotal from dm_device as d",nativeQuery = true)
    List<Map<String,Object>> deviceList();

    /**
     * 打印设备详情(运营)
     * @return
     */
    @Query(value = "select  d.id,d.`code`,d.`name`,d.operator,(select sum(file_page_num) from dm_printing_request where to_days(update_time) = to_days(now()) and status ='01' and printer_code = d.id)as pageTotal from dm_device as d where d.id=:deviceId",nativeQuery = true)
    Map<String,Object> deviceDetail(@Param("deviceId")Long deviceId);

    /**
     * 根据读卡器ip修改打印机状态
     */
    @Transactional
    @Modifying
    @Query(value = " update dm_device set status = ?2 where card_ip = ?1 ",nativeQuery = true)
    void updateStatus(String cardIp, String status);
}
