package com.zhongshu.card.server.core.dao;

import com.zhongshu.card.client.model.base.SuperSearch;
import com.zhongshu.card.server.core.util.CommonUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;

/**
 * @author TRX
 * @date 2024/5/31
 */
public abstract class BaseImpl {

    /**
     * 通用创建搜索条件
     *
     * @param param
     * @return
     */
    public Criteria buildCriteria(SuperSearch param) {
        Criteria criteria = new Criteria();
        // 机构ID
        if (ObjectUtils.isNotEmpty(param.getOid())) {
            criteria.and("oid").is(param.getOid());
        }
        criteria.and("isDelete").is(Boolean.FALSE);
        return criteria;
    }

    /**
     * 通用搜索条件 不包含oid
     *
     * @param param
     * @return
     */
    public Criteria buildCriteriaNotOid(SuperSearch param) {
        Criteria criteria = new Criteria();
        criteria.and("isDelete").is(Boolean.FALSE);
        // 时间
        if (!CommonUtil.longIsEmpty(param.getStartTime()) && !CommonUtil.longIsEmpty(param.getEndTime())) {
            criteria.and("createTime").gte(param.getStartTime()).and("createTime").lte(param.getEndTime());
        }
        return criteria;
    }

    /**
     * 排序
     *
     * @param param
     * @return
     */
    public Sort buildSort(SuperSearch param) {
        Sort sort = param.getOrderSort();
        if (sort == null && param.getIsSortDesc() != null) {
            if (param.getIsSortDesc()) {
                // 倒序
                sort = Sort.by(Sort.Order.desc("sort"), Sort.Order.desc("createTime"));
            } else {
                // 升序
                sort = Sort.by(Sort.Order.asc("sort"), Sort.Order.desc("createTime"));
            }
        }
        if (ObjectUtils.isEmpty(sort)) {
            sort = Sort.by(Sort.Order.desc("createTime"));
        }
        return sort;
    }

}
