package com.liquidnet.service.merchant.service.impl;

import com.liquidnet.service.base.PagedResult;
import com.liquidnet.service.merchant.dto.vo.MerchantSponsorsVo;
import com.liquidnet.service.merchant.service.IMerchantSponsorsService;
import com.liquidnet.service.merchant.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
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.stereotype.Service;

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

@Slf4j
@Service
public class MerchantSponsorsServiceImpl implements IMerchantSponsorsService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public PagedResult<MerchantSponsorsVo> search(String name, int page, int size) {
        // 查询条件
        Query query = new Query();
        String regex = String.format("%s%s%s", "^.*", name, ".*$");
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        query.addCriteria(Criteria.where("name").regex(pattern));
        query.addCriteria(Criteria.where("isOnline").is(1));

        // 总数
        long count = mongoTemplate.count(query, MerchantSponsorsVo.class, MerchantSponsorsVo.class.getSimpleName());

        // 分页
        PagedResult<MerchantSponsorsVo> pagedResult = ObjectUtil.getMerchantSponsorsVoPagedResult();
        if (count > 0) {
            query.fields().include("sponsorId").include("isOnline").include("name").include("uid");

            // 查询分页
            Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            query.with(pageable);
            List<MerchantSponsorsVo> sponsorsVoList = mongoTemplate.find(query, MerchantSponsorsVo.class, MerchantSponsorsVo.class.getSimpleName());

            pagedResult.setList(sponsorsVoList).setTotal(count, size);
        }

        return pagedResult;
    }


}
