package com.huimv.admin.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
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.huimv.admin.common.utils.DataUill;
import com.huimv.admin.common.utils.Result;
import com.huimv.admin.common.utils.ResultCode;
import com.huimv.admin.entity.BasePigpen;
import com.huimv.admin.entity.EnergyData;
import com.huimv.admin.entity.EnergyWater;
import com.huimv.admin.entity.vo.EnergyVo;
import com.huimv.admin.entity.vo.EnergyWaterDataVo;
import com.huimv.admin.entity.vo.UnitEnergyVo;
import com.huimv.admin.mapper.BasePigpenMapper;
import com.huimv.admin.mapper.EnergyDataMapper;
import com.huimv.admin.mapper.EnergyEnvDeviceMapper;
import com.huimv.admin.mapper.EnergyWaterMapper;
import com.huimv.admin.service.IEnergyWaterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-02-14
 */
@Service
public class EnergyWaterServiceImpl extends ServiceImpl<EnergyWaterMapper, EnergyWater> implements IEnergyWaterService {

    @Autowired
    private BasePigpenMapper basePigpenMapper;
    @Autowired
    private EnergyWaterMapper energyWaterMapper;
    @Autowired
    private EnergyDataMapper dataMapper;
    @Autowired
    private EnergyEnvDeviceMapper energyEnvDeviceMapper;

    @Override
    public Result listPigpen(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String displayType = paramsMap.get("displayType");
        String id = paramsMap.get("id");//层id

        JSONArray jsonArray = new JSONArray();
        QueryWrapper<BasePigpen> basePigpenQueryWrapper = new QueryWrapper<>();
        basePigpenQueryWrapper.eq("farm_id", farmId).like("other2", id).eq("other3",1);
        List<BasePigpen> basePigpenList = basePigpenMapper.selectList(basePigpenQueryWrapper);//得到所有的单元
        for (BasePigpen basePigpen : basePigpenList) {
            JSONObject jsonObject = new JSONObject();
            QueryWrapper<EnergyData> queryWrapper = new QueryWrapper<>();
            if (ObjectUtil.isNotEmpty(displayType)){
                queryWrapper.eq("display_type",displayType);
            }
            queryWrapper.eq("farm_id", farmId).eq("unit_id", basePigpen.getId());
            queryWrapper.select(" IFNULL(SUM(water_value),'0') waterValue");
            DateTime dateTime = DateUtil.beginOfDay(new Date());
            queryWrapper.ge("create_date", dateTime);

            EnergyData energyWater = dataMapper.selectOne(queryWrapper);
            if (ObjectUtil.isEmpty(energyWater)) {
                jsonObject.put("buildName", basePigpen.getBuildName());
                jsonObject.put("value", 0);
                jsonObject.put("id", basePigpen.getId());
            } else {
                DecimalFormat df = new DecimalFormat("0.00");
                jsonObject.put("buildName", basePigpen.getBuildName());
                jsonObject.put("value", df.format(Float.parseFloat(energyWater.getWaterValue())));
                jsonObject.put("id", basePigpen.getId());
            }
            jsonArray.add(jsonObject);
        }


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

    @Override
    public Result listData(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");
        String displayType = paramsMap.get("displayType");
        String startTime = paramsMap.get("startTime");
        String endTime = paramsMap.get("endTime");
        String id = paramsMap.get("id");//单元id

        if (type == null || type == "") {
            type = "3";
        }

        List<EnergyWaterDataVo> energyWaterList = null;
        QueryWrapper<EnergyData> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("water_value");
        if (ObjectUtil.isNotEmpty(displayType)){
            queryWrapper.eq("display_type",displayType);
        }
        queryWrapper.eq("farm_id", farmId).eq("unit_id", id);
        //自定义查询
        if ("4".equals(type)) {
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
            queryWrapper.between("create_date", startTime, endTime);
            energyWaterList = dataMapper.listDay3(queryWrapper);
        }
        //本年
        else if ("3".equals(type)) {
            DateTime dateTime = DateUtil.beginOfYear(new Date());
            queryWrapper.ge("create_date", dateTime);
            energyWaterList = dataMapper.listYear3(queryWrapper);
        }
        //本月
        else if ("2".equals(type)) {
            Date timesMonthmorning = DataUill.getTimesMonthmorning();
            queryWrapper.ge("create_date", timesMonthmorning);
            energyWaterList = dataMapper.listDay3(queryWrapper);
        }
        //本周
        else if ("1".equals(type)) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
            queryWrapper.ge("create_date", calendar.getTime());
            List<EnergyWaterDataVo> energyWaterDataVos = dataMapper.listDay3(queryWrapper);
            energyWaterList = energyWaterDataVos;
        }
        return new Result(ResultCode.SUCCESS, energyWaterList);
    }

    @Override
    public Result listPigpenApp(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String displayType = paramsMap.get("displayType");

        List<UnitEnergyVo> unitEnergyVoList = energyEnvDeviceMapper.listWaterPigpen(farmId);
        for (UnitEnergyVo unitEnergyVo : unitEnergyVoList) {
            unitEnergyVo.setValue(dataMapper.getTodayWater(unitEnergyVo.getId(),displayType));
        }
        return new Result(ResultCode.SUCCESS, unitEnergyVoList);
    }

    @Override
    public Result listScreen(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");
        String unitId = paramsMap.get("unitId");
        String displayType = paramsMap.get("displayType");
        List<EnergyVo> waterVo = new ArrayList<>();
        //近七天
        if ("0".equals(type)){
            waterVo = dataMapper.listSevenDayWater(farmId,displayType,unitId);
        }else if ("1".equals(type)){
            LocalDate currentDate = LocalDate.now();
            // 获取过去六周的日期范围
            for (int i = 5; i >= 0; i--) {
                EnergyVo waterVo1 = new EnergyVo();
                LocalDate startDate = currentDate.minusWeeks(i).with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                LocalDate endDate = startDate.plusDays(6);
                waterVo1.setDate(startDate.toString()+" - "+endDate.toString());
                waterVo1.setValue(dataMapper.getWater(farmId,displayType,unitId,startDate.toString() + " 00:00:00",endDate + " 23:59:59"));
                waterVo.add(waterVo1);
            }
        }else {
            waterVo = dataMapper.listSixMonthWater(farmId,displayType,unitId);
        }
        return new Result(ResultCode.SUCCESS,waterVo);
    }

    public List<EnergyVo> calculate(List<EnergyVo> list){
        List<EnergyVo> result = new ArrayList<>();
        double total = 0;
        for (EnergyVo vo : list) {
            total += vo.getValue();
            EnergyVo cumulativeVo = new EnergyVo();
            cumulativeVo.setDate(vo.getDate());
            cumulativeVo.setValue(total);
            result.add(cumulativeVo);
        }
        return result;
    }

    /*数组排序*/
    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

        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));
        }

        return sortedJsonArray;
    }
}
