package cn.exploring.engine.server.db.service;

import cn.exploring.engine.server.db.dao.WxStorageMapper;
import cn.exploring.engine.server.db.domain.WxStorage;
import cn.exploring.engine.server.db.domain.WxStorageExample;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class WxStorageService {
    @Resource
    private WxStorageMapper storageMapper;

    public void deleteByKey(String key) {
        WxStorageExample example = new WxStorageExample();
        example.or().andKeyEqualTo(key);
        storageMapper.logicalDeleteByExample(example);
    }

    public void add(WxStorage storageInfo) {
        storageInfo.setAddTime(LocalDateTime.now());
        storageInfo.setUpdateTime(LocalDateTime.now());
        storageMapper.insertSelective(storageInfo);
    }

    public WxStorage findByKey(String key) {
        WxStorageExample example = new WxStorageExample();
        example.or().andKeyEqualTo(key).andDeletedEqualTo(false);
        List<WxStorage> ss = storageMapper.selectByExample(example);
        if (ss == null || ss.size() <= 0) {
            return null;
        } else {
            return ss.get(0);
        }
    }

    public int update(WxStorage storageInfo) {
        storageInfo.setUpdateTime(LocalDateTime.now());
        return storageMapper.updateByPrimaryKeySelective(storageInfo);
    }

    public WxStorage findById(Integer id) {
        return storageMapper.selectByPrimaryKey(id);
    }

    public List<WxStorage> querySelective(String key, String name, Integer page, Integer limit, String sort, String order) {
        WxStorageExample example = new WxStorageExample();
        WxStorageExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(key)) {
            criteria.andKeyEqualTo(key);
        }
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return storageMapper.selectByExample(example);
    }
}
