package com.zcxk.charge.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcxk.charge.api.dto.QueryDeviceMonitorDto;
import com.zcxk.core.common.pojo.AjaxMessage;
import com.zcxk.core.oauth2.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;

/**
* @author Andy
**/
@RestController
@RequestMapping("/equipmentStatistics")
public class EquipmentStatisticsController {

    @Autowired
    RestTemplate restTemplate;

    @Value("${get_map_info_url}")
    private String getMapInfoUrl;

    @Value("${get_device_url}")
    private String getDeviceUrl;

    @GetMapping("/getTheMapInformationOfTheDevice")
    private AjaxMessage getTheMapInformationOfTheDevice(QueryDeviceMonitorDto queryDeviceMonitorDto){
        queryDeviceMonitorDto.setTenantId(UserUtil.getCurrentUser().getTenantId());
        return AjaxMessage.success(JSON.parse(sendApiReQuest(getMapInfoUrl,JSON.toJSONString(queryDeviceMonitorDto))));
    }

    @GetMapping("/getDeviceListInformation")
    private AjaxMessage getDeviceListInformation(QueryDeviceMonitorDto queryDeviceMonitorDto){
        queryDeviceMonitorDto.setTenantId(UserUtil.getCurrentUser().getTenantId());
        String result=sendApiReQuest(getDeviceUrl,JSON.toJSONString(queryDeviceMonitorDto));
        JSONObject info = JSON.parseObject(result);
        String key = "total";
        if (info.getInteger(key) == 0){
            info.put("list",new ArrayList<>());
        }
        return AjaxMessage.success(info);
    }

    private  String sendApiReQuest(String path , String args){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<>(args, headers);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(path, formEntity,
                String.class);
        JSONObject info = JSON.parseObject(stringResponseEntity.getBody());
        String result=null;
        String key = "status";
        String dataKey = "data";
        if(info.getInteger(key) == 0){
            result=info.getString(dataKey);
        }
        return result;
    }
}
