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

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.service.EnterpriseBaseInfoService;
import com.uas.platform.b2b.manage.core.util.StringUtils;
import com.uas.platform.b2b.manage.dao.EnterpriseBaseInfoDao;
import com.uas.platform.b2b.manage.model.EnterpriseBaseInfo;
import com.uas.platform.b2b.manage.page.criteria.LogicalExpression;
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;

/**
 * 企业基本信息操作实现
 *
 * Created by hejq on 2018-04-20.
 */
@Service
public class EnterpriseBaseInfoServiceImpl extends BaseService implements EnterpriseBaseInfoService {

    @Autowired
    private EnterpriseBaseInfoDao baseInfoDao;

    /**
     * 分页查询企业信息
     *
     * @param info    分页参数
     * @param keyword 关键字
     * @return
     */
    @Override
    public Page<EnterpriseBaseInfo> findEnterPageByKeyword(final PageInfo info, final String keyword) {
        if (!StringUtils.isEmpty(keyword)) {
            SimpleExpression name = new SimpleExpression("enName", keyword, CriterionExpression.Operator.LIKE, true);
            SimpleExpression address = new SimpleExpression("enAddress", keyword, CriterionExpression.Operator.LIKE, true);
            SimpleExpression enBusinessCode = new SimpleExpression("enBusinessCode", keyword, CriterionExpression.Operator.LIKE, true);
            if (keyword.matches(UU_REGEXP)) {
                SimpleExpression enUU = new SimpleExpression("uu", keyword, CriterionExpression.Operator.EQ, true);
                SimpleExpression[] expressions = new SimpleExpression[]{name, enUU, address, enBusinessCode};
                LogicalExpression logical = new LogicalExpression(expressions, CriterionExpression.Operator.OR);
                info.expression(logical);
            } else {
                SimpleExpression[] expressions = new SimpleExpression[]{name, address, enBusinessCode};
                LogicalExpression logical = new LogicalExpression(expressions, CriterionExpression.Operator.OR);
                info.expression(logical);
            }
        }
        return baseInfoDao.findAll(new Specification<EnterpriseBaseInfo>() {
            @Override
            public Predicate toPredicate(Root<EnterpriseBaseInfo> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                query.where(info.getPredicates(root, query, builder));
                return null;
            }
        }, info);
    }
}
