/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.energy.energyWater.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.modular.base.baseConfig.entity.BaseConfig;
import vip.xiaonuo.modular.base.baseConfig.mapper.BaseConfigMapper;
import vip.xiaonuo.modular.base.pigpen.entity.BasePigpen;
import vip.xiaonuo.modular.base.pigpen.mapper.BasePigpenMapper;
import vip.xiaonuo.modular.energy.energyElectricity.entity.vo.*;
import vip.xiaonuo.modular.energy.energyWater.entity.EnergyWater;
import vip.xiaonuo.modular.energy.energyWater.entity.vo.*;
import vip.xiaonuo.modular.energy.energyWater.mapper.EnergyWaterMapper;
import vip.xiaonuo.modular.energy.energyWater.param.EnergyWaterListParm;
import vip.xiaonuo.modular.energy.energyWater.param.EnergyWaterTopParm;
import vip.xiaonuo.modular.energy.energyWater.service.EnergyWaterService;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 能耗水表Service接口实现类
 *
 * @author newspaper
 * @date  2023/12/21 09:15
 **/
@Service
public class EnergyWaterServiceImpl extends ServiceImpl<EnergyWaterMapper, EnergyWater> implements EnergyWaterService {

    @Autowired
    private BaseConfigMapper baseConfigMapper;

    @Autowired
    private EnergyWaterMapper energyWaterMapper;

    @Autowired
    private BasePigpenMapper basePigpenMapper;

    @Override
    public EnergyWaterProportionVo getProportion(String orgId, String type) {
        EnergyWaterProportionVo energyWaterProportion = new EnergyWaterProportionVo();
        BigDecimal thisTotal,lastTotal;
        BigDecimal qoq = BigDecimal.ZERO;
        String parentId = baseConfigMapper.selectOne(new QueryWrapper<BaseConfig>().eq("config_name", "栋舍阶段").eq("parent_id", 0)).getId();
        List<BaseConfig> buildStage = baseConfigMapper.selectList(new QueryWrapper<BaseConfig>().eq("parent_id", parentId).orderByAsc("sort_code"));
        List<String> stages = buildStage.stream().map(config -> config.getConfigName()).collect(Collectors.toList());
        List<EnergyWaterRateVo> rateList = new ArrayList<>();
        if (type.equals("0")){
            thisTotal = energyWaterMapper.getWeekTotal(orgId);
            lastTotal = energyWaterMapper.getLastWeekTotal(orgId);
            for (String stage : stages) {
                EnergyWaterRateVo rate = new EnergyWaterRateVo();
                BigDecimal weekTotal = energyWaterMapper.getWeekTotalByType(stage, orgId);
                rate.setName(stage+"舍");
                rate.setValue(weekTotal);
                rateList.add(rate);
            }
        }else {
            thisTotal = energyWaterMapper.getMonthTotal(orgId);
            lastTotal = energyWaterMapper.getLastMonthTotal(orgId);
            for (String stage : stages) {
                EnergyWaterRateVo rate = new EnergyWaterRateVo();
                BigDecimal weekTotal = energyWaterMapper.getMonthTotalByType(stage, orgId);
                rate.setName(stage+"舍");
                rate.setValue(weekTotal);
                rateList.add(rate);
            }
        }
        if (lastTotal.compareTo(BigDecimal.ZERO) != 0) {
            qoq = thisTotal.subtract(lastTotal)
                    .divide(lastTotal, MathContext.DECIMAL64)
                    .multiply(BigDecimal.valueOf(100))
                    .setScale(2, RoundingMode.HALF_UP);
            if (thisTotal.compareTo(BigDecimal.ZERO) == 0) {
                qoq = BigDecimal.valueOf(0);
            }
        }
        energyWaterProportion.setTotal(thisTotal);
        energyWaterProportion.setQoq(qoq);
        energyWaterProportion.setList(rateList);
        return energyWaterProportion;
    }

    @Override
    public EnergyWaterTrendVo listTrend(EnergyWaterListParm energyWaterListParm) {
        String type = energyWaterListParm.getType();
        String pigpenId = energyWaterListParm.getPigpenId();
        String orgId = energyWaterListParm.getOrgId();
        String location;
        List<String> pigpenList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(pigpenId)){
            BasePigpen basePigpen = basePigpenMapper.selectById(pigpenId);
            location = basePigpen.getFullName();
            Integer pigpenType = basePigpen.getType();
            switch (pigpenType){
                case 0:
                    List<BasePigpen> basePigpens = basePigpenMapper.selectList(new QueryWrapper<BasePigpen>().lambda().eq(BasePigpen::getParentId, pigpenId));
                    if (ObjectUtil.isNotEmpty(basePigpens)){
                        List<String> collect = basePigpens.stream().map(basePigpen1 -> basePigpen1.getId()).collect(Collectors.toList());
                        List<BasePigpen> basePigpens1 = basePigpenMapper.selectList(new QueryWrapper<BasePigpen>().lambda().in(BasePigpen::getParentId, collect));
                        if (ObjectUtil.isNotEmpty(basePigpens1)){
                            pigpenList.addAll(basePigpens1.stream().map(basePigpen1 -> basePigpen1.getId()).collect(Collectors.toList()));
                        }
                    }
                    break;
                case 1:
                    List<BasePigpen> basePigpens1 = basePigpenMapper.selectList(new QueryWrapper<BasePigpen>().lambda().eq(BasePigpen::getParentId, pigpenId));
                    if (ObjectUtil.isNotEmpty(basePigpens1)){
                        pigpenList.addAll(basePigpens1.stream().map(basePigpen1 -> basePigpen1.getId()).collect(Collectors.toList()));
                    }
                    break;
                case 2:
                    pigpenList.add(pigpenId);
                    break;
                default:
                    throw new CommonException("pigpenId参数错误!");
            }
        }else {
            location = "全场";
        }
        EnergyWaterTrendVo waterTrend = new EnergyWaterTrendVo();
        List<EnergyWaterListVo> energyWaterList;
        if (type.equals("0")){
            energyWaterList = energyWaterMapper.listToday(pigpenList,orgId);
        }else if (type.equals("1")){
            energyWaterList = energyWaterMapper.listWeek(pigpenList,orgId);
        }else if (type.equals("2")){
            energyWaterList = energyWaterMapper.listMonth(pigpenList,orgId);
        }else if (type.equals("3")){
            String startDate = energyWaterListParm.getStartDate() + " 00:00:00";
            String endDate = energyWaterListParm.getEndDate() + " 23:59:59";
            energyWaterList = energyWaterMapper.listCustom(pigpenList,startDate,endDate,orgId);
        }else {
            energyWaterList = energyWaterMapper.listSevenDay(pigpenList,orgId);
        }
        waterTrend.setLocation(location);
        waterTrend.setList(energyWaterList);
        return waterTrend;
    }

    @Override
    public List<EnergyWaterTopVo> listTop(EnergyWaterTopParm energyWaterTopParm, String orgId) {
        String type = energyWaterTopParm.getType();
        List<EnergyWaterTopVo> resultList;
        if (type.equals("0")){
            resultList = energyWaterMapper.listTodayTop(orgId);
        }else if (type.equals("1")){
            resultList = energyWaterMapper.listWeekTop(orgId);
        }else if (type.equals("2")){
            resultList = energyWaterMapper.listMonthTop(orgId);
        }else {
            String startDate = energyWaterTopParm.getStartDate() + " 00:00:00";
            String endDate = energyWaterTopParm.getEndDate() + " 23:59:59";
            resultList = energyWaterMapper.listCustomTop(orgId,startDate,endDate);
        }
        return resultList;
    }
}
