package com.ff.weijinxiao.service;


import com.ff.weijinxiao.domain.SystemLog;
import com.ff.weijinxiao.repository.SystemLogRepository;
import com.ff.weijinxiao.util.SpecificationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SystemLogService {

    @Resource
    private SystemLogRepository systemLogRepository;


    public List<SystemLog> searchSystemLogsByTag(String beginTime, String endTime, String logAccount) {
        return systemLogRepository.findAll(new Specification<SystemLog>() {
            @Override
            public Predicate toPredicate(Root<SystemLog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (null != beginTime && beginTime.length()>0) {
                    list.add(criteriaBuilder.greaterThan(root.get("create_date").as(String.class),  beginTime));
                }
                if (null != endTime && endTime.length()>0) {
                    list.add(criteriaBuilder.lessThan(root.get("create_date").as(String.class), endTime ));
                }
                if (null != logAccount && logAccount.length()>0) {
                    list.add(criteriaBuilder.like(root.get("logAccount").as(String.class), "%" + logAccount + "%"));
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        });
    }


    public void save(SystemLog systemLog) {
        systemLogRepository.save(systemLog);
    }

    /**
     * 分页条件查询
     *
     * @param page
     * @param size
     * @param param
     * @return
     */
    public Page<SystemLog> findPage(int page, int size, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "id";
        Pageable pageable = new PageRequest(page - 1, size, direction, sort);
        return systemLogRepository.findAll(SpecificationUtil.buildSpecification(param, SystemLog.class), pageable);
    }

    /**
     * 根据条件查询List
     */
    public List<SystemLog> findList(Map<String, Object> param) {
        return systemLogRepository.findAll(SpecificationUtil.buildSpecification(param, SystemLog.class));
    }
}
