package com.sptg.third.biz.topsailiot.controller;

import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.iot.api.entity.IotDevice;
import com.sptg.iot.api.feigns.IotDeviceFeign;
import com.sptg.third.api.entity.ApiCommonResult;
import com.sptg.third.api.entity.topsailiot.*;
import com.sptg.third.api.feigns.grid.GridIotFeign;
import com.sptg.third.api.feigns.topsailiot.TopsailFeign;
import com.sptg.third.biz.topsailiot.util.TopsailHttpUtil;
import com.sptg.third.biz.topsailiot.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zwx
 * @create 2020/12/6 0:56
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class TopsailController implements TopsailFeign {

    private final TopsailSysConfigServiceInterface topsailSysConfigServiceInterface;
    private final TopsailProjectServiceInterface topsailProjectServiceInterface;
    private final TopsailDeviceServiceInterface topsailDeviceServiceInterface;
    private final TopsailAlarmServiceInterface topsailAlarmServiceInterface;
    private final TopsailDeviceConfigServiceInterface topsailDeviceConfigServiceInterface;
    private final IotDeviceFeign iotDeviceFeign;
    private final GridIotFeign gridIotFeign;

    /**
     * 获取项目列表
     * @return
     */
    @Override
    @GetMapping(value = "/topsail/iot/getProjectList")
    public ResultBean<String> getProjectList() {
        TopsailSysConfig topsailSysConfig = this.topsailSysConfigServiceInterface.getById(1L);
        TopsailHttpUtil httpUtil = new TopsailHttpUtil(topsailSysConfig);
        ApiCommonResult<List<TopsailProject>> apiCommonResult = httpUtil.getProjectList();
        if(apiCommonResult.getCode().equals("0")) { //成功
            List<TopsailProject> sourceList = apiCommonResult.getData();
            List<TopsailProject> targetList = new ArrayList<>();
            sourceList.forEach(source ->{
                Integer project_id = source.getProject_id();
                TopsailProject target = this.topsailProjectServiceInterface.getByProjectId(project_id);
                if(target == null){
                    target = new TopsailProject();
                }else{
                    source.setId(target.getId());
                }
                BeanUtils.copyProperties(source, target);
                targetList.add(target);
            });
            if(targetList.size() > 0){
                boolean b = this.topsailProjectServiceInterface.insertOrUpdateBatch(targetList);
                if(b){
                    return new ResultBean<>(ResultEnum.SUCCESS);
                }else{
                    return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，但批量保存数据失败");
                }
            }else{
                return new ResultBean<>(ResultEnum.SUCCESS, "接口调用成功，但无数据返回");
            }
        }else {
            return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，" + apiCommonResult.getMsg());
        }
    }

    /**
     * 批量查询设备最新数据
     * @param projectId
     * @return
     */
    @Override
    @GetMapping(value = "/topsail/iot/getDeviceDatas/{projectId}")
    public ResultBean<String> getDeviceDatas(@PathVariable(value = "projectId") Integer projectId) {
        TopsailSysConfig topsailSysConfig = this.topsailSysConfigServiceInterface.getById(1L);
        TopsailHttpUtil httpUtil = new TopsailHttpUtil(topsailSysConfig);
        ApiCommonResult<List<TopsailDevice>> apiCommonResult = httpUtil.getDeviceDatas(projectId);
        if(apiCommonResult.getCode().equals("0")) { //成功
            List<TopsailDevice> sourceList = apiCommonResult.getData();
            List<IotDevice> iotDeviceList = new ArrayList<>();
            sourceList.forEach(source ->{
                if(source.getDeviceType().equals(4)){
                    String device_id = source.getImei();
                    IotDevice target = this.iotDeviceFeign.getIotDeviceByDeviceId(device_id);
                    String sampleData = source.getSampleData();
                    Integer first = Integer.parseInt(sampleData.substring(0, 1));
                    Float tempValue = Float.parseFloat(sampleData);
                    Double v = tempValue / Math.pow(10, first);
                    String s = v.toString();
                    String monitorValue = s.substring(1, s.length());
                    if(target == null){
                        target = new IotDevice();
                        target.setDevice_id(device_id);
                        target.setStatus(source.getAlarmType());
                        target.setDefense_status(1);
                        target.setDevice_name("无线智能消防栓监测终端");
                        target.setIMEI(source.getImei());
                        target.setDevice_type("960417");
                        target.setTenantId("804981");
                        target.setIs_aep("1");
                        target.setBattery_value(source.getBatteryLevel().toString());
                        target.setSignal_intensity(source.getSignalStrength().toString());
                        target.setMonitorValue(monitorValue + source.getUnit());
                        iotDeviceList.add(target);
                    }else{
                        target.setDevice_data(source.getValue() + source.getUnit());
                        target.setTenantId("804981");
                        target.setIs_aep("1");
                        target.setBattery_value(source.getBatteryLevel().toString());
                        target.setSignal_intensity(source.getSignalStrength().toString());
                        target.setMonitorValue(monitorValue + source.getUnit());
                        iotDeviceList.add(target);
                    }
                }
            });
            if(iotDeviceList.size() > 0){
                ResultBean<String> resultBean = this.iotDeviceFeign.insertOrUpdateBatch(iotDeviceList);
                if(resultBean.getCode().equals("200")){
                    this.gridIotFeign.gridIotDevicePush(iotDeviceList); //推送到网格
                    return new ResultBean<>(ResultEnum.SUCCESS);
                }else{
                    return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，但批量保存数据失败");
                }
            }else{
                return new ResultBean<>(ResultEnum.SUCCESS, "接口调用成功，但无数据返回");
            }
        }else {
            return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，" + apiCommonResult.getMsg());
        }
    }

    /**
     * 查询单个设备最新数据
     * @param deviceId
     * @return
     */
    @Override
    @GetMapping(value = "/topsail/iot/getDeviceByDeviceId/{deviceId}")
    public ResultBean<String> getDeviceByDeviceId(@PathVariable(value = "deviceId") String deviceId) {
        TopsailSysConfig topsailSysConfig = this.topsailSysConfigServiceInterface.getById(1L);
        TopsailHttpUtil httpUtil = new TopsailHttpUtil(topsailSysConfig);
        ApiCommonResult<TopsailDevice> apiCommonResult = httpUtil.getDeviceByDeviceId(deviceId);
        if(apiCommonResult.getCode().equals("0")) { //成功
            TopsailDevice source = apiCommonResult.getData();
            String imei = source.getImei();
            TopsailDevice target = this.topsailDeviceServiceInterface.getByImei(imei);
            if(target == null){
                target = new TopsailDevice();
            }else{
                source.setId(target.getId());
            }
            BeanUtils.copyProperties(source, target);
            boolean b = this.topsailDeviceServiceInterface.insertOrUpdate(target);
            if(b){
                return new ResultBean<>(ResultEnum.SUCCESS);
            }else{
                return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，但批量保存数据失败");
            }
        }else {
            return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，" + apiCommonResult.getMsg());
        }
    }

    /**
     * 查询单个设备历史数据
     * @param deviceId
     * @return
     */
    @Override
    @GetMapping(value = "/topsail/iot/getDevicesHistoryByDeviceId/{deviceId}")
    public ResultBean<String> getDevicesHistoryByDeviceId(@PathVariable(value = "deviceId") String deviceId) {
        TopsailSysConfig topsailSysConfig = this.topsailSysConfigServiceInterface.getById(1L);
        TopsailHttpUtil httpUtil = new TopsailHttpUtil(topsailSysConfig);
        ApiCommonResult<List<TopsailDevice>> apiCommonResult = httpUtil.getDevicesHistoryByDeviceId(deviceId);
        if(apiCommonResult.getCode().equals("0")) { //成功
            List<TopsailDevice> sourceList = apiCommonResult.getData();
            List<TopsailDevice> targetList = new ArrayList<>();
            sourceList.forEach(source ->{
                String imei = source.getImei();
                TopsailDevice target = this.topsailDeviceServiceInterface.getByImei(imei);
                if(target == null){
                    target = new TopsailDevice();
                }else{
                    source.setId(target.getId());
                }
                BeanUtils.copyProperties(source, target);
                targetList.add(target);
            });
            if(targetList.size() > 0){
                boolean b = this.topsailDeviceServiceInterface.insertOrUpdateBatch(targetList);
                if(b){
                    return new ResultBean<>(ResultEnum.SUCCESS);
                }else{
                    return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，但批量保存数据失败");
                }
            }else{
                return new ResultBean<>(ResultEnum.SUCCESS, "接口调用成功，但无数据返回");
            }
        }else {
            return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，" + apiCommonResult.getMsg());
        }
    }

    /**
     * 批量查询最新预警信息
     * @param projectId
     * @return
     */
    @Override
    @GetMapping(value = "/topsail/iot/getDevicesAlarms/{projectId}")
    public ResultBean<String> getDevicesAlarms(@PathVariable(value = "projectId") Integer projectId) {
        TopsailSysConfig topsailSysConfig = this.topsailSysConfigServiceInterface.getById(1L);
        TopsailHttpUtil httpUtil = new TopsailHttpUtil(topsailSysConfig);
        ApiCommonResult<List<TopsailAlarm>> apiCommonResult = httpUtil.getDevicesAlarms(projectId);
        if(apiCommonResult.getCode().equals("0")) { //成功
            List<TopsailAlarm> sourceList = apiCommonResult.getData();
            List<TopsailAlarm> targetList = new ArrayList<>();
            sourceList.forEach(source ->{
                Integer alarmId = source.getId();
                TopsailAlarm target = this.topsailAlarmServiceInterface.getByAlarmId(alarmId);
                if(target == null){
                    target = new TopsailAlarm();
                    target.setAlarmId(source.getId());
                    source.setAlarmId(source.getId());
                    source.setId(null);
                }else{
                    source.setId(target.getId());
                    source.setAlarmId(target.getAlarmId());
                }
                BeanUtils.copyProperties(source, target);
                targetList.add(target);
            });
            if(targetList.size() > 0){
                boolean b = this.topsailAlarmServiceInterface.insertOrUpdateBatch(targetList);
                if(b){
                    return new ResultBean<>(ResultEnum.SUCCESS);
                }else{
                    return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，但批量保存数据失败");
                }
            }else{
                return new ResultBean<>(ResultEnum.SUCCESS, "接口调用成功，但无数据返回");
            }
        }else {
            return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，" + apiCommonResult.getMsg());
        }
    }

    /**
     * 单个设备预警历史
     * @param deviceId
     * @return
     */
    @Override
    @GetMapping(value = "/topsail/iot/getDevicesAlarmByDeviceId/{deviceId}")
    public ResultBean<String> getDevicesAlarmByDeviceId(@PathVariable(value = "deviceId") String deviceId) {
        TopsailSysConfig topsailSysConfig = this.topsailSysConfigServiceInterface.getById(1L);
        TopsailHttpUtil httpUtil = new TopsailHttpUtil(topsailSysConfig);
        ApiCommonResult<List<TopsailAlarm>> apiCommonResult = httpUtil.getDevicesAlarmByDeviceId(deviceId);
        if(apiCommonResult.getCode().equals("0")) { //成功
            List<TopsailAlarm> sourceList = apiCommonResult.getData();
            List<TopsailAlarm> targetList = new ArrayList<>();
            sourceList.forEach(source ->{
                Integer alarmId = source.getId();
                TopsailAlarm target = this.topsailAlarmServiceInterface.getByAlarmId(alarmId);
                if(target == null){
                    target = new TopsailAlarm();
                    target.setAlarmId(source.getId());
                    source.setAlarmId(source.getId());
                    source.setId(null);
                }else{
                    source.setId(target.getId());
                    source.setAlarmId(target.getAlarmId());
                }
                BeanUtils.copyProperties(source, target);
                targetList.add(target);
            });
            if(targetList.size() > 0){
                boolean b = this.topsailAlarmServiceInterface.insertOrUpdateBatch(targetList);
                if(b){
                    return new ResultBean<>(ResultEnum.SUCCESS);
                }else{
                    return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，但批量保存数据失败");
                }
            }else{
                return new ResultBean<>(ResultEnum.SUCCESS, "接口调用成功，但无数据返回");
            }
        }else {
            return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，" + apiCommonResult.getMsg());
        }
    }

    /**
     * 批量设备配置信息获取
     * @param topsailIotDevice
     * @return
     */
    @Override
    @PostMapping(value = "/topsail/iot/getDevicesConfigs")
    public ResultBean<String> getDevicesConfigs(@RequestBody TopsailDevice topsailIotDevice) {
        TopsailSysConfig topsailSysConfig = this.topsailSysConfigServiceInterface.getById(1L);
        TopsailHttpUtil httpUtil = new TopsailHttpUtil(topsailSysConfig);
        Integer projectId = topsailIotDevice.getProjectId();
        Integer deviceType = topsailIotDevice.getDeviceType();
        ApiCommonResult<List<TopsailDeviceConfig>> apiCommonResult = httpUtil.getDevicesConfigs(projectId, deviceType);
        if(apiCommonResult.getCode().equals("0")) { //成功
            List<TopsailDeviceConfig> sourceList = apiCommonResult.getData();
            List<TopsailDeviceConfig> targetList = new ArrayList<>();
            sourceList.forEach(source ->{
                String imei = source.getImei();
                TopsailDeviceConfig target = this.topsailDeviceConfigServiceInterface.getByImei(imei);
                if(target == null){
                    target = new TopsailDeviceConfig();
                }else{
                    source.setId(target.getId());
                }
                BeanUtils.copyProperties(source, target);
                targetList.add(target);
            });
            if(targetList.size() > 0){
                boolean b = this.topsailDeviceConfigServiceInterface.insertOrUpdateBatch(targetList);
                if(b){
                    return new ResultBean<>(ResultEnum.SUCCESS);
                }else{
                    return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，但批量保存数据失败");
                }
            }else{
                return new ResultBean<>(ResultEnum.SUCCESS, "接口调用成功，但无数据返回");
            }
        }else {
            return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，" + apiCommonResult.getMsg());
        }
    }

    /**
     * 单个设备配置下发
     * @param deviceId
     * @return
     */
    @Override
    @GetMapping(value = "/topsail/iot/sendDevicesConfigByDeviceId/{deviceId}")
    public ResultBean<String> sendDevicesConfigByDeviceId(@PathVariable(value = "deviceId") String deviceId, @RequestBody TopsailDeviceConfig topsailDeviceConfig) {
        TopsailSysConfig topsailSysConfig = this.topsailSysConfigServiceInterface.getById(1L);
        TopsailHttpUtil httpUtil = new TopsailHttpUtil(topsailSysConfig);
        ApiCommonResult<String> apiCommonResult = httpUtil.sendDevicesConfigByDeviceId(deviceId, topsailDeviceConfig);
        if(apiCommonResult.getCode().equals("0")) { //成功
                return new ResultBean<>(ResultEnum.SUCCESS, apiCommonResult.getData());
        }else{
            return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，但批量保存数据失败");
        }
    }

    /**
     * 某设备配置信息查询
     * @param imei
     * @return
     */
    @Override
    @GetMapping(value = "/topsail/iot/getDeviceConfigData/{imei}")
    public ResultBean<String> getDeviceConfigData(@PathVariable(value = "imei") String imei) {
        TopsailSysConfig topsailSysConfig = this.topsailSysConfigServiceInterface.getById(1L);
        TopsailHttpUtil httpUtil = new TopsailHttpUtil(topsailSysConfig);
        ApiCommonResult<TopsailConfigData> apiCommonResult = httpUtil.getDeviceConfigData(imei);
        if(apiCommonResult.getCode().equals("0")) { //成功
            TopsailConfigData source = apiCommonResult.getData();
            TopsailDeviceConfig configSource = JsonUtils.jsonToPojo(source.getConfig(), TopsailDeviceConfig.class);
            TopsailDeviceConfig target = this.topsailDeviceConfigServiceInterface.getByImei(imei);
            if(target == null){
                target = new TopsailDeviceConfig();
            }else{
                configSource.setId(target.getId());
            }
            BeanUtils.copyProperties(configSource, target);
            boolean b = this.topsailDeviceConfigServiceInterface.insertOrUpdate(target);
            if(b){
                return new ResultBean<>(ResultEnum.SUCCESS);
            }else{
                return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，但批量保存数据失败");
            }
        }else {
            return new ResultBean<>(ResultEnum.FAILURE, "接口调用失败，" + apiCommonResult.getMsg());
        }
    }
}
