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

import com.github.microservice.components.data.mongo.mongo.helper.DBHelper;
import com.zhongshu.card.client.model.org.userGroup.UserGroupToUserSearch;
import com.zhongshu.card.server.core.dao.BaseImpl;
import com.zhongshu.card.server.core.dao.org.extend.UserGroupToUserDaoExtend;
import com.zhongshu.card.server.core.domain.org.UserGroup;
import com.zhongshu.card.server.core.domain.org.UserGroupToUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author TRX
 * @CreateDate: 2023/4/12
 * @Version: 1.0
 */
public class UserGroupToUserDaoImpl extends BaseImpl implements UserGroupToUserDaoExtend {

    @Autowired
    private DBHelper dbHelper;

    @Override
    public Page<UserGroupToUser> page(Pageable pageable, UserGroupToUserSearch param) {
        Criteria criteria = buildFilterCriteria(param);

        Sort sort = buildSort(param);
        Query query = Query.query(criteria);
        query.with(sort);
        return dbHelper.pages(query, pageable, UserGroupToUser.class);
    }

    private Criteria buildFilterCriteria(UserGroupToUserSearch param) {
        Criteria criteria = buildCriteriaNotOid(param);

        if (StringUtils.isNotEmpty(param.getProjectOid())) {
            criteria.and("projectOid").is(param.getProjectOid());
        }
        if (param.getState() != null) {
            criteria.and("state").is(param.getState());
        }

        if (StringUtils.isNotEmpty(param.getGroupId())) {
            criteria.and("userGroup").is(UserGroup.build(param.getGroupId()));
        }

        // 模糊搜索
        List<Criteria> criterias = new ArrayList<>();

        if (!CollectionUtils.isEmpty(criterias)) {
            criteria.andOperator(criterias.toArray(new Criteria[]{}));
        }

        return criteria;
    }

}
