/*
 * 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.energyDevice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
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.energyDevice.entity.EnergyDevice;
import vip.xiaonuo.modular.energy.energyDevice.entity.vo.EnergyDeviceCountVo;
import vip.xiaonuo.modular.energy.energyDevice.mapper.EnergyDeviceMapper;
import vip.xiaonuo.modular.energy.energyDevice.param.*;
import vip.xiaonuo.modular.energy.energyDevice.service.EnergyDeviceService;
import vip.xiaonuo.modular.env.envdevice.entity.EnvDevice;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 能耗设备Service接口实现类
 *
 * @author newspaper
 * @date  2023/12/28 08:46
 **/
@Service
public class EnergyDeviceServiceImpl extends ServiceImpl<EnergyDeviceMapper, EnergyDevice> implements EnergyDeviceService {

    @Autowired
    private BaseConfigMapper baseConfigMapper;
    @Autowired
    private BasePigpenMapper basePigpenMapper;

    @Override
    public Page<EnergyDevice> page(EnergyDevicePageParam energyDevicePageParam) {
        String orgId = energyDevicePageParam.getOrgId();
        QueryWrapper<EnergyDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EnergyDevice::getOrgId,orgId).orderByAsc(EnergyDevice::getId);
        if(ObjectUtil.isNotEmpty(energyDevicePageParam.getDeviceType())) {
            queryWrapper.lambda().eq(EnergyDevice::getDeviceTypeId, energyDevicePageParam.getDeviceType());
        }
        String installPosition = energyDevicePageParam.getInstallPosition();
        List<String> pigpenList = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(installPosition)) {
            BasePigpen basePigpen = basePigpenMapper.selectById(installPosition);
            Integer type = basePigpen.getType();
            switch (type){
                case 0:
                    List<BasePigpen> basePigpens = basePigpenMapper.selectList(new QueryWrapper<BasePigpen>().lambda().eq(BasePigpen::getParentId, basePigpen.getId()));
                    if (ObjectUtil.isNotEmpty(basePigpens)){
                        pigpenList.addAll(basePigpens.stream().map(basePigpen1 -> basePigpen1.getId()).collect(Collectors.toList()));
                    }
                    for (BasePigpen pigpen : basePigpens) {
                        List<BasePigpen> childPigpens = basePigpenMapper.selectList(new QueryWrapper<BasePigpen>().lambda().eq(BasePigpen::getParentId, pigpen.getId()));
                        if (ObjectUtil.isNotEmpty(childPigpens)){
                            pigpenList.addAll(childPigpens.stream().map(basePigpen2 -> basePigpen2.getId()).collect(Collectors.toList()));
                        }
                    }
                    break;
                case 1:
                    List<BasePigpen> pigpens = basePigpenMapper.selectList(new QueryWrapper<BasePigpen>().lambda().eq(BasePigpen::getParentId, basePigpen.getId()));
                    if (ObjectUtil.isNotEmpty(pigpens)){
                        pigpenList.addAll(pigpens.stream().map(basePigpen3 -> basePigpen3.getId()).collect(Collectors.toList()));
                    }
                case 2:
                    pigpenList.add(installPosition);
                    break;
            }
            if (ObjectUtil.isEmpty(pigpenList)){
                return new Page<>();
            }
            queryWrapper.lambda().in(EnergyDevice::getInstallPosition, pigpenList);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(EnergyDeviceAddParam energyDeviceAddParam) {
        String orgId = energyDeviceAddParam.getOrgId();
        EnergyDevice energyDevice = BeanUtil.toBean(energyDeviceAddParam, EnergyDevice.class);
        if (this.count(new QueryWrapper<EnergyDevice>().lambda()
                .eq(EnergyDevice::getOrgId,orgId)
                .eq(EnergyDevice::getDeviceCode,energyDevice.getDeviceCode())) > 0) {
            throw new CommonException("存在相同设备编号,编号为:{}",energyDevice.getDeviceCode());
        }
        if (this.count(new QueryWrapper<EnergyDevice>().lambda()
                .eq(EnergyDevice::getOrgId,orgId)
                .eq(EnergyDevice::getDeviceName,energyDevice.getDeviceName())) > 0) {
            throw new CommonException("存在相同设备名称,名称为:{}",energyDevice.getDeviceName());
        }
        if (this.count(new QueryWrapper<EnergyDevice>().lambda()
                .eq(EnergyDevice::getOrgId,orgId)
                .eq(EnergyDevice::getInstallPosition,energyDevice.getInstallPosition())) > 0) {
            throw new CommonException("该位置已存在设备!");
        }
        this.save(energyDevice);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(EnergyDeviceEditParam energyDeviceEditParam) {
        EnergyDevice energyDevice = this.queryEntity(energyDeviceEditParam.getId());
        String orgId = energyDevice.getOrgId();
        BeanUtil.copyProperties(energyDeviceEditParam, energyDevice);
        if (this.count(new QueryWrapper<EnergyDevice>().lambda()
                .eq(EnergyDevice::getOrgId,orgId)
                .eq(EnergyDevice::getDeviceCode,energyDevice.getDeviceCode())
                .ne(EnergyDevice::getId,energyDevice.getId())) > 0) {
            throw new CommonException("存在相同设备编号,编号为:{}",energyDevice.getDeviceCode());
        }
        if (this.count(new QueryWrapper<EnergyDevice>().lambda()
                .eq(EnergyDevice::getOrgId,orgId)
                .eq(EnergyDevice::getDeviceName,energyDevice.getDeviceName())
                .ne(EnergyDevice::getId,energyDevice.getId())) > 0) {
            throw new CommonException("存在相同设备名称,名称为:{}",energyDevice.getDeviceName());
        }
        if (this.count(new QueryWrapper<EnergyDevice>().lambda()
                .eq(EnergyDevice::getOrgId,orgId)
                .eq(EnergyDevice::getInstallPosition,energyDevice.getInstallPosition())
                .ne(EnergyDevice::getId,energyDevice.getId())) > 0) {
            throw new CommonException("该位置已存在设备!");
        }
        this.updateById(energyDevice);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<EnergyDeviceIdParam> energyDeviceIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(energyDeviceIdParamList, EnergyDeviceIdParam::getId));
    }

    @Override
    public EnergyDevice detail(EnergyDeviceIdParam energyDeviceIdParam) {
        return this.queryEntity(energyDeviceIdParam.getId());
    }

    @Override
    public EnergyDevice queryEntity(String id) {
        EnergyDevice energyDevice = this.getById(id);
        if(ObjectUtil.isEmpty(energyDevice)) {
            throw new CommonException("能耗设备不存在，id值为：{}", id);
        }
        return energyDevice;
    }

    @Override
    public EnergyDeviceCountVo deviceCount(EnergyDeviceOrgIdParam energyDeviceOrgIdParam) {
        EnergyDeviceCountVo energyDeviceCountVo = new EnergyDeviceCountVo();
        String orgId = energyDeviceOrgIdParam.getOrgId();
        long deviceNum = this.count(new QueryWrapper<EnergyDevice>().lambda().eq(EnergyDevice::getOrgId, orgId));
        if (deviceNum == 0){
            energyDeviceCountVo.setDeviceNum(0L);
            energyDeviceCountVo.setOnDeviceNum(0L);
            energyDeviceCountVo.setOffDeviceNum(0L);
            energyDeviceCountVo.setOnlineRate("0%");
        }else {
            energyDeviceCountVo.setDeviceNum(deviceNum);
            long onDeviceNum = this.count(new QueryWrapper<EnergyDevice>().lambda().eq(EnergyDevice::getStatus,"1").eq(EnergyDevice::getOrgId, orgId));
            energyDeviceCountVo.setOnDeviceNum(onDeviceNum);
            long offDeviceNum = this.count(new QueryWrapper<EnergyDevice>().lambda().eq(EnergyDevice::getStatus,"0").eq(EnergyDevice::getOrgId, orgId));
            energyDeviceCountVo.setOffDeviceNum(offDeviceNum);
            //创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            //设置精确到小数点后两位
            numberFormat.setMaximumFractionDigits(2);
            System.out.println("onDeviceNum"+onDeviceNum);
            System.out.println("deviceNum"+deviceNum);
            String onlineRate = numberFormat.format((float)onDeviceNum / (float) deviceNum* 100) + "%";
            System.out.println("onlineRate"+onlineRate);
            energyDeviceCountVo.setOnlineRate(onlineRate);
        }
        return energyDeviceCountVo;
    }

    @Override
    public List<BaseConfig> deviceTypeSelector(EnergyDeviceOrgIdParam energyDeviceOrgIdParam) {
        String orgId = energyDeviceOrgIdParam.getOrgId();
        String parentId = baseConfigMapper.selectOne(new QueryWrapper<BaseConfig>().lambda().eq(BaseConfig::getParentId, 0).eq(BaseConfig::getConfigName, "能耗设备类型")).getId();
        List<BaseConfig> baseConfigs = baseConfigMapper.selectList(new QueryWrapper<BaseConfig>().lambda().eq(BaseConfig::getParentId, parentId).eq(BaseConfig::getOrgId, orgId));
        return baseConfigs;
    }
}
