package com.tykj.workflowcore.user.service.impl;

import com.github.wenhao.jpa.Specifications;
import com.tykj.workflowcore.user.dao.LogContentDao;
import com.tykj.workflowcore.user.pojo.LogContent;
import com.tykj.workflowcore.user.pojo.vo.LogContentVo;
import com.tykj.workflowcore.user.pojo.vo.PageResponse;
import com.tykj.workflowcore.user.service.LogContentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.Date;
import java.util.List;

@Service
public class LogContentServiceImpl implements LogContentService {
    @Autowired
    private LogContentDao logContentDao;

    @Override
    public PageResponse<LogContent> select(LogContentVo logContentVo) {
        Date startTime = logContentVo.getStartTime();
        Date finishTime = logContentVo.getFinishTime();
        String operator = logContentVo.getOperator();
        String result = logContentVo.getResult();
        String sortType = logContentVo.getSortType();
        int page = logContentVo.getPage();
        int size = logContentVo.getSize();
        Specification<LogContent> specification = Specifications.<LogContent>and()
                .like(!StringUtils.isEmpty(operator), "operator", "%" + operator + "%")
                .like(!StringUtils.isEmpty(result), "result", "%" + result + "%")
                .gt(startTime!=null,"operateTime",startTime)
                .lt(finishTime!=null,"operateTime",finishTime)
                .build();
        if (page <= 0) {
            page = 1;
        }
        Pageable pageable;
        if (sortType!= null && sortType.equals("ASC")){
            pageable = PageRequest.of(page - 1, size, Sort.Direction.ASC, "operateTime");
        }else {
         pageable = PageRequest.of(page - 1, size, Sort.Direction.DESC, "operateTime");
        }
        List<LogContent> logContentList = logContentDao.findAll(specification, pageable).getContent();
        long count = logContentDao.count(specification);
        return new PageResponse<>(page, size, count, logContentList);
    }

    @Override
    public LogContent findById(Integer id) {
        LogContent logContent = logContentDao.findById(id).get();
        if (logContent != null){
            return logContent;
        }
        return null;
    }


    @Override
    public LogContent save(LogContent logContent) {
        LogContent logContent1 = logContentDao.save(logContent);
        if (logContent1 != null){
            return logContent1;
        }
        return null;
    }
}
