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.NoticeInfoSearchParam;
import com.zhongshu.card.server.core.dao.BaseImpl;
import com.zhongshu.card.server.core.dao.school.extend.NoticeInfoDaoExtend;
import com.zhongshu.card.server.core.domain.school.NoticeInfo;
import com.zhongshu.card.server.core.util.CommonUtil;
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 org.springframework.util.CollectionUtils;

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

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

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private DBHelper dbHelper;

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

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

        if (ObjectUtils.isNotEmpty(param.getCreateUserId())) {
            criteria.and("createUserId").is(param.getCreateUserId());
        }

        if (!CommonUtil.longIsEmpty(param.getStartTime()) && !CommonUtil.longIsEmpty(param.getEndTime())) {
            criteria.and("createTime").gte(param.getStartTime()).and("createTime").lte(param.getEndTime());
        }

        // 模糊搜索
        List<Criteria> criterias = new ArrayList<>();
        if (StringUtils.isNotEmpty(param.getTitle())) {
            Pattern pattern = Pattern.compile("^.*" + param.getTitle() + ".*$");
            criterias.add(Criteria.where("title").is(pattern));
        }
        if (!CollectionUtils.isEmpty(criterias)) {
            criteria.andOperator(criterias.toArray(new Criteria[]{}));
        }
        criteria.and("isDelete").is(Boolean.FALSE);

        Sort sort = Sort.by(
                Sort.Order.desc("toppingTime"),
                Sort.Order.desc("createTime")
        );
        Query query = Query.query(criteria);
        query.with(sort);
        return dbHelper.pages(query, pageable, NoticeInfo.class);
    }

}
