package com.uas.platform.b2b.manage.service.impl;

import com.uas.platform.b2b.manage.core.support.SystemSession;
import com.uas.platform.b2b.manage.dao.UasSchedularDao;
import com.uas.platform.b2b.manage.model.UasSchedular;
import com.uas.platform.b2b.manage.page.PageInfo;
import com.uas.platform.b2b.manage.page.criteria.CriterionExpression;
import com.uas.platform.b2b.manage.page.criteria.SimpleExpression;
import com.uas.platform.b2b.manage.core.util.StringUtils;
import com.uas.platform.b2b.manage.page.criteria.LogicalExpression;
import com.uas.platform.b2b.manage.service.UasSchedularService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Date;

/**
 * ERP轮询地址
 *
 * @author hejq
 * @date 2018-07-04 18:42
 */
@Service
public class UasSchedularServiceImpl implements UasSchedularService {

    @Autowired
    private UasSchedularDao schedularDao;

    /**
     * 保存轮询地址配置
     *
     * @param schedular 轮询地址配置信息
     * @return
     */
    @Override
    public UasSchedular save(UasSchedular schedular) {
        schedular.setUser(SystemSession.getUser().getName());
        schedular.setDate(new Date(System.currentTimeMillis()));
        return schedularDao.save(schedular);
    }

    /**
     * 通过id删除配置信息
     *
     * @param id id
     */
    @Override
    public void deleteById(Long id) {
        if (schedularDao.exists(id)) {
            schedularDao.delete(id);
        }
    }

    /**
     * 通过关键词查询配置信息
     *
     * @param info    分页参数
     * @param keyword 关键词
     * @return
     */
    @Override
    public Page<UasSchedular> findConfigPageByKeyword(final PageInfo info, String keyword) {
        if (!StringUtils.isEmpty(keyword)) {
            SimpleExpression name = new SimpleExpression("name", keyword, CriterionExpression.Operator.LIKE, true);
            SimpleExpression url = new SimpleExpression("url", keyword, CriterionExpression.Operator.LIKE, true);
            SimpleExpression[] expressions = new SimpleExpression[]{name, url};
            LogicalExpression logical = new LogicalExpression(expressions, CriterionExpression.Operator.OR);
            info.expression(logical);
        }
        return schedularDao.findAll(new Specification<UasSchedular>() {
            @Override
            public Predicate toPredicate(Root<UasSchedular> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                query.where(info.getPredicates(root, query, builder));
                return null;
            }
        }, info);
    }
}
