package com.huimv.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hikvision.cms.api.common.util.HttpClientSSLUtils;
import com.huimv.admin.common.utils.DataUill;
import com.huimv.admin.common.utils.Result;
import com.huimv.admin.common.utils.ResultCode;
import com.huimv.admin.entity.*;
import com.huimv.admin.entity.dto.DeviceDto;
import com.huimv.admin.entity.vo.EnvDataVo;
import com.huimv.admin.entity.vo.WriteEnvDataVo;
import com.huimv.admin.entity.zengxindto.*;
import com.huimv.admin.mapper.*;
import com.huimv.admin.service.IEnvDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-02-13
 */
@Service
public class EnvDeviceServiceImpl extends ServiceImpl<EnvDeviceMapper, EnvDevice> implements IEnvDeviceService {

    @Autowired
    private EnvDeviceMapper envDeviceMapper;
    @Autowired
    private BasePigpenMapper basePigpenMapper;
    @Autowired
    private EnvDataMapper dataMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private EnvWarningInfoMapper warningInfoMapper;
    @Autowired
    private EnvNh3nMapper nh3nMapper;
    @Autowired
    private WriteEnvDataMapper writeEnvDataMapper;

    @Override
    public Result count(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        QueryWrapper<EnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        Integer count = envDeviceMapper.selectCount(queryWrapper);
        JSONObject jsonObject = new JSONObject();
        if (count == 0) {
            jsonObject.put("DeviceCount", 0);
            jsonObject.put("OnDeviceCount", 0);
            jsonObject.put("OffDeviceCount", 0);
            jsonObject.put("OnDeviceRate", 0);
        } else {
            QueryWrapper<EnvDevice> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("device_status", 1).eq("farm_id", farmId);
            Integer count1 = envDeviceMapper.selectCount(queryWrapper1);
            Integer OffDeviceCount = count - count1;
            //创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            //设置精确到小数点后两位
            numberFormat.setMaximumFractionDigits(2);
            String onDeviceRate = numberFormat.format((float) count1 / (float) count * 100) + "%";
            jsonObject.put("DeviceCount", count);
            jsonObject.put("OnDeviceCount", count1);
            jsonObject.put("OffDeviceCount", OffDeviceCount);
            jsonObject.put("OnDeviceRate", onDeviceRate);
        }
        return new Result(ResultCode.SUCCESS, jsonObject);
    }

    @Override
    public Result list(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String pageSize = paramsMap.get("pageSize");
        String pageNo = paramsMap.get("pageNo");
        if (pageSize == null || pageSize == "") {
            pageSize = "10";
        }
        if (pageNo == null || pageNo == "") {
            pageNo = "1";
        }
        QueryWrapper<EnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        Page<EnvDevice> page = new Page(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        return new Result(ResultCode.SUCCESS, envDeviceMapper.selectPage(page, queryWrapper));
    }

    @Override
    public Result add(HttpServletRequest httpServletRequest, EnvDevice envDevice) {
        System.out.println(envDevice.getDeviceName());
        if (envDeviceMapper.selectCount(new QueryWrapper<EnvDevice>().eq("device_name", envDevice.getDeviceName()).eq("farm_id", envDevice.getFarmId())) != 0) {
            return new Result(ResultCode.FAIL, "设备名称已存在");
        }
        if (envDeviceMapper.selectCount(new QueryWrapper<EnvDevice>().eq("device_code", envDevice.getDeviceCode())) != 0) {
            return new Result(ResultCode.FAIL, "设备编码已存在");
        }
        if (envDeviceMapper.selectCount(new QueryWrapper<EnvDevice>().eq("unit_id", envDevice.getUnitId()).eq("farm_id", envDevice.getFarmId())) != 0) {
            return new Result(ResultCode.FAIL, "该单元已有设备");
        }
        envDeviceMapper.insert(envDevice);
        return new Result(ResultCode.SUCCESS, "添加成功");
    }

    @Override
    public Result edit(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String id = paramsMap.get("id");
        String DeviceName = paramsMap.get("DeviceName");
        String BuildLocation = paramsMap.get("BuildLocation");
        String DeviceBrand = paramsMap.get("DeviceBrand");
        String remark = paramsMap.get("remark");
        if (remark == null || remark == "") {
            remark = null;
        }

        QueryWrapper<EnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        EnvDevice envDevice = envDeviceMapper.selectOne(queryWrapper);
        envDevice.setFarmId(Integer.parseInt(farmId));
        envDevice.setDeviceName(DeviceName);
        envDevice.setDeviceBrand(DeviceBrand);
        envDevice.setBuildLocation(BuildLocation);
        envDevice.setRemark(remark);

        QueryWrapper<EnvDevice> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("device_name", DeviceName);
        if (ObjectUtil.isEmpty(envDeviceMapper.selectOne(queryWrapper1))) {
            envDeviceMapper.updateById(envDevice);
        } else {
            return new Result(ResultCode.FAIL, "设备名称已存在");
        }
        return new Result(ResultCode.SUCCESS);
    }

    @Override
    public Result delete(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String id = paramsMap.get("id");
        QueryWrapper<EnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("farm_id", farmId);
        envDeviceMapper.delete(queryWrapper);
        return new Result(ResultCode.SUCCESS, "删除成功");
    }

    @Override
    public Result listPigpen(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String id = paramsMap.get("id");//楼层id
        String displayType = paramsMap.get("displayType");
        if ("".equals(displayType) || null == displayType) {
            displayType = "0";
        }
        JSONArray jsonArray = new JSONArray();
        QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).eq("other3", 0);
        if (id == null || id == "") {
            queryWrapper.eq("parent_id", 3);
        } else {
            queryWrapper.like("other2", id);
        }
        List<BasePigpen> basePigpens = basePigpenMapper.selectList(queryWrapper);//得到栋舍单元
        for (int i = 0; i < basePigpens.size(); i++) {
           /* QueryWrapper<EnvDevice> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("unit_name",basePigpens.get(i).getId());
            EnvDevice envDevice = envDeviceMapper.selectOne(queryWrapper1);//找到栋舍绑定的设备，利用单元id*/
            JSONObject jsonObject = new JSONObject();
            if (displayType.equals("0")) {
                QueryWrapper<EnvData> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("unit_id", basePigpens.get(i).getId()).orderByDesc("create_time").last(" limit 1");//通过设备id来拿取数据
                EnvData envData = dataMapper.selectOne(queryWrapper2);
                if (ObjectUtil.isEmpty(envData)) {
                    jsonObject.put("temp", 0);//温度
                    jsonObject.put("hum", 0);//湿度
                    jsonObject.put("location", basePigpens.get(i).getBuildName());
                    jsonObject.put("unit_id", basePigpens.get(i).getId());//单元id
                } else {
                    jsonObject.put("temp", envData.getEnvTemp());//温度
                    jsonObject.put("hum", envData.getEnvHum());//湿度
                    jsonObject.put("location", basePigpens.get(i).getBuildName());
                    jsonObject.put("unit_id", envData.getUnitId());//单元id
                }
            } else {
                QueryWrapper<WriteEnvData> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("unit_id", basePigpens.get(i).getId()).orderByDesc("create_time").last(" limit 1");//通过设备id来拿取数据
                WriteEnvData writeEnvData = writeEnvDataMapper.selectOne(queryWrapper1);
                if (ObjectUtil.isEmpty(writeEnvData)) {
                    jsonObject.put("temp", 0);//温度
                    jsonObject.put("hum", 0);//湿度
                    jsonObject.put("location", basePigpens.get(i).getBuildName());
                    jsonObject.put("unit_id", basePigpens.get(i).getId());//单元id
                } else {
                    jsonObject.put("temp", writeEnvData.getTemp());//温度
                    jsonObject.put("hum", writeEnvData.getHum());//湿度
                    jsonObject.put("location", basePigpens.get(i).getBuildName());
                    jsonObject.put("unit_id", writeEnvData.getUnitId());//单元id
                }
            }

            jsonArray.add(jsonObject);
        }
        return new Result(ResultCode.SUCCESS, jsonArray);
    }

    @Override
    public Result listEnv(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String id = paramsMap.get("id");//单元id
        String type = paramsMap.get("type");//查询类型
        String startTime = paramsMap.get("startTime");
        String endTime = paramsMap.get("endTime");
        String displayType = paramsMap.get("displayType");//数据来源 2为填报数据
        if (type == null || type == "") {
            type = "1";
        }
        if ("".equals(displayType) || null == displayType) {
            displayType = "0";
        }
        Map map = new HashMap<>();
        if (displayType.equals("0")) {
            QueryWrapper<BasePigpen> basePigpenQueryWrapper = new QueryWrapper<>();
            basePigpenQueryWrapper.eq("farm_id", farmId).eq("id", id);
            BasePigpen basePigpen = basePigpenMapper.selectOne(basePigpenQueryWrapper);

            QueryWrapper<EnvData> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("unit_id", id).eq("farm_id", farmId);
            if (ObjectUtil.isEmpty(basePigpen)) {
                map.put("location", "");
            }else {
                map.put("location", basePigpen.getBuildName());
            }

            //展示某一天
            if ("5".equals(type)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                queryWrapper.between("create_time", startTime, endTime);
                List<EnvData> envData = dataMapper.listDay2(queryWrapper);


                map.put("data", envData);
            }

            //自定义查询
            if ("4".equals(type)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                queryWrapper.between("create_time", startTime, endTime);
                List<EnvData> envData = dataMapper.listDay(queryWrapper);

                map.put("location", basePigpen.getBuildName());
                map.put("data", envData);
            }
            //本月
            else if ("3".equals(type)) {
                Date timesMonthmorning = DataUill.getTimesMonthmorning();
                queryWrapper.ge("create_time", timesMonthmorning);
                List<EnvData> envData = dataMapper.listDay(queryWrapper);

                map.put("data", envData);

            }
            //本周
            else if ("2".equals(type)) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
                queryWrapper.ge("create_time", calendar.getTime());
                List<EnvData> envData = dataMapper.listDay(queryWrapper);

                map.put("data", envData);
            }
            //今日
            else if ("1".equals(type)) {
                Date timesmorning = DataUill.getTimesmorning();
                queryWrapper.ge("create_time", timesmorning);
                List<EnvData> envData = dataMapper.listNow(queryWrapper);

                map.put("data", envData);
            }
        } else {
            QueryWrapper<BasePigpen> basePigpenQueryWrapper = new QueryWrapper<>();
            basePigpenQueryWrapper.eq("farm_id", farmId).eq("id", id);
            BasePigpen basePigpen = basePigpenMapper.selectOne(basePigpenQueryWrapper);

            QueryWrapper<WriteEnvData> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("unit_id", id).eq("farm_id", farmId);

            //展示某一天
            if ("5".equals(type)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                queryWrapper.between("create_time", startTime, endTime);
                List<WriteEnvDataVo> writeEnvData = writeEnvDataMapper.listDay2(queryWrapper);

                map.put("location", basePigpen.getBuildName());
                map.put("data", writeEnvData);
            }

            //自定义查询
            if ("4".equals(type)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                queryWrapper.between("create_time", startTime, endTime);
                List<WriteEnvDataVo> writeEnvData = writeEnvDataMapper.listDay(queryWrapper);

                map.put("location", basePigpen.getBuildName());
                map.put("data", writeEnvData);
            }
            //本月
            else if ("3".equals(type)) {
                Date timesMonthmorning = DataUill.getTimesMonthmorning();
                queryWrapper.ge("create_time", timesMonthmorning);
                List<WriteEnvDataVo> writeEnvData = writeEnvDataMapper.listDay(queryWrapper);
                map.put("location", basePigpen.getBuildName());
                map.put("data", writeEnvData);

            }
            //本周
            else if ("2".equals(type)) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
                queryWrapper.ge("create_time", calendar.getTime());
                List<WriteEnvDataVo> writeEnvData = writeEnvDataMapper.listDay(queryWrapper);
                map.put("location", basePigpen.getBuildName());
                map.put("data", writeEnvData);
            }
            //今日
            else if ("1".equals(type)) {
                Date timesmorning = DataUill.getTimesmorning();
                queryWrapper.ge("create_time", timesmorning);
                List<WriteEnvDataVo> writeEnvData = writeEnvDataMapper.listNow(queryWrapper);
                map.put("location", basePigpen.getBuildName());
                map.put("data", writeEnvData);
            }
        }

        return new Result(ResultCode.SUCCESS, map);
    }

    @Override
    public Result listDeviceCount(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        Integer offCount = 0;
        Integer onCount = 0;
        QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).eq("parent_id", 0);
        List<BasePigpen> basePigpens = basePigpenMapper.selectList(queryWrapper);//得到所有的栋
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < basePigpens.size(); i++) {
            QueryWrapper<BasePigpen> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.like("other2", basePigpens.get(i).getId());
            List<BasePigpen> basePigpens1 = basePigpenMapper.selectList(queryWrapper1);//得到所有的楼层
            for (int j = 0; j < basePigpens1.size(); j++) {
                QueryWrapper<EnvDevice> deviceQueryWrapper = new QueryWrapper<>();
                deviceQueryWrapper.eq("unit_id", basePigpens1.get(j).getId());
                EnvDevice envDevice = envDeviceMapper.selectOne(deviceQueryWrapper);
                if (ObjectUtil.isNotEmpty(envDevice)) {
                    if (envDevice.getDeviceStatus() == 0) {
                        offCount++;
                    } else {
                        onCount++;
                    }
                }

            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("location", basePigpens.get(i).getBuildName());
            jsonObject.put("onDevice", onCount);
            jsonObject.put("offDevice", offCount);
            jsonArray.add(jsonObject);
            offCount = 0;
            onCount = 0;
        }
        return new Result(ResultCode.SUCCESS, jsonArray);
    }

    @Override
    @Transactional
    public Result sync(Map<String, String> params) throws Exception {
        String farmId = params.get("farmId");
        //获取所有栏舍
        Map<String, Object> map = new HashMap<String, Object>();
        String s = HttpClientSSLUtils.doPost("https://yzwlw.loongk.com/mobile/login?username=华统&password=21218cca77804d2ba1922c33e0151105", JSON.toJSONString(map));
        System.out.println("登录带栏舍：" + s);
        LoginDto loginDto = JSONUtil.toBean(s, LoginDto.class);
        DataToken token = loginDto.getData().getToken();
        String encode = Base64.encode(token.getUserId() + "_" + token.getToken());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", encode);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        List<DataShacks> shacks = loginDto.getData().getShacks();
        // 不能删除，需做比较
        List<String> zengXinDeviceId = shacks.stream().map(DataShacks::getId).collect(Collectors.toList());
        List<String> huatongDeviceId = envDeviceMapper.selectDeviceCodeByfarmId(Integer.parseInt(farmId));

        CopyOnWriteArrayList<String> zengXinDeviceIdCopy = ListUtil.toCopyOnWriteArrayList(zengXinDeviceId);
        CopyOnWriteArrayList<String> huatongDeviceIdCopy = ListUtil.toCopyOnWriteArrayList(huatongDeviceId);
        //新增的设备
        zengXinDeviceIdCopy.removeAll(huatongDeviceId);
        //新增
        if (zengXinDeviceIdCopy.size() > 0) {
            for (String deviceId : zengXinDeviceIdCopy) {
                syncConfig(deviceId, requestEntity, farmId);
            }
        }
        //需要删除的设备
        huatongDeviceIdCopy.removeAll(zengXinDeviceId);
        if (huatongDeviceIdCopy.size() > 0) {
            this.remove(new QueryWrapper<EnvDevice>().in("device_code", huatongDeviceIdCopy));
        }
        System.out.println("zengxin:" + zengXinDeviceIdCopy);
        System.out.println(huatongDeviceIdCopy);
        return new Result(10000, "同步成功", false);
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<String, Object>();
        String s = null;
        try {
            s = HttpClientSSLUtils.doPost("https://yzwlw.loongk.com/mobile/login?username=华统&password=21218cca77804d2ba1922c33e0151105", JSON.toJSONString(map));
            LoginDto loginDto = JSONUtil.toBean(s, LoginDto.class);
            DataToken token = loginDto.getData().getToken();
            String encode = Base64.encode(token.getUserId() + "_" + token.getToken());
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", encode);
            HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
            //
            RestTemplate restTemplate = new RestTemplate();

            ResponseEntity<String> exchangePeizhi = restTemplate.exchange("https://yzwlw.loongk.com/mobile/loadShackDatas/2c92083a871cf897018725a162130013", HttpMethod.GET, requestEntity, String.class);
            System.out.println(exchangePeizhi.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("登录带栏舍：" + s);
    }

    @Override
    public Result bandingUnitId(HttpServletRequest httpServletRequest, EnvDevice envDevice) {
        Integer unitId = envDevice.getUnitId();
        int count = this.count(new QueryWrapper<EnvDevice>().eq("unit_id", unitId));
        if (count > 0) {
            return new Result(10001, "绑定失败，该栋舍已有设备", false);
        }
        this.updateById(envDevice);
        return new Result(10000, "绑定成功", true);
    }

    @Override
    public Result listPigpenAll(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        //TODO 优化一下
        String farmId = paramsMap.get("farmId");
        String displayType = paramsMap.get("displayType");
        if ("".equals(displayType) || null == displayType) {
            displayType = "0";
        }
        List objects = new ArrayList<>();
        if ("0".equals(displayType)) {
            List<EnvDataVo> envDataVos = dataMapper.listPigpenAll(farmId);
            return new Result(ResultCode.SUCCESS, envDataVos);
        } else {
            QueryWrapper<BasePigpen> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("farm_id", farmId).eq("f_type", 3);
            List<BasePigpen> basePigpens = basePigpenMapper.selectList(queryWrapper1);
            for (BasePigpen basePigpen : basePigpens) {
                JSONObject jsonObject = new JSONObject();
                QueryWrapper<WriteEnvData> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("farm_id", farmId).eq("unit_id", basePigpen.getId())
                        .orderByDesc("create_time").last(" limit 1");
                WriteEnvData writeEnvData = writeEnvDataMapper.selectOne(queryWrapper);
                if (ObjectUtil.isNotEmpty(writeEnvData)) {
                    jsonObject.put("temp", writeEnvData.getTemp());//温度
                    jsonObject.put("hum", writeEnvData.getHum());//湿度
                    jsonObject.put("location", basePigpen.getBuildName());
                    jsonObject.put("aq", writeEnvData.getAq());
                    jsonObject.put("unitId", basePigpen.getId());//单元id
                } else {
                    jsonObject.put("temp", 0);//温度
                    jsonObject.put("hum", 0);//湿度
                    jsonObject.put("location", basePigpen.getBuildName());
                    jsonObject.put("unitId", basePigpen.getId());//单元id
                    jsonObject.put("aq", 0);
                }
                objects.add(jsonObject);
            }

        }
        return new Result(ResultCode.SUCCESS, objects);
    }

    @Override
    public Result listEnvCount(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        QueryWrapper<EnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        Integer count = envDeviceMapper.selectCount(queryWrapper);//设备检测数量
        queryWrapper.eq("device_status", 1);
        Integer count1 = envDeviceMapper.selectCount(queryWrapper);//设备在线数量
        //创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        //设置精确到小数点后两位
        numberFormat.setMaximumFractionDigits(2);
        String onDeviceRate = numberFormat.format((float) count1 / (float) count * 100); //设备在线率
        QueryWrapper<EnvWarningInfo> warningInfoQueryWrapper = new QueryWrapper<>();
        warningInfoQueryWrapper.eq("farm_id", farmId);
        Integer warnCount = warningInfoMapper.selectCount(warningInfoQueryWrapper);//全年报警数量
        Date timesmorning = DataUill.getTimesmorning();
        warningInfoQueryWrapper.ge("date", timesmorning);
        Integer warningCountToday = warningInfoMapper.selectCount(warningInfoQueryWrapper);//今日报警数量
        //得到监测保障天数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long day = 0;
        try {
            Date now = new Date();
            String nowTime = sdf.format(now);
//            System.out.println(now);
            Date date = sdf.parse("2023-01-01");//指定日期
            Date mydate = sdf.parse(nowTime);//当前日期
            day = (mydate.getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
//            System.out.println(day);
        } catch (Exception e) {
            return new Result(ResultCode.SUCCESS, "");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("WarningCountYear", warnCount);
        jsonObject.put("WarningCountToday", warningCountToday);
        jsonObject.put("EnvCount", count);
        jsonObject.put("OnCount", count);
        jsonObject.put("onDeviceRate", onDeviceRate);
        jsonObject.put("day", day);
        return new Result(ResultCode.SUCCESS, jsonObject);
    }

    @Override
    public Result listData(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        JSONArray jsonArray = new JSONArray();

        QueryWrapper<EnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        List<EnvDevice> envDevices = envDeviceMapper.selectList(queryWrapper);
        for (EnvDevice envDevice : envDevices) {
            if (StringUtils.isNotBlank(envDevice.getRemark()) && "26".equals(farmId)) {
                QueryWrapper<EnvNh3n> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("device_code", envDevice.getRemark()).orderByDesc("create_date").last(" limit 1");
                EnvNh3n envNh3n = nh3nMapper.selectOne(queryWrapper1);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("deviceCode", envNh3n.getDeviceCode());
                jsonObject.put("buildName", envDevice.getUnitName());
                jsonObject.put("aq", envNh3n.getNh3N());
                jsonObject.put("status", envDevice.getDeviceStatus());
                jsonObject.put("hum", "");
                jsonObject.put("temp", "");
                jsonArray.add(jsonObject);
            } else if (envDevice.getDeviceCode().length() > 3 && "26".equals(farmId)) {
                QueryWrapper<EnvData> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("device_id", envDevice.getDeviceName()).orderByDesc("create_time").last(" limit 1");
                EnvData envData = dataMapper.selectOne(queryWrapper1);
                if (ObjectUtil.isNotEmpty(envData)) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("deviceCode", envData.getDeviceId());
                    jsonObject.put("buildName", envDevice.getUnitName());
                    jsonObject.put("aq", "");
                    jsonObject.put("hum", envData.getEnvHum());
                    jsonObject.put("temp", envData.getEnvTemp());
                    jsonObject.put("status", envDevice.getDeviceStatus());
                    jsonArray.add(jsonObject);
                }
            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("deviceCode", envDevice.getDeviceCode());
                jsonObject.put("buildName", envDevice.getUnitName());
                jsonObject.put("aq", "");
                jsonObject.put("hum", "");
                jsonObject.put("temp", "");
                jsonObject.put("status", envDevice.getDeviceStatus());
                jsonArray.add(jsonObject);
            }
        }
        return new Result(ResultCode.SUCCESS, jsonArray);
    }

    //添加新的设备
    private void syncConfig(String shackId, HttpEntity httpEntity, String farmId) {
        try {
            ResponseEntity<String> exchangePeizhi = restTemplate.exchange("https://yzwlw.loongk.com/mobile/loadShackConfig/" + shackId, HttpMethod.GET, httpEntity, String.class);
            String peizhibody = exchangePeizhi.getBody();
            ShackConfigDto shackConfigDto = JSONUtil.toBean(peizhibody, ShackConfigDto.class);
            ShackConfigData data = shackConfigDto.getData();
            List<ShackConfigDataSensors> sensors = data.getSensors();
            if (ObjectUtil.isNotEmpty(sensors)) {
                EnvDevice envDevice = new EnvDevice();
                envDevice.setFarmId(Integer.parseInt(farmId));
                envDevice.setDeviceBrand("增鑫");
                envDevice.setDeviceCode(data.getId());
                envDevice.setDeviceName(data.getName());
                for (ShackConfigDataSensors sensor : sensors) {
                    if ("TEMPERATURE".equals(sensor.getType())) {
                        envDevice.setOhter1(sensor.getId());
                    }
                    if ("HUMIDITY".equals(sensor.getType())) {
                        envDevice.setOhter2(sensor.getId());
                    }
                }
                envDeviceMapper.insert(envDevice);
            }
        } catch (Exception e) {
            System.out.println("设备同步异常：" + e + "  deviceId" + shackId);
        }

    }


}
