package com.usky.transfer.controller.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.demo.RemoteTsdbProxyService;
import com.usky.demo.domain.*;
import com.usky.transfer.domain.DmpDevice;
import com.usky.transfer.domain.DmpDeviceCommand;
import com.usky.transfer.service.DmpDeviceCommandService;
import com.usky.transfer.service.DmpDeviceService;
import com.usky.transfer.service.vo.DeviceMapVO;
import com.usky.transfer.service.vo.ExternalHistoryRequestVO;
import com.usky.transfer.service.vo.ExternalLastRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("dataQuery")
public class QueryDeviceDataController {
    @Autowired
    private RemoteTsdbProxyService remoteTsdbProxyService;
    @Autowired
    private DmpDeviceService dmpDeviceService;
    @Autowired
    private DmpDeviceCommandService dmpDeviceCommandService;

    @Cacheable(cacheNames = "externalDeviceList",sync = true)
    public Map<String, DeviceMapVO> getExternalDeviceMap(){
        Map<String,DeviceMapVO> deviceMap = new HashMap<>();
        LambdaQueryWrapper<DmpDevice> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DmpDevice::getDeleteFlag,0)
                .orderByDesc(DmpDevice::getId);
        List<DmpDevice> list = dmpDeviceService.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            for (int i = 0; i < list.size(); i++) {
                String deviceId = list.get(i).getDeviceId();
                DeviceMapVO mapVO = new DeviceMapVO();
                mapVO.setProductCode(list.get(i).getProductCode());
                mapVO.setDeviceId(list.get(i).getDeviceId());
                mapVO.setDeviceUuid(list.get(i).getDeviceUuid());
                mapVO.setDeviceStatus(list.get(i).getServiceStatus());

                deviceMap.put(deviceId,mapVO);
            }
        }

        return deviceMap;
    }

//    /**
//     * 单个设备实时数据查询(对外)
//     * @param productCode
//     * @param deviceId
//     * @return
//     */
//    @GetMapping("/externalLast")
//    public ApiResult<LastResultVO> queryLastDeviceData(@RequestParam(value = "productCode") String productCode,
//                                                       @RequestParam(value = "deviceId") String deviceId){
//        Map<String, DeviceMapVO> deviceMapList = this.getExternalDeviceMap();
//        if(!deviceMapList.containsKey(deviceId)){
//            throw new BusinessException(deviceId+"无设备信息");
//        }
//
//        String deviceUUId = "";
//
//        for (Map.Entry<String,DeviceMapVO> map:deviceMapList.entrySet()) {
//            String productCode1 = map.getValue().getProductCode();
//            String deviceId1 = map.getKey();
//            if((productCode.equals(productCode1)) && (deviceId.equals(deviceId1))){
//                deviceUUId = map.getValue().getDeviceUuid();
//            }
//        }
//
//        return ApiResult.success(remoteTsdbProxyService.queryLastDeviceData(deviceUUId));
//    }

    /**
     * 批量设备实时数据查询(对外)
     * @param requestVO
     * @return
     */
    @PostMapping("/externalLast")
    public ApiResult<List<LastInnerResultVO>> queryLastDeviceData(@RequestBody ExternalLastRequestVO requestVO){
        Map<String, DeviceMapVO> deviceMapList = this.getExternalDeviceMap();
        LastInnerQueryVO reqVO = new LastInnerQueryVO();

        String productCode = requestVO.getProductCode();
        List<String> deviceIds = requestVO.getDeviceId();
        List<String> deviceUUIds = new ArrayList<>();
        for (int i = 0; i < deviceIds.size(); i++) {
            String deviceId = deviceIds.get(i);
            if(!deviceMapList.containsKey(deviceId)){
                throw new BusinessException(deviceId+"无设备信息");
            }

            for (Map.Entry<String,DeviceMapVO> map:deviceMapList.entrySet()) {
                String productCode1 = map.getValue().getProductCode();
                String deviceId1 = map.getKey();
                if((productCode.equals(productCode1)) && (deviceId.equals(deviceId1))){
                    deviceUUIds.add(map.getValue().getDeviceUuid());

                }
            }
        }
        reqVO.setDeviceuuid(deviceUUIds);

        return remoteTsdbProxyService.queryLastDeviceData(reqVO);
    }

//    /**
//     * 单个设备历史数据查询(对外)
//     * @param productCode
//     * @param deviceId
//     * @param startTime
//     * @param endTime
//     * @return
//     */
//    @GetMapping("/externalHistory")
//    public ApiResult<HistoryResultVO> queryHistoryDeviceData(@RequestParam(value = "productCode") String productCode,
//                                                             @RequestParam(value = "deviceId") String deviceId,
//                                                             @RequestParam(value = "startTime") String startTime,
//                                                             @RequestParam(value = "endTime") String endTime){
//        Map<String, DeviceMapVO> deviceMapList = this.getExternalDeviceMap();
//        if(!deviceMapList.containsKey(deviceId)){
//            throw new BusinessException(deviceId+"无设备信息");
//        }
//
//        String deviceUUId = "";
//
//        for (Map.Entry<String,DeviceMapVO> map:deviceMapList.entrySet()) {
//            String productCode1 = map.getValue().getProductCode();
//            String deviceId1 = map.getKey();
//            if((productCode.equals(productCode1)) && (deviceId.equals(deviceId1))){
//                deviceUUId = map.getValue().getDeviceUuid();
//            }
//        }
//
//        return ApiResult.success(remoteTsdbProxyService.queryHistoryDeviceData(deviceUUId,startTime,endTime));
//    }

    /**
     * 批量设备历史数据查询(对外)
     * @param requestVO
     * @return
     */
    @PostMapping("/externalHistory")
    public ApiResult<List<HistorysInnerResultVO>> queryHistoryDeviceData(@RequestBody ExternalHistoryRequestVO requestVO){
        Map<String, DeviceMapVO> deviceMapList = this.getExternalDeviceMap();
        HistorysInnerRequestVO reqVO = new HistorysInnerRequestVO();

        String productCode = requestVO.getProductCode();
        List<String> deviceIds = requestVO.getDeviceId();
        List<String> deviceUUIds = new ArrayList<>();
        for (int i = 0; i < deviceIds.size(); i++) {
            String deviceId = deviceIds.get(i);
            if(!deviceMapList.containsKey(deviceId)){
                throw new BusinessException(deviceId+"无设备信息");
            }

            for (Map.Entry<String,DeviceMapVO> map:deviceMapList.entrySet()) {
                String productCode1 = map.getValue().getProductCode();
                String deviceId1 = map.getKey();
                if((productCode.equals(productCode1)) && (deviceId.equals(deviceId1))){
                    deviceUUIds.add(map.getValue().getDeviceUuid());

                }
            }
        }
        reqVO.setDeviceuuid(deviceUUIds);
        reqVO.setStartTime(requestVO.getStartTime());
        reqVO.setEndTime(requestVO.getEndTime());

        return remoteTsdbProxyService.queryHistoryDeviceData(reqVO);
    }

    /**
     * 指令记录
     * @param commandStatus
     * @param productCode
     * @param deviceId
     * @param userName
     * @param startTime
     * @param endTime
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("deviceCommandRecord")
    public ApiResult<CommonPage<DmpDeviceCommand>> deviceCommandRecord(@RequestParam(value = "commandStatus",required = false) Integer commandStatus,
                                                                       @RequestParam(value = "productCode",required = false) String productCode,
                                                                       @RequestParam(value = "deviceUuid",required = false) String deviceUuid,
                                                                       @RequestParam(value = "userName",required = false) String userName,
                                                                       @RequestParam(value = "startTime",required = false) String startTime,
                                                                       @RequestParam(value = "endTime",required = false) String endTime,
                                                                       @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                                                       @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize){
        return ApiResult.success(dmpDeviceCommandService.deviceCommandRecord(commandStatus,productCode,deviceUuid,userName,startTime,endTime,pageNum,pageSize));
    }
}
