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

import com.github.microservice.components.data.mongo.mongo.helper.DBHelper;
import com.zhongshu.card.client.model.devices.deviceProduct.DeviceProductProvideServeSearch;
import com.zhongshu.card.server.core.dao.BaseImpl;
import com.zhongshu.card.server.core.dao.devices.extend.DeviceProductProvideServeDaoExtend;
import com.zhongshu.card.server.core.domain.devices.DeviceProductProvideServe;
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 DeviceProductProvideServeDaoImpl extends BaseImpl implements DeviceProductProvideServeDaoExtend {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private DBHelper dbHelper;

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

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

    @Override
    public long count(DeviceProductProvideServeSearch param) {
        Criteria criteria = buildFilterCriteria(param);

        Query query = Query.query(criteria);
        return mongoTemplate.count(query, DeviceProductProvideServe.class);
    }

    public Criteria buildFilterCriteria(DeviceProductProvideServeSearch param) {
        param.setOid("");
        Criteria criteria = buildCriteria(param);
        // 项目oid
        if (StringUtils.isNotEmpty(param.getProjectOid())) {
            criteria.and("projectOid").is(param.getProjectOid());
        }

        if (StringUtils.isNotEmpty(param.getDeviceProductId())) {
            criteria.and("deviceProductId").is(param.getDeviceProductId());
        }

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

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

        if (StringUtils.isNotEmpty(param.getName())) {
            Pattern pattern = Pattern.compile("^.*" + param.getName() + ".*$");
            criterias.add(Criteria.where("name").is(pattern));
        }
        if (!CollectionUtils.isEmpty(criterias)) {
            criteria.andOperator(criterias.toArray(new Criteria[]{}));
        }
        return criteria;
    }

}
