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

import com.github.microservice.components.data.mongo.mongo.helper.DBHelper;
import com.zhongshu.card.client.model.school.DictInfoSearch;
import com.zhongshu.card.server.core.dao.BaseImpl;
import com.zhongshu.card.server.core.dao.school.extend.DictInfoDaoExtend;
import com.zhongshu.card.server.core.domain.school.DictInfo;
import org.apache.commons.lang3.ObjectUtils;
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.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

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

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private DBHelper dbHelper;

    @Override
    public Page<DictInfo> page(Pageable pageable, DictInfoSearch param) {
        Criteria criteria = new Criteria();

        // 机构ID
        if (ObjectUtils.isNotEmpty(param.getOid())) {
            criteria.and("oid").is(param.getOid());
        }

        if (param.getDictInfoType() != null) {
            criteria.and("dictInfoType").is(param.getDictInfoType());
        }

        // 模糊搜索
        List<Criteria> criterias = new ArrayList<>();
        if (StringUtils.isNotEmpty(param.getName())) {
            Pattern pattern = Pattern.compile("^.*" + param.getName() + ".*$");
            criterias.add(Criteria.where("name").is(pattern));
        }
        criteria.and("isDelete").is(Boolean.FALSE);
        param.setIsSortDesc(Boolean.FALSE);
        Sort sort = buildSort(param);
        Query query = Query.query(criteria);
        query.with(sort);
        return dbHelper.pages(query, pageable, DictInfo.class);
    }

}
