package com.gyee.wisdom.alarm.sharding.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gyee.wisdom.alarm.sharding.entity.FaultSnap;
import com.gyee.wisdom.alarm.sharding.mapper.FaultSnapMapper;
import com.gyee.wisdom.common.utils.DateUtil;
import com.gyee.wisdom.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FaultSnapService extends ServiceImpl<FaultSnapMapper, FaultSnap> {
    @Autowired
    private FaultSnapMapper faultSnapMapper;

    /**
     * 根据条件查询所有数据
     *
     * @param stationId
     * @param windturbineId
     * @param category1
     * @param category2
     * @param category3
     * @param rank
     * @param startTime
     * @param endTime
     * @param isOpened
     * @param alertText
     * @return
     */
    public List<FaultSnap> queryAll(String stationId, String windturbineId, String category1,
                                    String category2, String category3, String rank,
                                    String startTime, String endTime, String isOpened, String alertText) throws Exception {

        QueryWrapper<FaultSnap> wrapper = new QueryWrapper<>();

        if (StringUtils.hasText(stationId))
            wrapper.eq("STATIONID", stationId);
        if (StringUtils.hasText(windturbineId))
            wrapper.eq("WINDTURBINEID", windturbineId);
        if (StringUtils.hasText(category1))
            wrapper.eq("CATEGORY1", category1);
        if (StringUtils.hasText(category2))
            wrapper.eq("CATEGORY2", category2);
        if (StringUtils.hasText(category3))
            wrapper.eq("CATEGORY3", category3);
        if (StringUtils.hasText(rank))
            wrapper.eq("RANK", rank);
        if (StringUtils.hasText(isOpened))
            wrapper.eq("ISOPENED", Integer.valueOf(isOpened));
        if (StringUtils.hasText(alertText))
            wrapper.eq("ALERTTEXT", alertText);

        if (StringUtil.isNotBlank(startTime) && StringUtil.isNotBlank(endTime))
            wrapper.between("LASTUPDATETIME", DateUtil.parseDate1(startTime), DateUtil.parseDate1(endTime));

        wrapper.orderByDesc("LASTUPDATETIME");

        List<FaultSnap> faultSnaps = baseMapper.selectList(wrapper);

        return faultSnaps;
    }

    public List<FaultSnap> getTopNumFault(String topNum) throws Exception {
        topNum = topNum.trim();

        int num = Integer.parseInt(topNum);
        if (num < 1)
            return null;
        if (num > 2000)
            num = 2000;

        return faultSnapMapper.getTopNumFault(num);
    }
}
