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.EnergyFeed;
import com.huimv.admin.entity.vo.EnergyFeedDataVo;
import com.huimv.admin.mapper.BasePigpenMapper;
import com.huimv.admin.mapper.EnergyDataMapper;
import com.huimv.admin.mapper.EnergyFeedMapper;
import com.huimv.admin.service.IEnergyFeedService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-02-14
 */
@Service
public class EnergyFeedServiceImpl extends ServiceImpl<EnergyFeedMapper, EnergyFeed> implements IEnergyFeedService {

    @Autowired
    private EnergyFeedMapper energyFeedMapper;
    @Autowired
    private BasePigpenMapper basePigpenMapper;
    @Autowired
    private EnergyDataMapper dataMapper;

    @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");

        JSONArray jsonArray = new JSONArray();

        QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).eq("parent_id", id);
        List<BasePigpen> basePigpens = basePigpenMapper.selectList(queryWrapper);//所有层
        for (BasePigpen basePigpen : basePigpens) {
            Float count = 0.00f;
            QueryWrapper<BasePigpen> basePigpenQueryWrapper = new QueryWrapper<>();
            basePigpenQueryWrapper.like("other2", basePigpen.getId()).eq("farm_id", farmId).eq("f_type", 3);
            List<BasePigpen> basePigpens1 = basePigpenMapper.selectList(basePigpenQueryWrapper);//得到所有的单元
            List<Integer> idList = new ArrayList<>();
            basePigpens1.forEach(item->{
                idList.add(item.getId());
            });
            JSONObject jsonObject = new JSONObject();
            QueryWrapper<EnergyData> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("unit_id", idList).eq("farm_id", farmId);
            if (ObjectUtil.isNotEmpty(displayType)){
                queryWrapper1.eq("display_type",displayType);
            }
            DateTime dateTime = DateUtil.beginOfDay(new Date());
            queryWrapper1.ge("create_date", dateTime);
            queryWrapper1.select(" IFNULL(SUM(feed_value),'0') feedValue");
            queryWrapper1.lambda().isNotNull(EnergyData::getFeedValue);
            EnergyData energyGas = dataMapper.selectOne(queryWrapper1);

            if (ObjectUtil.isNotEmpty(energyGas)) {
                count = count + Float.parseFloat(energyGas.getFeedValue());
            } else {
                count = count + 0.00f;
            }
            DecimalFormat df = new DecimalFormat("0.00");
            jsonObject.put("value", df.format(count));
            jsonObject.put("buildName", basePigpen.getBuildName());
            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 id = paramsMap.get("id");//楼层id
        String startTime = paramsMap.get("startTime");
        String endTime = paramsMap.get("endTime");

        List<EnergyFeedDataVo> energyGasList = null;
        //默认显示本年
        if (type == null || type == "") {
            type = "3";
        }

        QueryWrapper<BasePigpen> pigpenQueryWrapper = new QueryWrapper<>();
        pigpenQueryWrapper.eq("farm_id", farmId).like("other2", id);
        List<BasePigpen> basePigpens = basePigpenMapper.selectList(pigpenQueryWrapper);//单元的集合
        List<Integer> unitIds = new ArrayList<>();
        basePigpens.forEach(item -> {
            unitIds.add(item.getId());
        });

        QueryWrapper<EnergyData> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(displayType)){
            queryWrapper.eq("display_type",displayType);
        }
        queryWrapper.isNotNull("feed_value");
        queryWrapper.eq("farm_id", farmId).in("unit_id", unitIds);
        //自定义查询
        if ("4".equals(type)) {
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
            queryWrapper.between("create_date", startTime, endTime);
            energyGasList = dataMapper.listDay2(queryWrapper);
        }
        //全年
        else if ("3".equals(type)) {
            DateTime dateTime = DateUtil.beginOfYear(new Date());
            queryWrapper.ge("create_date", dateTime);
            List<EnergyFeedDataVo> energyFeedDataVos = dataMapper.listYear2(queryWrapper);
            energyGasList = energyFeedDataVos;
        }
        //本月
        else if ("2".equals(type)) {
            Date timesMonthmorning = DataUill.getTimesMonthmorning();
            queryWrapper.ge("create_date", timesMonthmorning);
            energyGasList = dataMapper.listDay2(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<EnergyFeedDataVo> energyFeedDataVos = dataMapper.listDay2(queryWrapper);
            energyGasList = energyFeedDataVos;
        }

        return new Result(ResultCode.SUCCESS, energyGasList);

    }

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

        JSONArray jsonArray = new JSONArray();

        QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId).eq("f_type", 1);
        List<BasePigpen> basePigpens = basePigpenMapper.selectList(queryWrapper);//所有层
        for (BasePigpen basePigpen : basePigpens) {
            Float count = 0.00f;
            QueryWrapper<BasePigpen> basePigpenQueryWrapper = new QueryWrapper<>();
            basePigpenQueryWrapper.like("other2", basePigpen.getId()).eq("farm_id", farmId).eq("f_type", 3);
            List<BasePigpen> basePigpens1 = basePigpenMapper.selectList(basePigpenQueryWrapper);//得到所有的单元
            List<Integer> idList = new ArrayList<>();
            basePigpens1.forEach(item->{
                idList.add(item.getId());
            });
            JSONObject jsonObject = new JSONObject();
            QueryWrapper<EnergyData> queryWrapper1 = new QueryWrapper<>();
            if (ObjectUtil.isNotEmpty(displayType)){
                queryWrapper.eq("display_type",displayType);
            }
            queryWrapper1.in("unit_id", idList).eq("farm_id", farmId);
            queryWrapper1.lambda().isNotNull(EnergyData::getFeedValue);
            DateTime dateTime = DateUtil.beginOfWeek(new Date());
            queryWrapper1.ge("create_date", dateTime);
            queryWrapper1.select(" IFNULL(SUM(feed_value),'0') feedValue");
            EnergyData energyGas = dataMapper.selectOne(queryWrapper1);

            if (ObjectUtil.isNotEmpty(energyGas)) {
                count = count + Float.parseFloat(energyGas.getFeedValue());
            } else {
                count = count + 0.00f;
            }
            DecimalFormat df = new DecimalFormat("0.00");
            jsonObject.put("value", df.format(count));
            jsonObject.put("buildName", basePigpen.getBuildName());
            jsonObject.put("id", basePigpen.getId());
            jsonArray.add(jsonObject);
        }
        JSONArray array = jsonArraySort(jsonArray, "value", true);
        return new Result(ResultCode.SUCCESS, array);
    }

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