/*
 * 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.energyElectricity.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.EnergyElectricity;
import vip.xiaonuo.modular.energy.energyElectricity.entity.vo.*;
import vip.xiaonuo.modular.energy.energyElectricity.mapper.EnergyElectricityMapper;
import vip.xiaonuo.modular.energy.energyElectricity.param.EnergyElectricityListParm;
import vip.xiaonuo.modular.energy.energyElectricity.param.EnergyElectricityTopParm;
import vip.xiaonuo.modular.energy.energyElectricity.param.EnergyElectricityUnitIdParam;
import vip.xiaonuo.modular.energy.energyElectricity.service.EnergyElectricityService;
import vip.xiaonuo.modular.energy.energyWater.mapper.EnergyWaterMapper;

import javax.validation.constraints.NotBlank;
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 EnergyElectricityServiceImpl extends ServiceImpl<EnergyElectricityMapper, EnergyElectricity> implements EnergyElectricityService {

    @Autowired
    private EnergyElectricityMapper energyElectricityMapper;
    @Autowired
    private EnergyWaterMapper energyWaterMapper;

    @Autowired
    private BaseConfigMapper baseConfigMapper;

    @Autowired
    private BasePigpenMapper basePigpenMapper;

    @Override
    public EnergyElectricityProportionVo getProportion(String orgId, String type) {
        EnergyElectricityProportionVo electricityProportion = new EnergyElectricityProportionVo();
        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<EnergyElectricityRateVo> rateList = new ArrayList<>();
        if (type.equals("0")){
            thisTotal = energyElectricityMapper.getWeekTotal(orgId);
            lastTotal = energyElectricityMapper.getLastWeekTotal(orgId);
            for (String stage : stages) {
                EnergyElectricityRateVo rate = new EnergyElectricityRateVo();
                BigDecimal weekTotal = energyElectricityMapper.getWeekTotalByType(stage, orgId);
                rate.setName(stage+"舍");
                rate.setValue(weekTotal);
                rateList.add(rate);
            }
        }else {
            thisTotal = energyElectricityMapper.getMonthTotal(orgId);
            lastTotal = energyElectricityMapper.getLastMonthTotal(orgId);
            for (String stage : stages) {
                EnergyElectricityRateVo rate = new EnergyElectricityRateVo();
                BigDecimal weekTotal = energyElectricityMapper.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);
            }
        }
        electricityProportion.setTotal(thisTotal);
        electricityProportion.setQoq(qoq);
        electricityProportion.setList(rateList);
        return electricityProportion;
    }

    @Override
    public EnergyElectricityTrendVo listTrend(EnergyElectricityListParm energyElectricityListParm) {
        String type = energyElectricityListParm.getType();
        String pigpenId = energyElectricityListParm.getPigpenId();
        String orgId = energyElectricityListParm.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 = "全场";
        }
        EnergyElectricityTrendVo electricityTrend = new EnergyElectricityTrendVo();
        List<EnergyElectricityListVo> energyElectricityList;
        if (type.equals("0")){
            energyElectricityList = energyElectricityMapper.listToday(pigpenList,orgId);
        }else if (type.equals("1")){
            energyElectricityList = energyElectricityMapper.listWeek(pigpenList,orgId);
        }else if (type.equals("2")){
            energyElectricityList = energyElectricityMapper.listMonth(pigpenList,orgId);
        }else if (type.equals("3")){
            String startDate = energyElectricityListParm.getStartDate() + " 00:00:00";
            String endDate = energyElectricityListParm.getEndDate() + " 23:59:59";
            energyElectricityList = energyElectricityMapper.listCustom(pigpenList,startDate,endDate,orgId);
        }else {
            energyElectricityList = energyElectricityMapper.listSevenDay(pigpenList,orgId);
        }
        electricityTrend.setLocation(location);
        electricityTrend.setList(energyElectricityList);
        return electricityTrend;
    }

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

    @Override
    public List<EnergyScreenVo> listScreenEnergy(String orgId) {
        List<EnergyScreenVo> energyVoList = energyElectricityMapper.listScreenEnergy(orgId);
        return energyVoList;
    }

    @Override
    public EnergyElectricityMobileVo getToday(EnergyElectricityUnitIdParam electricityUnitIdParam) {
        String orgId = electricityUnitIdParam.getOrgId();
        String pigpenId = electricityUnitIdParam.getPigpenId();
        List<String> pigpenList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(pigpenId)){
            BasePigpen basePigpen = basePigpenMapper.selectById(pigpenId);
            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参数错误!");
            }
        }
        EnergyElectricityMobileVo result= new EnergyElectricityMobileVo();
        result.setElectricityValue(energyElectricityMapper.getToday(pigpenList,orgId));
        result.setWaterValue(energyWaterMapper.getToday(pigpenList,orgId));
        return result;
    }
}
