package com.sysu.admin.support.base;

import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.DateTimePath;
import com.sysu.admin.controller.crop.class_item.CropClassItem;
import com.sysu.admin.controller.crop.class_item.CropItemService;
import com.sysu.admin.controller.crop.period.CropPeriodService;
import com.sysu.admin.support.system.organ.OrganService;
import com.sysu.admin.support.shiro.ShiroService;
import com.sysu.admin.support.system.config.SConfigService;
import com.sysu.admin.support.system.user.UserService;
import com.sysu.admin.utils.shape.geoserver.GeoServerConfig;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import java.util.Date;
import java.util.Set;

/**
 * @title BaseController
 * @description
 * @author XIE
 * @date 2020年4月24日下午10:01:01
 */
@Component
public class ServiceContext {

    @Autowired
    public JPAQueryFactory mJPAQueryFactory;

    @Autowired
    public ShiroService mShiroService;

    @Lazy
    @Autowired
    public OrganService mOrganService;
    @Lazy
    @Autowired
    public UserService mUserService;
    @Lazy
    @Autowired
    public GeoServerConfig mGeoServerConfig;
    @Lazy
    @Autowired
    public SConfigService mSConfigService;

    @Lazy
    @Autowired
    public CropItemService mCropItemService;

    @Lazy
    @Autowired
    public CropPeriodService mCropPeriodService;

    /**
     * 构造日期条件
     * @param predicate 条件对象
     * @param stringPath
     * @param beforeOrAfter 查询时间之前 还是 之后的数据
     * @param val 时间
     * @return
     */
    protected Predicate createDateWhere(Predicate predicate, DateTimePath<Date> stringPath, boolean beforeOrAfter, Date val){
        if(beforeOrAfter)
            return ExpressionUtils.and(predicate, stringPath.before(val));
        else
            return ExpressionUtils.and(predicate, stringPath.after(val));
    }

    protected void validate(@Valid Object obj) {
        Set<ConstraintViolation<Object>> validateSet = Validation.buildDefaultValidatorFactory()
                .getValidator()
                .validate(obj, new Class[0]);
        if (!CollectionUtils.isEmpty(validateSet)) {
            String messages = validateSet.stream()
                    .map(ConstraintViolation::getMessage)
                    .reduce((m1, m2) -> m1 + "；" + m2)
                    .orElse("参数输入有误！");
            throw new IllegalArgumentException(messages);
        }
    }

}
