package com.huimv.management.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huimv.common.exception.RRException;
import com.huimv.management.entity.vo.ThresholdManagementVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.common.utils.PageUtils;
import com.huimv.common.utils.Query;

import com.huimv.management.dao.ThresholdManagementDao;
import com.huimv.management.entity.ThresholdManagementEntity;
import com.huimv.management.service.ThresholdManagementService;

/**
 * <p>
 * 报警阈值管理ServiceImpl
 * </p>
 *
 * @author yinhao
 * @version 1.0
 * @date 2021/6/15 13:21
 */
@Service("thresholdManagementService")
public class ThresholdManagementServiceImpl extends ServiceImpl<ThresholdManagementDao, ThresholdManagementEntity> implements ThresholdManagementService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<ThresholdManagementVo> queryWrapper = new QueryWrapper<>();

        String farmId = (String) params.get("formFarmId");
        if (StringUtils.isBlank(farmId)) {
            throw new RRException("牧场id为必传参数!");
        }
        queryWrapper.eq("farm_id", Integer.parseInt(farmId));

        String belongTo = (String) params.get("belongTo");
        if (StringUtils.isNotBlank(belongTo)) {
            queryWrapper.eq("belong_to", Short.parseShort(belongTo));
        }
        String thresholdType = (String) params.get("thresholdType");
        if (StringUtils.isNotBlank(thresholdType)) {
            queryWrapper.like("threshold_type", thresholdType);
        }
        queryWrapper.apply("threshold.deleted = 0 AND farm.deleted = 0");

        IPage<ThresholdManagementVo> page = baseMapper.page(new Query<>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public Map<String, Double> selectByType(Short type) {
        LambdaQueryWrapper<ThresholdManagementEntity> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(ThresholdManagementEntity::getBelongTo, type);

        Map<String, Double> map = new HashMap<>();
        List<ThresholdManagementEntity> thresholdManagementEntities = baseMapper.selectList(lambdaQueryWrapper);
        if (CollUtil.isNotEmpty(thresholdManagementEntities)) {
            for (ThresholdManagementEntity entity : thresholdManagementEntities) {
                map.put(entity.getThresholdType(), entity.getThresholdValue());
            }
        }
        return map;
    }
}