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.management.dao.FarmDao;
import com.huimv.management.entity.FarmEntity;
import com.huimv.management.entity.OutdoorEnvironmentEntity;
import com.huimv.management.entity.vo.OutdoorEnvironmentVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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.OutdoorEnvironmentDao;
import com.huimv.management.entity.OutdoorEnvironmentEntity;
import com.huimv.management.service.OutdoorEnvironmentService;

/**
 * <p>
 *  室外环境ServiceImpl
 * </p>
 *
 * @author yinhao
 * @version 1.0
 * @date 2021/6/11 17:45
 */
@Service("outdoorEnvironmentService")
public class OutdoorEnvironmentServiceImpl extends ServiceImpl<OutdoorEnvironmentDao, OutdoorEnvironmentEntity> implements OutdoorEnvironmentService {

    @Autowired
    private FarmDao farmDao;

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

        //构建条件wrapper
        QueryWrapper<OutdoorEnvironmentVo> queryWrapper = new QueryWrapper<>();

        //异常状态
        String abnormalStatus = (String) params.get("abnormalStatus");
        if (StringUtils.isNotEmpty(abnormalStatus)) {
            queryWrapper.eq("env.abnormal_status", Boolean.parseBoolean(abnormalStatus));
        }

        //牧场名称
        String farmName = (String) params.get("farmName");
        if (farmName != null) {
            LambdaQueryWrapper<FarmEntity> query = Wrappers.<FarmEntity>lambdaQuery().like(FarmEntity::getName, farmName);
            List<Integer> idList = farmDao.selectIdList(query);
            if (CollUtil.isNotEmpty(idList)) {
                queryWrapper.in("env.farm_id", idList);
            }
        }

        //时间区间(前)
        String startTime = (String) params.get("startTime");
        if (StringUtils.isNotEmpty(startTime)) {
            queryWrapper.ge("env.collect_time", startTime);
        }

        //时间区间(后)
        String endTime = (String) params.get("endTime");
        if (StringUtils.isNotEmpty(endTime)) {
            queryWrapper.le("env.collect_time", startTime);
        }

        //排除逻辑删除
        queryWrapper.apply(" env.deleted = 0 AND farm.deleted = 0");
        //根据采集时间倒序查询
        queryWrapper.orderByDesc("env.collect_time");

        //mapper文件sql编写并返回分页对象
        IPage<OutdoorEnvironmentVo> page = baseMapper.page(new Query<>().getPage(params),queryWrapper);
        return new PageUtils(page);
    }

}