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

import cn.exploring.engine.server.db.dao.WxSearchHistoryMapper;
import cn.exploring.engine.server.db.domain.WxSearchHistory;
import cn.exploring.engine.server.db.domain.WxSearchHistoryExample;
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 WxSearchHistoryService {
    @Resource
    private WxSearchHistoryMapper searchHistoryMapper;

    public void save(WxSearchHistory searchHistory) {
        searchHistory.setAddTime(LocalDateTime.now());
        searchHistory.setUpdateTime(LocalDateTime.now());
        searchHistoryMapper.insertSelective(searchHistory);
    }

    public List<WxSearchHistory> queryByUid(int uid) {
        WxSearchHistoryExample example = new WxSearchHistoryExample();
        example.or().andUserIdEqualTo(uid).andDeletedEqualTo(false);
        example.setDistinct(true);
        return searchHistoryMapper.selectByExampleSelective(example, WxSearchHistory.Column.keyword);
    }

    public void deleteByUid(int uid) {
        WxSearchHistoryExample example = new WxSearchHistoryExample();
        example.or().andUserIdEqualTo(uid);
        searchHistoryMapper.logicalDeleteByExample(example);
    }

    public List<WxSearchHistory> querySelective(String userId, String keyword, Integer page, Integer size, String sort, String order) {
        WxSearchHistoryExample example = new WxSearchHistoryExample();
        WxSearchHistoryExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(userId)) {
            criteria.andUserIdEqualTo(Integer.valueOf(userId));
        }
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andKeywordLike("%" + keyword + "%");
        }
        criteria.andDeletedEqualTo(false);

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

        PageHelper.startPage(page, size);
        return searchHistoryMapper.selectByExample(example);
    }
}
