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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gyee.wisdom.alarm.sharding.entity.Datadictionary;
import com.gyee.wisdom.alarm.sharding.mapper.DatadictionaryMapper;
import com.gyee.wisdom.alarm.sharding.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class DatadictionaryService {

    @Autowired
    private DatadictionaryMapper datadictionaryMapper;

    public IPage<Datadictionary> pageQueryAll(Page<Datadictionary> page, String name, String category) {
        QueryWrapper<Datadictionary> wrapper = new QueryWrapper<>();
        if (StringUtil.isNotBlank(name))
            wrapper.like("name", name);
        if (StringUtil.isNotBlank(category))
            wrapper.eq("category", category);
        return datadictionaryMapper.selectPage(page, wrapper);
    }

    public List<Datadictionary> getAllDatadictionary() {
        return datadictionaryMapper.getAllDatadictionary();
    }

    public int saveOrUpdateDatadictionary(Datadictionary datadictionary) {
        int result = 0;
        if(datadictionary.getId()<=0){
            QueryWrapper<Datadictionary> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("id");
            List<Datadictionary> datadictionaries = datadictionaryMapper.selectList(wrapper);
            datadictionary.setId(datadictionaries.get(0).getId()+1);
            result = datadictionaryMapper.insert(datadictionary);
        }else {
            Datadictionary datadictionary1 = datadictionaryMapper.selectById(datadictionary.getId());
            if (datadictionary1!=null){
                result = datadictionaryMapper.updateById(datadictionary);
            }
            else {
                result = datadictionaryMapper.insert(datadictionary);
            }
        }
        return result;
    }

    public int deleteDatadictionary(String id) {
        return datadictionaryMapper.deleteById(id);
    }
}
