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

import com.zhongshu.card.client.model.org.RegionModel;
import com.zhongshu.card.server.core.dao.org.extend.RegionDaoExtend;
import com.zhongshu.card.server.core.domain.org.Region;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class RegionDaoImpl implements RegionDaoExtend {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public List<RegionModel> findByCodeStartingWithAndTypeAndName(RegionModel regionModel) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        Optional.ofNullable(regionModel.getCode()).ifPresent(it -> criteria.and("code").regex("^" + it));
        Optional.ofNullable(regionModel.getName()).ifPresent(it -> criteria.and("name").regex("^.*" + it + ".*$"));
        Optional.ofNullable(regionModel.getType()).ifPresent(it -> criteria.and("type").is(it));

        query.addCriteria(criteria);
        return mongoTemplate.find(query, Region.class).stream().map(it -> {
            RegionModel re = new RegionModel();
            BeanUtils.copyProperties(it, re);
            return re;
        }).collect(Collectors.toList());
    }
}
