package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.LocationUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.NumberFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据大屏Controller
 *
 * @author zhengjie
 * @date 2023-09-08
 */
@RestController
@RequestMapping("/system/display")
public class TDataDisplayController extends BaseController {
    @Autowired
    private ITShouhuanAlarmListService tShouhuanAlarmListService;

    @Autowired
    private ITDeviceListService tDeviceListService;

    @Autowired
    private ITShouhuanInfoService itShouhuanInfoService;

    @Autowired
    private ITUserProfileService userProfileService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private LocationUtils locationUtils;

    /**
     * 查询SOS预警处理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(DataAlarmListDto dataAlarmListDto) {
        startPage();
        List<DataAlarmListDto> list = tShouhuanAlarmListService.selectTShouhuanAlarmList(dataAlarmListDto);
        List<AlarmListDto> alarmListDtos = list.stream().map(
                mapper -> {
                    AlarmListDto alarmListDto = new AlarmListDto();
                    alarmListDto.setName(mapper.getName());
                    alarmListDto.setTelno(mapper.getTel_one());
                    alarmListDto.setLocation(getCounterLocation(mapper.getGps_long() + "," + mapper.getGps_lat()));
                    alarmListDto.setAlarmMessage(tDeviceListService.checkMessage(mapper.getAlarm_type()));
                    alarmListDto.setCreatetime(mapper.getCreatetime());
                    return alarmListDto;
                }
        ).collect(Collectors.toList());
        return getDataTable1(alarmListDtos, tShouhuanAlarmListService.selectTShouhuanAlarmListCount());
    }

    @GetMapping("/count")
    public AjaxResult count() {
        return success(userProfileService.selectuserAgeCount());
    }

    @GetMapping("/alarm")
    public AjaxResult alarm() {
        AlarmStatusDto dto = new AlarmStatusDto();
        dto.setAlarmSOSSolve(tShouhuanAlarmListService.selectTShouhuanAlarmSOSSolve());
        dto.setUn_alarmSOSSolve(tShouhuanAlarmListService.selectTShouhuanAlarmSOS() - tShouhuanAlarmListService.selectTShouhuanAlarmSOSSolve());
        dto.setAlarmRailSolve(tShouhuanAlarmListService.selectTShouhuanAlarmRailSolve());
        dto.setUn_alarmRailSolve(tShouhuanAlarmListService.selectTShouhuanAlarmRail() - tShouhuanAlarmListService.selectTShouhuanAlarmRailSolve());
        dto.setAlarmHeartSolve(tShouhuanAlarmListService.selectTShouhuanAlarmRailSolve());
        dto.setUn_alarmHeartSolve(tShouhuanAlarmListService.selectTShouhuanAlarmHeart() - tShouhuanAlarmListService.selectTShouhuanAlarmHeartSolve());
        dto.setAlarmFallSolve(tShouhuanAlarmListService.selectTShouhuanAlarmFallSolve());
        dto.setUn_alarmFallSolve(tShouhuanAlarmListService.selectTShouhuanAlarmFall() - tShouhuanAlarmListService.selectTShouhuanAlarmFallSolve());
        dto.setAlarmLowSolve(tShouhuanAlarmListService.selectTShouhuanAlarmLowSolve());
        dto.setUn_alarmLowSolve(tShouhuanAlarmListService.selectTShouhuanAlarmLow() - tShouhuanAlarmListService.selectTShouhuanAlarmLowSolve());
        dto.setAlarmStatusSolve(tShouhuanAlarmListService.selectTShouhuanAlarmStatus());
        dto.setUn_alarmStatusSolve(tShouhuanAlarmListService.selectTShouhuanAlarmStatusSolve());
        return success(dto);
    }

    @GetMapping("/percent")
    public AjaxResult percent() {
        AlarmPercentDto dto = new AlarmPercentDto();
        dto.setAlarmSOS(checkPercent(tShouhuanAlarmListService.selectTShouhuanAlarmSOSSolve(), tShouhuanAlarmListService.selectTShouhuanAlarmSOS()));
        dto.setAlarmRail(checkPercent(tShouhuanAlarmListService.selectTShouhuanAlarmRailSolve(), tShouhuanAlarmListService.selectTShouhuanAlarmRail()));
        dto.setAlarmFall(checkPercent(tShouhuanAlarmListService.selectTShouhuanAlarmFallSolve(), tShouhuanAlarmListService.selectTShouhuanAlarmFall()));
        int statusSum = tShouhuanAlarmListService.selectTShouhuanAlarmStatus() + tShouhuanAlarmListService.selectTShouhuanAlarmStatusSolve();
        dto.setAlarmStauts(checkPercent(tShouhuanAlarmListService.selectTShouhuanAlarmStatus(), statusSum));
        int alarmAll = tShouhuanAlarmListService.selectTShouhuanAlarmSOSSolve() + tShouhuanAlarmListService.selectTShouhuanAlarmRailSolve() + tShouhuanAlarmListService.selectTShouhuanAlarmRailSolve() + tShouhuanAlarmListService.selectTShouhuanAlarmFallSolve() + tShouhuanAlarmListService.selectTShouhuanAlarmOtherSolve();
        dto.setAlarmAll(checkPercent(alarmAll, tShouhuanAlarmListService.selectTShouhuanAlarmListCount()));
        return success(dto);
    }

    @GetMapping("/deviceView")
    public AjaxResult deviceView() {
        DeviceViewDto dto = new DeviceViewDto();
        dto.setDeviceCount(tShouhuanAlarmListService.selectTShouhuanAlarmStatus() + tShouhuanAlarmListService.selectTShouhuanAlarmStatusSolve());
        dto.setDeviceOnline(tShouhuanAlarmListService.selectTShouhuanAlarmStatus());
        dto.setUn_deviceOnline(tShouhuanAlarmListService.selectTShouhuanAlarmStatusSolve());
        dto.setAlarmCount(tShouhuanAlarmListService.selectTShouhuanAlarmListCount());
        return success(dto);
    }

    @GetMapping("/deviceType")
    public AjaxResult deviceType() {
        Integer total = tDeviceListService.selectDeviceListCount();
        List<DeviceTypeDto> deviceListDto = tDeviceListService.selectDeviceListDto();
        for (DeviceTypeDto listDto : deviceListDto) {
            listDto.setDeviceStr(checkDeviceType(listDto.getDevice_model()));
            listDto.setDevicePercent(checkPercent(listDto.getCount(), total));
        }
        AjaxResult ajax = new AjaxResult();
        ajax.put("list", deviceListDto);
        ajax.put("total", total);
        return AjaxResult.success("操作成功", ajax);
    }

    @GetMapping("/userAgeAll")
    public AjaxResult userAgeAll() {
        Integer total = userProfileService.selectuserAgeCount();
        List<UserAgeDto> dtoList = userProfileService.selectuserAgeDto();
        dtoList.removeIf(user -> StringUtils.isNull(user.getAge()));
        AjaxResult ajax = new AjaxResult();
        ajax.put("list", dtoList);
        ajax.put("total", total);
        return AjaxResult.success("操作成功", ajax);
    }

    @GetMapping("/mapGpsView")
    public AjaxResult mapGpsView() {
        List<MapGpsDto> dtoList = itShouhuanInfoService.selectMapGpsView();
        AjaxResult ajax = new AjaxResult();
        ajax.put("lnglat", dtoList);
        AjaxResult ajax1 = new AjaxResult();
        ajax1.put("pointList", ajax);
        return AjaxResult.success("操作成功", ajax1);
    }

    @GetMapping("/mapGpsViewV2")
    public AjaxResult mapGpsViewV2() {   //TODO 暂时写在Controller中
        List<MapGpsDto> dtoList = itShouhuanInfoService.selectMapGpsView();
        List<AjaxResult> collect = new ArrayList<>();
        if (dtoList != null && !dtoList.isEmpty()) {
            collect = dtoList.stream()
                    .map(mapGpsDto -> {
                        AjaxResult ajax = new AjaxResult();
                        List<Float> list = new ArrayList<>();
                        if (mapGpsDto != null && mapGpsDto.getGps_long() != null && mapGpsDto.getGps_lat() != null) {
                            list.add(mapGpsDto.getGps_long());
                            list.add(mapGpsDto.getGps_lat());
                        }
                        ajax.put("lnglat", list);
                        return ajax;
                    }).filter(
                            person -> {
                                List<Float> lngList = (List<Float>) person.get("lnglat");
                                if (lngList != null && !lngList.isEmpty() && lngList.size() >= 2) {
                                    Float lng = lngList.get(0);
                                    Float lat = lngList.get(1);
                                    return lng > 0 && lat > 0;
                                }
                                return false;
                            }).collect(Collectors.toList());
        }
        return AjaxResult.success("操作成功", collect);
    }

    /**
     * 用户新增
     */
    @GetMapping("/addUser")
    public AjaxResult addUser() {
        List<AddUserDto> dtoList = userProfileService.selectAddUser();
        return success(dtoList);
    }

    /**
     * 设备新增
     */
    @GetMapping("/addDevice")
    public AjaxResult addDevice() {
        List<AddDeviceDto> dtoList = tDeviceListService.selectAddDevice();
        LocalDate currentDate = LocalDate.now();
        LocalDate lastMonthDate = currentDate.minusMonths(1);
        int year = currentDate.getYear();
        if (dtoList.size() == 2) {
            int lastMonth = lastMonthDate.getMonthValue() - 1;
            AddDeviceDto dto = new AddDeviceDto();
            dto.setMonth(year + "-0" + lastMonth);
            dto.setCount(0);
            dtoList.add(dto);
        } else if (dtoList.size() == 1) {
            int lastMonth = lastMonthDate.getMonthValue();
            int lastlastMonth = lastMonthDate.getMonthValue() - 1;
            AddDeviceDto dto = new AddDeviceDto();
            dto.setMonth(year + "-0" + lastMonth);
            dto.setCount(0);
            dtoList.add(dto);
            AddDeviceDto dto1 = new AddDeviceDto();
            dto1.setMonth(year + "-0" + lastlastMonth);
            dto1.setCount(0);
            dtoList.add(dto1);
        }
        dtoList = dtoList.stream().sorted(Comparator.comparing(AddDeviceDto::getMonth)).collect(Collectors.toList());
        return success(dtoList);
    }

    @GetMapping("/alarmStatusList")
    public AjaxResult alarmStatusList() {
        List<AlarmStatusListDto> dtoList = tShouhuanAlarmListService.selectAlarmStatusListDto();
        for (AlarmStatusListDto dto : dtoList) {
            dto.setAlarm_msg(tDeviceListService.checkMessage(dto.getAlarm_type()));
        }
        return success(dtoList);
    }

    /**
     * 设备总览
     */
    @GetMapping("/deviceOver")
    public AjaxResult deviceOver() {
        DeviceOverDto dto = new DeviceOverDto();
        dto.setBindDevice(tDeviceListService.selectDeviceListCount());
        dto.setBindUser(tDeviceListService.selectTDeviceListBandUser());
        dto.setDeviceOnline(tShouhuanAlarmListService.selectTShouhuanAlarmStatus());
        return success(dto);
    }

    /**
     * 查询SOS预警处理列表
     */
    @GetMapping("/alarmList")
    public AjaxResult alarmList(DataAlarmListDto dataAlarmListDto) {
        List<DataAlarmListDto> list = tShouhuanAlarmListService.selectTShouhuanAlarmList(dataAlarmListDto);
        List<MessageAlarmListDto> messageAlarmListDtoList = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            messageAlarmListDtoList = list.stream().map(
                    mapper -> {
                        MessageAlarmListDto alarmListDto = new MessageAlarmListDto();
                        alarmListDto.setName(mapper.getName());
                        alarmListDto.setAlarm_msg(tDeviceListService.checkMessage(mapper.getAlarm_type()));
                        alarmListDto.setTelno(mapper.getTel_one());
                        alarmListDto.setGps_long(mapper.getGps_long());
                        alarmListDto.setGps_lat(mapper.getGps_lat());
                        alarmListDto.setAddress(getCounterLocation(mapper.getGps_long() + "," + mapper.getGps_lat()));
                        alarmListDto.setAlarm_type(mapper.getAlarm_type());
                        alarmListDto.setCreatetime(mapper.getCreatetime());
                        return alarmListDto;
                    }
            ).collect(Collectors.toList());
        }
        return success(messageAlarmListDtoList);
    }


    /**
     * 逆地理编码
     *
     * @param location
     * @return
     */
    public String getCounterLocation(String location) {

        Map<String, String> params = new HashMap<>();
        params.put("location", location);
        logger.info("获取逆地理编码,请求的参数为:{}", params);
        JSONObject map = locationUtils.getCounterLocation(params);
        LocationDto locationDto = com.alibaba.fastjson2.JSONObject.parseObject(String.valueOf(map), LocationDto.class);
        logger.info("获取逆地理编码,返回的请求结果为:{}", map);
        return locationDto.getFormatted_address();
    }

    /**
     * 计算百分比
     */
    public String checkPercent(int num1, int num2) {
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(2);
        String result = numberFormat.format((float) num1 / (float) num2 * 100);
        return result;
    }

    public String checkDeviceType(Integer device_model) {
        if (device_model == null) {
            return "null";
        }
        SysDictData date = new SysDictData();
        date.setDictType("sys_device_type");
        List<SysDictData> selectDictDataList = sysDictDataService.selectDictDataList(date);
        for (SysDictData sysDictData : selectDictDataList) {
            if (device_model == Integer.parseInt(sysDictData.getDictValue())) {
                return sysDictData.getDictLabel();
            }
        }
        return "null";
    }
}
