package com.huimv.admin.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.huimv.admin.common.token.TokenSign;
import com.huimv.admin.common.utils.DataUill;
import com.huimv.admin.common.utils.ExcelImportSheet;
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.ListRankVo;
import com.huimv.admin.entity.vo.*;
import com.huimv.admin.mapper.*;
import com.huimv.admin.service.IEnergyDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 耗能数据 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-02-14
 */
@Service
public class EnergyDataServiceImpl extends ServiceImpl<EnergyDataMapper, EnergyData> implements IEnergyDataService {

    @Autowired
    private EnergyDataMapper dataMapper;
    @Autowired
    private BasePigpenMapper basePigpenMapper;
    @Autowired
    private EnergyWarningInfoMapper warningInfoMapper;
    @Autowired
    private EnergyEnvDeviceMapper envDeviceMapper;
    @Autowired
    private EnergyScreenMapper screenMapper;
    @Autowired
    private BaseFarmMapper farmMapper;

    @Override
    public Result listCount(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String waterDisplayType = paramsMap.get("waterDisplayType");
        String electricityDisplayType = paramsMap.get("electricityDisplayType");
        String feedDisplayType = paramsMap.get("feedDisplayType");
        String gasDisplayType = paramsMap.get("gasDisplayType");
        QueryWrapper<EnergyData> waterqueryWrapper = new QueryWrapper<>();
        QueryWrapper<EnergyData> electricityqueryWrapper = new QueryWrapper<>();
        QueryWrapper<EnergyData> feedqueryWrapper = new QueryWrapper<>();
        QueryWrapper<EnergyData> gasqueryWrapper = new QueryWrapper<>();

        EnergyDataVo energyDataVo;
        Date monthmorning = DataUill.getTimesMonthmorning();
        if ("1".equals(waterDisplayType)||"1".equals(electricityDisplayType)||"1".equals(feedDisplayType)
                ||"1".equals(gasDisplayType)) {
            if (ObjectUtil.isNotEmpty(waterDisplayType)) {
                waterqueryWrapper.eq("display_type", waterDisplayType);
            }
            if (ObjectUtil.isNotEmpty(electricityDisplayType)) {
                electricityqueryWrapper.eq("display_type", electricityDisplayType);
            }
            if (ObjectUtil.isNotEmpty(feedDisplayType)) {
                feedqueryWrapper.eq("display_type", feedDisplayType);
            }
            if (ObjectUtil.isNotEmpty(gasDisplayType)) {
                gasqueryWrapper.eq("display_type", gasDisplayType);
            }
            waterqueryWrapper.eq("farm_id", farmId).ge("create_date", monthmorning);
            electricityqueryWrapper.eq("farm_id", farmId).ge("create_date", monthmorning);
            feedqueryWrapper.eq("farm_id", farmId).ge("create_date", monthmorning);
            gasqueryWrapper.eq("farm_id", farmId).ge("create_date", monthmorning);
            energyDataVo = dataMapper.listWaterCount(waterqueryWrapper);
            energyDataVo.setGasValue(dataMapper.listGasCount(gasqueryWrapper));
            energyDataVo.setFeedValue(dataMapper.listFeedCount(feedqueryWrapper));
            energyDataVo.setElectricityValue(dataMapper.listElectricityCount(electricityqueryWrapper));
            QueryWrapper<EnergyWarningInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("farm_id", farmId);
            Integer count = warningInfoMapper.selectCount(queryWrapper1);
            energyDataVo.setCount(count);
        }else {
            QueryWrapper<EnergyData> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("display_type", waterDisplayType);
            queryWrapper.eq("farm_id", farmId).ge("create_date", monthmorning);
            energyDataVo = dataMapper.listAllCount(queryWrapper);
        }
        return new Result(ResultCode.SUCCESS, energyDataVo);
    }

    @Override
    public Result listData(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String dataType = paramsMap.get("dataType");
        String displayType = paramsMap.get("displayType");
        String timeType = paramsMap.get("timeType");
        String startTime = paramsMap.get("startTime");
        String endTime = paramsMap.get("endTime");

        if (dataType == null || dataType == "") {
            dataType = "1";
        }
        if (timeType == null || timeType == "") {
            timeType = "3";
        }

        QueryWrapper<EnergyData> dataQueryWrapper = new QueryWrapper<>();
        dataQueryWrapper.eq("farm_id", farmId);
        if (ObjectUtil.isNotEmpty(displayType)) {
            dataQueryWrapper.eq("display_type", displayType);
        }
        //用水
        if ("1".equals(dataType)) {
            dataQueryWrapper.isNotNull("water_value");
            //自定义
            if ("4".equals(timeType)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                dataQueryWrapper.between("create_date", startTime, endTime);
                return new Result(ResultCode.SUCCESS, dataMapper.listDayWater(dataQueryWrapper));
            }
            //全年
            if ("3".equals(timeType)) {
                DateTime dateTime = DateUtil.beginOfYear(new Date());
                dataQueryWrapper.ge("create_date", dateTime);
                List<EnergyAllDataVo> energyWaterDataVos = dataMapper.listYearWater(dataQueryWrapper);
                return new Result(ResultCode.SUCCESS, energyWaterDataVos);
            }
            //本月
            if ("2".equals(timeType)) {
                Date timesMonthmorning = DataUill.getTimesMonthmorning();
                dataQueryWrapper.ge("create_date", timesMonthmorning);
                return new Result(ResultCode.SUCCESS, dataMapper.listDayWater(dataQueryWrapper));
            }
            //本周
            if ("1".equals(timeType)) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
                dataQueryWrapper.ge("create_date", calendar.getTime());
                List<EnergyAllDataVo> energyWaterDataVos = dataMapper.listDayWater(dataQueryWrapper);
                return new Result(ResultCode.SUCCESS, energyWaterDataVos);
            }
        }
        //用电
        else if ("2".equals(dataType)) {
            dataQueryWrapper.isNotNull("electricity_value");
            //自定义
            if ("4".equals(timeType)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                dataQueryWrapper.between("create_date", startTime, endTime);
                return new Result(ResultCode.SUCCESS, dataMapper.listDayElectricity(dataQueryWrapper));
            }
            //全年
            if ("3".equals(timeType)) {
                DateTime dateTime = DateUtil.beginOfYear(new Date());
                dataQueryWrapper.ge("create_date", dateTime);
                List<EnergyAllDataVo> energyElectricityDataVos = dataMapper.listYearElectricity(dataQueryWrapper);
                return new Result(ResultCode.SUCCESS, energyElectricityDataVos);
            }
            //本月
            if ("2".equals(timeType)) {
                Date timesMonthmorning = DataUill.getTimesMonthmorning();
                dataQueryWrapper.ge("create_date", timesMonthmorning);
                return new Result(ResultCode.SUCCESS, dataMapper.listDayElectricity(dataQueryWrapper));
            }
            //本周
            if ("1".equals(timeType)) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
                dataQueryWrapper.ge("create_date", calendar.getTime());
                List<EnergyAllDataVo> energyElectricityDataVos = dataMapper.listDayElectricity(dataQueryWrapper);
                return new Result(ResultCode.SUCCESS, energyElectricityDataVos);
            }
        }
        //饲料
        else if ("3".equals(dataType)) {
            dataQueryWrapper.isNotNull("feed_value");
            //自定义
            if ("4".equals(timeType)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                dataQueryWrapper.between("create_date", startTime, endTime);
                return new Result(ResultCode.SUCCESS, dataMapper.listDayFeed(dataQueryWrapper));
            }
            //全年
            if ("3".equals(timeType)) {
                DateTime dateTime = DateUtil.beginOfYear(new Date());
                dataQueryWrapper.ge("create_date", dateTime);
                List<EnergyAllDataVo> energyFeedDataVos = dataMapper.listYearFeed(dataQueryWrapper);
                return new Result(ResultCode.SUCCESS, energyFeedDataVos);
            }
            //本月
            if ("2".equals(timeType)) {
                Date timesMonthmorning = DataUill.getTimesMonthmorning();
                dataQueryWrapper.ge("create_date", timesMonthmorning);
                return new Result(ResultCode.SUCCESS, dataMapper.listDayFeed(dataQueryWrapper));
            }
            //本周
            if ("1".equals(timeType)) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
                dataQueryWrapper.ge("create_date", calendar.getTime());
                List<EnergyAllDataVo> energyFeedDataVos = dataMapper.listDayFeed(dataQueryWrapper);
                return new Result(ResultCode.SUCCESS, energyFeedDataVos);
            }
        }
        //天然气
        else if ("4".equals(dataType)) {
            dataQueryWrapper.isNotNull("gas_value");
            //自定义
            if ("4".equals(timeType)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                dataQueryWrapper.between("create_date", startTime, endTime);
                return new Result(ResultCode.SUCCESS, dataMapper.listDayGas(dataQueryWrapper));
            }
            //全年
            if ("3".equals(timeType)) {
                DateTime dateTime = DateUtil.beginOfYear(new Date());
                dataQueryWrapper.ge("create_date", dateTime);
                List<EnergyAllDataVo> energyGasDataVos = dataMapper.listYearGas(dataQueryWrapper);
                return new Result(ResultCode.SUCCESS, energyGasDataVos);
            }
            //本月
            if ("2".equals(timeType)) {
                Date timesMonthmorning = DataUill.getTimesMonthmorning();
                dataQueryWrapper.ge("create_date", timesMonthmorning);
                return new Result(ResultCode.SUCCESS, dataMapper.listDayGas(dataQueryWrapper));
            }
            //本周
            if ("1".equals(timeType)) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
                dataQueryWrapper.ge("create_date", calendar.getTime());
                List<EnergyAllDataVo> energyGasDataVos = dataMapper.listDayGas(dataQueryWrapper);
                return new Result(ResultCode.SUCCESS, energyGasDataVos);
            }
        }
        return new Result(ResultCode.SUCCESS);
    }

    @Override
    public Result listRank(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String displayType = paramsMap.get("displayType");
        String dataType = paramsMap.get("dataType");
        String timeType = paramsMap.get("timeType");
        String startTime = paramsMap.get("startTime");
        String endTime = paramsMap.get("endTime");
        if (dataType == null || dataType == "") {
            dataType = "1";
        }
        if (timeType == null || timeType == "") {
            timeType = "3";
        }
        JSONArray jsonArray = new JSONArray();

        QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).eq("f_type", 2).eq("other3", 1);
        List<BasePigpen> pigpens = basePigpenMapper.selectList(queryWrapper);//得到所有的楼层
        for (BasePigpen pigpen : pigpens) {
            Float value = 0.00f;
            JSONObject jsonObject = new JSONObject();
            QueryWrapper<BasePigpen> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.like("other2", pigpen.getId()).eq("farm_id", farmId).ne("id", pigpen.getId());
            List<BasePigpen> basePigpens1 = basePigpenMapper.selectList(queryWrapper1);
            List<Integer> idList = new ArrayList<>();
            basePigpens1.forEach(item -> {
                idList.add(item.getId());
            });//某一层所有单元的id

            QueryWrapper<EnergyData> waterWrapper = new QueryWrapper<>();
            QueryWrapper<EnergyData> gasWrapper = new QueryWrapper<>();
            QueryWrapper<EnergyData> electricityWrapper = new QueryWrapper<>();
            QueryWrapper<EnergyData> feedWrapper = new QueryWrapper<>();
            if (idList.size() != 0) {
                waterWrapper.eq("farm_id", farmId).in("unit_id", idList);
                gasWrapper.eq("farm_id", farmId).in("unit_id", idList);
                electricityWrapper.eq("farm_id", farmId).in("unit_id", idList);
                feedWrapper.eq("farm_id", farmId).in("unit_id", idList);
                if ("4".equals(timeType)) {
                    //自定义
                    startTime = startTime + " 00:00:00";
                    endTime = endTime + " 23:59:59";
                    waterWrapper.between("create_date", startTime, endTime);
                    gasWrapper.between("create_date", startTime, endTime);
                    electricityWrapper.between("create_date", startTime, endTime);
                    feedWrapper.between("create_date", startTime, endTime);
                } else if ("3".equals(timeType)) {
                    //本年
                    DateTime dateTime = DateUtil.beginOfYear(new Date());
                    waterWrapper.ge("create_date", dateTime);
                    gasWrapper.ge("create_date", dateTime);
                    electricityWrapper.ge("create_date", dateTime);
                    feedWrapper.ge("create_date", dateTime);
                } else if ("2".equals(timeType)) {
                    //本月
                    Date timesMonthmorning = DataUill.getTimesMonthmorning();
                    waterWrapper.ge("create_date", timesMonthmorning);
                    gasWrapper.ge("create_date", timesMonthmorning);
                    electricityWrapper.ge("create_date", timesMonthmorning);
                    feedWrapper.ge("create_date", timesMonthmorning);
                } else if ("1".equals(timeType)) {
                    //本周
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
                    waterWrapper.ge("create_date", calendar.getTime());
                    gasWrapper.ge("create_date", calendar.getTime());
                    electricityWrapper.ge("create_date", calendar.getTime());
                    feedWrapper.ge("create_date", calendar.getTime());
                }


                if (ObjectUtil.isNotEmpty(displayType)) {
                    waterWrapper.eq("display_type", displayType);
                }
                if (ObjectUtil.isNotEmpty(displayType)) {
                    gasWrapper.eq("display_type", displayType);
                }
                if (ObjectUtil.isNotEmpty(displayType)) {
                    electricityWrapper.eq("display_type", displayType);
                }
                if (ObjectUtil.isNotEmpty(displayType)) {
                    feedWrapper.eq("display_type", displayType);
                }

                waterWrapper.select(" IFNULL(SUM(water_value),0) waterValue ");
                gasWrapper.select(" IFNULL(SUM(gas_value),0) gasValue ");
                electricityWrapper.select(" IFNULL(SUM(electricity_value),0) electricityValue ");
                feedWrapper.select(" IFNULL(SUM(feed_value),0) feedValue ");
                if ("1".equals(dataType)) {
                    value = Float.parseFloat(dataMapper.selectOne(waterWrapper).getWaterValue());
                    jsonObject.put("value", value);
                }
                if ("2".equals(dataType)) {
                    value = Float.parseFloat(dataMapper.selectOne(electricityWrapper).getElectricityValue());
                    jsonObject.put("value", value);
                }
                if ("3".equals(dataType)) {
                    value = Float.parseFloat(dataMapper.selectOne(feedWrapper).getFeedValue());
                    jsonObject.put("value", value);

                }
                if ("4".equals(dataType)) {
                    value = Float.parseFloat(dataMapper.selectOne(gasWrapper).getGasValue());
                    jsonObject.put("value", value);
                }

            } else {
                jsonObject.put("value", 0);
            }
            jsonObject.put("buildName", pigpen.getBuildName());
            jsonArray.add(jsonObject);
        }

        JSONArray arraySort = jsonArraySort(jsonArray, "value", true);
        return new Result(ResultCode.SUCCESS, arraySort);
    }

    @Override
    public Result listDataScreen(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String waterDisplayType = paramsMap.get("waterDisplayType");
        String electricityDisplayType = paramsMap.get("electricityDisplayType");
        String feedDisplayType = paramsMap.get("feedDisplayType");
        String gasDisplayType = paramsMap.get("gasDisplayType");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
        QueryWrapper<EnergyData> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("farm_id", farmId).ge("create_date", calendar.getTime());
        if (ObjectUtil.isNotEmpty(gasDisplayType)) {
            queryWrapper1.eq("display_type", gasDisplayType);
        }
        QueryWrapper<EnergyData> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("farm_id", farmId).ge("create_date", calendar.getTime());
        if (ObjectUtil.isNotEmpty(feedDisplayType)) {
            queryWrapper2.eq("display_type", feedDisplayType);
        }
        QueryWrapper<EnergyData> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("farm_id", farmId).ge("create_date", calendar.getTime());
        if (ObjectUtil.isNotEmpty(waterDisplayType)) {
            queryWrapper3.eq("display_type", waterDisplayType);
        }
        QueryWrapper<EnergyData> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("farm_id", farmId).ge("create_date", calendar.getTime());
        if (ObjectUtil.isNotEmpty(electricityDisplayType)) {
            queryWrapper4.eq("display_type", electricityDisplayType);
        }
        List<EnergyAllDataVo> energyGasDataVos = dataMapper.listDayGas(queryWrapper1.isNotNull("gas_value"));
        List<EnergyAllDataVo> energyFeedDataVos = dataMapper.listDayFeed(queryWrapper2.isNotNull("feed_value"));
        List<EnergyAllDataVo> energyWaterDataVos = dataMapper.listDayWater(queryWrapper3.isNotNull("water_value"));
        List<EnergyAllDataVo> energyElectricityDataVos = dataMapper.listDayElectricity(queryWrapper4.isNotNull("electricity_value"));
        Collections.reverse(energyGasDataVos);
        Collections.reverse(energyFeedDataVos);
        Collections.reverse(energyWaterDataVos);
        Collections.reverse(energyElectricityDataVos);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("gas", energyGasDataVos);
        jsonObject.put("water", energyWaterDataVos);
        jsonObject.put("energyElectricity", energyElectricityDataVos);
        if (energyFeedDataVos.size() != 0) {
            for (EnergyAllDataVo energyFeedDataVo : energyFeedDataVos) {
                Double feed = Double.valueOf(energyFeedDataVo.getValue());
                DecimalFormat def = new DecimalFormat("0.00");
                energyFeedDataVo.setValue(def.format(feed / 1000));
            }
        }
        jsonObject.put("feed", energyFeedDataVos);
        return new Result(ResultCode.SUCCESS, jsonObject);
    }

    @Override
    public Result listRankScreen(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String dataType = paramsMap.get("dataType");
        String waterDisplayType = paramsMap.get("waterDisplayType");
        String electricityDisplayType = paramsMap.get("electricityDisplayType");
        String feedDisplayType = paramsMap.get("feedDisplayType");
        String gasDisplayType = paramsMap.get("gasDisplayType");

        if (dataType == null || dataType == "") {
            dataType = "1";
        }
        JSONArray jsonArray = new JSONArray();
        QueryWrapper<EnergyData> waterWrapper = new QueryWrapper<>();
        QueryWrapper<EnergyData> gasWrapper = new QueryWrapper<>();
        QueryWrapper<EnergyData> electricityWrapper = new QueryWrapper<>();
        QueryWrapper<EnergyData> feedWrapper = new QueryWrapper<>();
        Date timesMonthmorning = DataUill.getTimesMonthmorning();

        waterWrapper.eq("farm_id", farmId).ge("create_date", timesMonthmorning);
        gasWrapper.eq("farm_id", farmId).ge("create_date", timesMonthmorning);
        feedWrapper.eq("farm_id", farmId).ge("create_date", timesMonthmorning);
        electricityWrapper.eq("farm_id", farmId).ge("create_date", timesMonthmorning);
        if (ObjectUtil.isNotEmpty(waterDisplayType)) {
            waterWrapper.eq("display_type", waterDisplayType);
        }
        if (ObjectUtil.isNotEmpty(gasDisplayType)) {
            gasWrapper.eq("display_type", gasDisplayType);
        }
        if (ObjectUtil.isNotEmpty(electricityDisplayType)) {
            electricityWrapper.eq("display_type", electricityDisplayType);
        }
        if (ObjectUtil.isNotEmpty(feedDisplayType)) {
            feedWrapper.eq("display_type", feedDisplayType);
        }
        List<ListRankVo> lists = new ArrayList<>();
        if ("1".equals(dataType)) {
            lists = dataMapper.listRankWater(waterWrapper);
        }
        if ("2".equals(dataType)) {
            lists = dataMapper.listRankElectricity(electricityWrapper);
        }
        if ("3".equals(dataType)) {
            lists = dataMapper.listRankFeed(feedWrapper);
        }
        if ("4".equals(dataType)) {
            lists = dataMapper.listRankGas(gasWrapper);
        }

        for (ListRankVo list : lists) {
            JSONObject jsonObject = new JSONObject();
            QueryWrapper<EnergyEnvDevice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("farm_id", farmId).eq("unit_id", list.getUnitId());
            EnergyEnvDevice envDevice = envDeviceMapper.selectOne(queryWrapper);
            jsonObject.put("value", list.getValue());
            jsonObject.put("buildName", envDevice.getDeviceName());
            jsonArray.add(jsonObject);
        }


        return new Result(ResultCode.SUCCESS, jsonArray);


    }

    @Override
    public Result listDataAll(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {

        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");// 1水 2电
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

        String time = paramsMap.get("time");
        if ("".equals(time) || null == time) {
            Date timesmorning = DataUill.getTimesmorning();
            time = sdf1.format(timesmorning);
        }
        String start = time + " 00:00:00";
        String end = time + " 23:59:59";
        QueryWrapper<EnergyScreen> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).between("create_date", start, end).eq("type", type);
        List<EnergyScreen> energyScreens = screenMapper.selectList(queryWrapper);

        JSONArray jsonArray = new JSONArray();
        if (energyScreens.size() != 0) {
            for (EnergyScreen energyScreen : energyScreens) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("deviceCode", energyScreen.getDeviceCode());
                jsonObject.put("buildName", energyScreen.getBuildName());
                jsonObject.put("day1", energyScreen.getTodayRead());
                jsonObject.put("day2", energyScreen.getTodayConsume());
                jsonObject.put("day3", energyScreen.getYesterdayConsume());
                jsonObject.put("week1", energyScreen.getWeekConsume());
                jsonObject.put("week2", energyScreen.getLastWeekConsume());
                jsonObject.put("month1", energyScreen.getMonthConsume());
                jsonObject.put("month2", energyScreen.getLastMonthConsume());
                jsonObject.put("day4", energyScreen.getDayDifference());
                jsonObject.put("week3", energyScreen.getWeekDifference());
                jsonObject.put("month3", energyScreen.getMonthDifference());
                jsonArray.add(jsonObject);
            }
        }


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


    @Override
    public Result listDataAll2(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) throws ParseException {

        String farmId = TokenSign.getFarmIds(httpServletRequest);
        if (farmId.length() > 2) {
            farmId = paramsMap.get("farmId");
        }

        String type = paramsMap.get("type");// 1水 2电

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

        String time = paramsMap.get("time");
        if ("".equals(time) || null == time) {
            Date timesmorning = DataUill.getTimesmorning();
            time = sdf1.format(timesmorning);
        }
        String start = time + " 00:00:00";
        String end = time + " 23:59:59";
        QueryWrapper<EnergyScreen> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).between("create_date", start, end).eq("type", type);
        List<EnergyScreen> energyScreens = screenMapper.selectList(queryWrapper);

        JSONArray jsonArray = new JSONArray();
        if (energyScreens.size() != 0) {
            for (EnergyScreen energyScreen : energyScreens) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("deviceCode", energyScreen.getDeviceCode());
                jsonObject.put("buildName", energyScreen.getBuildName());
                jsonObject.put("todayRead", energyScreen.getTodayRead());
                jsonObject.put("todayConsume", energyScreen.getTodayConsume());
                jsonObject.put("yesterdayConsume", energyScreen.getYesterdayConsume());
                jsonObject.put("weekConsume", energyScreen.getWeekConsume());
                jsonObject.put("lastWeekConsume", energyScreen.getLastWeekConsume());
                jsonObject.put("monthConsume", energyScreen.getMonthConsume());
                jsonObject.put("lastMonthConsume", energyScreen.getLastMonthConsume());
                jsonObject.put("dayDifference", energyScreen.getDayDifference());
                jsonObject.put("weekDifference", energyScreen.getWeekDifference());
                jsonObject.put("monthDifference", energyScreen.getMonthDifference());
                jsonObject.put("farmName", energyScreen.getFarmName());
                jsonArray.add(jsonObject);
            }
        }

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

    @Override
    public Result listDataTail(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) throws ParseException {
        String deviceCode = paramsMap.get("deviceCode");
        String type = paramsMap.get("type");
//        String farmId = paramsMap.get("farmId");

        if ("".equals(type) || null == type) {
            type = "1";
        }
        String startDate = paramsMap.get("startDate");
        String endDate = paramsMap.get("endDate");
        if ("".equals(startDate) || null == startDate) {
            Date date1 = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            startDate = sdf.format(date1);
            endDate = sdf.format(date1);
        }
        HashMap<String, String> map = new HashMap<>();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("type", type);
        jsonObject1.put("startDate", startDate);
        jsonObject1.put("endDate", endDate);
        List<String> list = new ArrayList<>();
        if ("".equals(deviceCode) || null == deviceCode) {
            QueryWrapper<EnergyEnvDevice> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("farm_id", 26, 29, 22, 28, 21, 33, 34, 35,23,36,37,38,27,40,41,39,42,24).ne("device_code","0102D472");
            if ("1".equals(type)) {
                queryWrapper1.eq("remark", 1);
            } else {
                queryWrapper1.eq("remark", 0);
            }
            List<EnergyEnvDevice> envDevices = envDeviceMapper.selectList(queryWrapper1);
            envDevices.forEach(item -> {
                list.add(item.getDeviceCode());
            });
            jsonObject1.put("deviceCode", list);
        } else {
            list.add(deviceCode);
            jsonObject1.put("deviceCode", list);
        }

        map.put("Content-Type", "application/json;charset=utf-8");
        String post = HttpRequest.post("http://huimv.ifarmcloud.com/huimvAdmin/energy-electricity/sendData")//http://huimv.ifarmcloud.com/
                .headerMap(map, false).body(jsonObject1.toJSONString()).timeout(30 * 1000).execute().body();
        System.out.println(post);

        JSONArray jsonArray = JSON.parseArray(post);
        System.out.println(jsonArray);
        JSONArray array = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            if (ObjectUtil.isEmpty(jsonArray.getJSONObject(i).get("other2"))) {
                jsonObject.put("farmName", "");
            } else {
                jsonObject.put("farmName", jsonArray.getJSONObject(i).get("other2"));
            }

            if (ObjectUtil.isEmpty(jsonArray.getJSONObject(i).get("other1"))) {
                jsonObject.put("buildName", "");
            } else {
                jsonObject.put("buildName", jsonArray.getJSONObject(i).get("other1"));
            }

            jsonObject.put("deviceCode", jsonArray.getJSONObject(i).get("chipCode"));
            jsonObject.put("createTime", jsonArray.getJSONObject(i).get("createDate"));

            if ("1".equals(type)) {
                jsonObject.put("value", jsonArray.getJSONObject(i).get("waterValue"));

            } else {
                jsonObject.put("value", jsonArray.getJSONObject(i).get("electricityValue"));
            }
            jsonObject.put("originalValue", jsonArray.getJSONObject(i).get("other3"));
            array.add(jsonObject);
        }
        return new Result(ResultCode.SUCCESS, array);
    }

    @Override
    public Result listAll(Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String dataType = paramsMap.get("dataType");
        List<EnergyData> energyData = new ArrayList<>();
        if ("1".equals(dataType)) {
            energyData = dataMapper.selectList(new QueryWrapper<EnergyData>().lambda()
                    .eq(EnergyData::getFarmId, farmId)
                    .eq(EnergyData::getDisplayType, 1)
                    .isNotNull(EnergyData::getWaterValue)
                    .orderByDesc(EnergyData::getCreateDate));
        }
        if ("2".equals(dataType)) {
            energyData = dataMapper.selectList(new QueryWrapper<EnergyData>().lambda()
                    .eq(EnergyData::getFarmId, farmId)
                    .eq(EnergyData::getDisplayType, 1)
                    .isNotNull(EnergyData::getElectricityValue)
                    .orderByDesc(EnergyData::getCreateDate));
        }
        if ("3".equals(dataType)) {
            energyData = dataMapper.selectList(new QueryWrapper<EnergyData>().lambda()
                    .eq(EnergyData::getFarmId, farmId)
                    .eq(EnergyData::getDisplayType, 1)
                    .isNotNull(EnergyData::getFeedValue)
                    .orderByDesc(EnergyData::getCreateDate));
        }
        if ("4".equals(dataType)) {
            energyData = dataMapper.selectList(new QueryWrapper<EnergyData>().lambda()
                    .eq(EnergyData::getFarmId, farmId)
                    .eq(EnergyData::getDisplayType, 1)
                    .isNotNull(EnergyData::getGasValue)
                    .orderByDesc(EnergyData::getCreateDate));
        }
        return new Result(ResultCode.SUCCESS, energyData);
    }

    @Override
    public Result importData(HttpServletRequest httpServletRequest, Map<String, String> paramsMap, MultipartFile files) throws Exception {
        String farmId = paramsMap.get("farmId");
        String unitId = paramsMap.get("unitId");
        String farmName = paramsMap.get("farmName");
        int anInt = Integer.parseInt(unitId);
        Map<String, String> map = new HashMap<>();
        //表头与键值对的映射关系
        map.put("序号", "id");
        map.put("网关类型", "type");
        map.put("设备编号", "deviceCode");
        map.put("互感器参数", "trans");
        map.put("位置", "deviceName");
        try (
                //这里面的对象会自动关闭
                InputStream in = files.getInputStream();
                Workbook workbook = ExcelImportSheet.getTypeFromExtends(in, files.getOriginalFilename())
        ) {

            //根据名称获取单张表对象 也可以使用getSheetAt(int index)获取单张表的对象 获取第一张表
            Sheet sheet = workbook.getSheetAt(0);
            List<EnergyEnvImport> list = ExcelImportSheet.getListFromExcel(sheet, EnergyEnvImport.class, map);
            for (EnergyEnvImport energyEnvImport : list) {
                if (StringUtils.isNotBlank(energyEnvImport.getDeviceName())) {
                    EnergyEnvDevice envDevice = new EnergyEnvDevice();
                    envDevice.setUnitName(energyEnvImport.getDeviceName());
                    envDevice.setUnitId(anInt);
                    envDevice.setDeviceName(energyEnvImport.getDeviceName());
                    envDevice.setFarmId(Integer.parseInt(farmId));
                    envDevice.setRemark(farmName);
                    if ("电表".equals(energyEnvImport.getType())) {
                        envDevice.setRemark("0");
                    } else if ("水表（大口径）".equals(energyEnvImport.getType())) {
                        envDevice.setRemark("1");
                    } else if ("水表（小口径）".equals(energyEnvImport.getType())) {
                        envDevice.setRemark("1");
                    }
                    String deviceCode = energyEnvImport.getDeviceCode();
                    envDevice.setDeviceCode(deviceCode.substring(deviceCode.length() - 8));
                    envDeviceMapper.insert(envDevice);
                    anInt++;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(10001, "数据格式异常！", false);
        } finally {
            //写着好看的
        }
        return new Result(10000, "保存成功！", true);
    }
    /*数组排序*/
    public static JSONArray jsonArraySort(JSONArray jsonArr, String sortKey, boolean is_desc) {
        //存放排序结果json数组
        JSONArray sortedJsonArray = new JSONArray();
        //用于排序的list
        List<JSONObject> jsonValues = new ArrayList<JSONObject>();
        //将参数json数组每一项取出，放入list
        if (jsonArr.size() < 8) {
            for (int i = 0; i < jsonArr.size(); i++) {
                jsonValues.add(jsonArr.getJSONObject(i));
            }
            //快速排序，重写compare方法，完成按指定字段比较，完成排序
            Collections.sort(jsonValues, new Comparator<JSONObject>() {
                //排序字段
                private final String KEY_NAME = sortKey;

                //重写compare方法
                @Override
                public int compare(JSONObject a, JSONObject b) {
                    //如果用String接会导致一位数和两位数混合比对的时候不能准确比出来，要用int类型接
                    //String valA = new String();
                    //String valB = new String();
                    Float valA = 0.00f;
                    Float valB = 0.00f;
                    try {
                        valA = Float.parseFloat(a.getString(KEY_NAME));
                        valB = Float.parseFloat(b.getString(KEY_NAME));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //是升序还是降序
                    if (is_desc) {
                        return -valA.compareTo(valB);
                    } else {
                        return -valB.compareTo(valA);
                    }

                }
            });
            //将排序后结果放入结果jsonArray
            for (int i = 0; i < jsonArr.size(); i++) {
                sortedJsonArray.add(jsonValues.get(i));
            }
        } else {
            for (int i = 0; i < jsonArr.size(); i++) {
                jsonValues.add(jsonArr.getJSONObject(i));
            }
            //快速排序，重写compare方法，完成按指定字段比较，完成排序
            Collections.sort(jsonValues, new Comparator<JSONObject>() {
                //排序字段
                private final String KEY_NAME = sortKey;

                //重写compare方法
                @Override
                public int compare(JSONObject a, JSONObject b) {
                    //如果用String接会导致一位数和两位数混合比对的时候不能准确比出来，要用int类型接
                    //String valA = new String();
                    //String valB = new String();
                    Float valA = 0.00f;
                    Float valB = 0.00f;
                    try {
                        valA = Float.parseFloat(a.getString(KEY_NAME));
                        valB = Float.parseFloat(b.getString(KEY_NAME));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //是升序还是降序
                    if (is_desc) {
                        return -valA.compareTo(valB);
                    } else {
                        return -valB.compareTo(valA);
                    }

                }
            });
            //将排序后结果放入结果jsonArray
            for (int i = 0; i < 8; i++) {
                sortedJsonArray.add(jsonValues.get(i));
            }
        }

        return sortedJsonArray;
    }

    /*数组排序*/
    public static JSONArray jsonArraySort1(JSONArray jsonArr, String sortKey, boolean is_desc) {
        //存放排序结果json数组
        JSONArray sortedJsonArray = new JSONArray();
        //用于排序的list
        List<JSONObject> jsonValues = new ArrayList<JSONObject>();
        //将参数json数组每一项取出，放入list

        for (int i = 0; i < jsonArr.size(); i++) {
            jsonValues.add(jsonArr.getJSONObject(i));
        }
        //快速排序，重写compare方法，完成按指定字段比较，完成排序
        Collections.sort(jsonValues, new Comparator<JSONObject>() {
            //排序字段
            private final String KEY_NAME = sortKey;

            //重写compare方法
            @Override
            public int compare(JSONObject a, JSONObject b) {
                //如果用String接会导致一位数和两位数混合比对的时候不能准确比出来，要用int类型接
                //String valA = new String();
                //String valB = new String();
                Float valA = 0.00f;
                Float valB = 0.00f;
                try {
                    valA = Float.parseFloat(a.getString(KEY_NAME));
                    valB = Float.parseFloat(b.getString(KEY_NAME));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //是升序还是降序
                if (is_desc) {
                    return -valA.compareTo(valB);
                } else {
                    return -valB.compareTo(valA);
                }

            }
        });
        //将排序后结果放入结果jsonArray
        if (jsonArr.size() < 5) {
            for (int i = 0; i < jsonArr.size(); i++) {
                sortedJsonArray.add(jsonValues.get(i));
            }
        } else {
            for (int i = 0; i < 5; i++) {
                sortedJsonArray.add(jsonValues.get(i));
            }
        }
        return sortedJsonArray;
    }

}
