/*
 * 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.feed.feedingenv.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.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.modular.base.baseConfig.entity.BaseConfig;
import vip.xiaonuo.modular.base.baseConfig.mapper.BaseConfigMapper;
import vip.xiaonuo.modular.base.pigpen.mapper.BasePigpenMapper;
import vip.xiaonuo.modular.env.envdevice.entity.EnvDevice;
import vip.xiaonuo.modular.env.envdevice.entity.vo.EnvDeviceCountVo;
import vip.xiaonuo.modular.env.envdevice.param.EnvDeviceOrgIdParam;
import vip.xiaonuo.modular.feed.feedingenv.entity.FeedingEnv;
import vip.xiaonuo.modular.feed.feedingenv.mapper.FeedingEnvMapper;
import vip.xiaonuo.modular.feed.feedingenv.param.*;
import vip.xiaonuo.modular.feed.feedingenv.service.FeedingEnvService;

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

/**
 * 精准饲喂设备Service接口实现类
 *
 * @author wang
 * @date 2023/12/28 11:26
 **/
@Service
public class FeedingEnvServiceImpl extends ServiceImpl<FeedingEnvMapper, FeedingEnv> implements FeedingEnvService {

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


    @Override
    public List<FeedingEnv> page(FeedingEnvPageParam feedingEnvPageParam) {
        QueryWrapper<FeedingEnv> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", feedingEnvPageParam.getOrgId())
                .eq(StringUtils.isNotBlank(feedingEnvPageParam.getType()),"type",feedingEnvPageParam.getType());
        List<FeedingEnv> feedingEnvs = envMapper.selectList(queryWrapper);
        return feedingEnvs;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResult add(FeedingEnvAddParam feedingEnvAddParam) {
        FeedingEnv feedingEnv = BeanUtil.toBean(feedingEnvAddParam, FeedingEnv.class);
        QueryWrapper<FeedingEnv> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", feedingEnv.getOrgId())
                .eq("device_code", feedingEnv.getDeviceCode())
                .or().eq("unit_id", feedingEnv.getUnitId());
        if (ObjectUtil.isNotEmpty(envMapper.selectOne(queryWrapper))) {
            return new CommonResult(500, "编号重复或者栋舍已被绑定", false);
        } else {
            this.save(feedingEnv);
            return CommonResult.ok();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResult edit(FeedingEnvEditParam feedingEnvEditParam) {
        if (this.count(new QueryWrapper<FeedingEnv>().lambda().eq(FeedingEnv::getOrgId, feedingEnvEditParam.getOrgId())
                .eq(FeedingEnv::getUnitId, feedingEnvEditParam.getUnitId())
                .ne(FeedingEnv::getId,feedingEnvEditParam.getId())) > 0) {
            return new CommonResult(500, "栋舍已被绑定", false);
        }
        if (this.count(new QueryWrapper<FeedingEnv>().lambda().eq(FeedingEnv::getOrgId, feedingEnvEditParam.getOrgId())
                .eq(FeedingEnv::getDeviceCode, feedingEnvEditParam.getDeviceCode())
                .ne(FeedingEnv::getId,feedingEnvEditParam.getId())) > 0) {
            return new CommonResult(500, "设备编号已存在！", false);
        }
        FeedingEnv feedingEnv = this.queryEntity(feedingEnvEditParam.getId().toString());
        BeanUtil.copyProperties(feedingEnvEditParam, feedingEnv);
        this.updateById(feedingEnv);
        return CommonResult.ok();
    }

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

    @Override
    public FeedingEnv detail(FeedingEnvIdParam feedingEnvIdParam) {
        return this.queryEntity(feedingEnvIdParam.getId().toString());
    }

    @Override
    public FeedingEnv queryEntity(String id) {
        FeedingEnv feedingEnv = this.getById(id);
        if (ObjectUtil.isEmpty(feedingEnv)) {
            throw new CommonException("精准饲喂设备不存在，id值为：{}", id);
        }
        return feedingEnv;
    }

    @Override
    public JSONObject listEnv(String orgId) {
        JSONObject jsonObject = new JSONObject();
        long deviceNum = this.count(new QueryWrapper<FeedingEnv>().lambda().eq(FeedingEnv::getOrgId, orgId));
        if (deviceNum > 0){
            jsonObject.put("envCount", 0);
            jsonObject.put("onliveCount", 0);
            jsonObject.put("offliveCount", 0);
            jsonObject.put("rank", "0%");
        }else {
            jsonObject.put("envCount",deviceNum);
            long onDeviceNum = this.count(new QueryWrapper<FeedingEnv>().lambda().eq(FeedingEnv::getDeviceStatus,"1").eq(FeedingEnv::getOrgId, orgId));
            jsonObject.put("onliveCount", onDeviceNum);

            long offDeviceNum = this.count(new QueryWrapper<FeedingEnv>().lambda().eq(FeedingEnv::getDeviceStatus,"0").eq(FeedingEnv::getOrgId, orgId));
            jsonObject.put("offliveCount", offDeviceNum);
            //创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            //设置精确到小数点后两位
            numberFormat.setMaximumFractionDigits(2);
            String onlineRate = numberFormat.format((float)onDeviceNum / (float) deviceNum* 100) + "%";
            jsonObject.put("rank", onlineRate);

        }
        return jsonObject;
    }

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


    @Override
    public List<BaseConfig> deviceTypeSelector(FeedingEnvPageParam envDeviceOrgIdParam) {
        String orgId = envDeviceOrgIdParam.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;
    }
}
