/*
 * 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.env.envdevice.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 cn.hutool.json.JSONUtil;
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.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.core.enums.EnvDataTypeEnum;
import vip.xiaonuo.modular.env.envdevice.entity.EnvDevice;
import vip.xiaonuo.modular.env.envdevice.mapper.EnvDeviceMapper;
import vip.xiaonuo.modular.env.envdevice.param.EnvDeviceAddParam;
import vip.xiaonuo.modular.env.envdevice.param.EnvDeviceEditParam;
import vip.xiaonuo.modular.env.envdevice.param.EnvDeviceIdParam;
import vip.xiaonuo.modular.env.envdevice.param.EnvDevicePageParam;
import vip.xiaonuo.modular.env.envdevice.service.EnvDeviceService;

import javax.validation.constraints.NotBlank;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 环控设备Service接口实现类
 *
 * @author newspaper
 * @date  2023/12/18 09:58
 **/
@Service
public class EnvDeviceServiceImpl extends ServiceImpl<EnvDeviceMapper, EnvDevice> implements EnvDeviceService {

    @Autowired
    private EnvDeviceMapper envDeviceMapper;

//    @Override
//    public Page<EnvDevice> page(EnvDevicePageParam envDevicePageParam) {
//        String orgId = StpLoginUserUtil.getLoginUser().getOrgId();
//        QueryWrapper<EnvDevice> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("d.org_id",orgId).orderByAsc("d.id");
//        if(ObjectUtil.isNotEmpty(envDevicePageParam.getDeviceType())) {
//            queryWrapper.eq("d.device_type", envDevicePageParam.getDeviceType());
//        }
//        if(ObjectUtil.isNotEmpty(envDevicePageParam.getInstallPosition())) {
//            queryWrapper.eq("d.install_position", envDevicePageParam.getInstallPosition());
//        }
//        return envDeviceMapper.page(CommonPageRequest.defaultPage(), queryWrapper);
//
//
//    }

    @Override
    public Page<EnvDevice> page(EnvDevicePageParam envDevicePageParam) {
        String orgId = StpLoginUserUtil.getLoginUser().getOrgId();
        QueryWrapper<EnvDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id",orgId).orderByAsc("id");
        if(ObjectUtil.isNotEmpty(envDevicePageParam.getDeviceType())) {
            queryWrapper.eq("device_type", envDevicePageParam.getDeviceType());
        }
        if(ObjectUtil.isNotEmpty(envDevicePageParam.getInstallPosition())) {
            queryWrapper.eq("install_position", envDevicePageParam.getInstallPosition());
        }
        return  this.page(CommonPageRequest.defaultPage(), queryWrapper);


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(EnvDeviceAddParam envDeviceAddParam) {
        EnvDevice envDevice = BeanUtil.toBean(envDeviceAddParam, EnvDevice.class);
        this.save(envDevice);

        CommonDataChangeEventCenter.doAddWithData(EnvDataTypeEnum.DEVICE.getValue(), JSONUtil.createArray().put(envDevice));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(EnvDeviceEditParam envDeviceEditParam) {
        EnvDevice envDevice = this.queryEntity(envDeviceEditParam.getId());
        BeanUtil.copyProperties(envDeviceEditParam, envDevice);
        this.updateById(envDevice);

        CommonDataChangeEventCenter.doUpdateWithData(EnvDataTypeEnum.DEVICE.getValue(), JSONUtil.createArray().put(envDevice));
    }

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

        CommonDataChangeEventCenter.doDeleteWithDataId(EnvDataTypeEnum.DEVICE.getValue(), toDeleteDeviceIdList);
    }

    @Override
    public EnvDevice detail(EnvDeviceIdParam envDeviceIdParam) {
        return envDeviceMapper.detail(envDeviceIdParam.getId());
    }

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

    @Override
    public Map deviceCount() {
        Map resultMap = new HashMap();
        String orgId = StpLoginUserUtil.getLoginUser().getOrgId();
//        .eq(EnvDevice::getDeleteFlag,"NOT_DELETE")
        long deviceNum = this.count(new QueryWrapper<EnvDevice>().lambda().eq(EnvDevice::getOrgId, orgId));
        if (deviceNum == 0){
            resultMap.put("deviceNum",0);
            resultMap.put("onDeviceNum",0);
            resultMap.put("offDeviceNum",0);
            resultMap.put("onlineRate",0);
        }else {
            resultMap.put("deviceNum",deviceNum);
            long onDeviceNum = this.count(new QueryWrapper<EnvDevice>().lambda().eq(EnvDevice::getStatus,"1").eq(EnvDevice::getOrgId, orgId));
            resultMap.put("onDeviceNum",onDeviceNum);
            long offDeviceNum = this.count(new QueryWrapper<EnvDevice>().lambda().eq(EnvDevice::getStatus,"1").eq(EnvDevice::getOrgId, orgId));
            resultMap.put("offDeviceNum",offDeviceNum);
            //创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            //设置精确到小数点后两位
            numberFormat.setMaximumFractionDigits(2);
            String onlineRate = numberFormat.format((float)onDeviceNum / (float) deviceNum* 100) + "%";
            resultMap.put("onlineRate",onlineRate);
        }
        return resultMap;
    }
}
