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.permiss.Device2UseUsableSearch;
import com.zhongshu.card.server.core.dao.BaseImpl;
import com.zhongshu.card.server.core.dao.devices.extend.Device2UseUsableDaoExtend;
import com.zhongshu.card.server.core.domain.devices.permiss.Device2UseUsable;
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.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

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

    @Autowired
    private DBHelper dbHelper;

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

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

    private Criteria buildFilterCriteria(Device2UseUsableSearch param) {
        Criteria criteria = buildCriteriaNotOid(param);

        if (StringUtils.isNotEmpty(param.getProjectOid())) {
            criteria.and("projectOid").is(param.getProjectOid());
        }

        if (ObjectUtils.isNotEmpty(param.getUseDataIds())) {
            criteria.and("useDataIds").in(param.getUseDataIds());
        }

        if (ObjectUtils.isNotEmpty(param.getDeviceIds())) {
            criteria.and("deviceIds").in(param.getDeviceIds());
        }

        if (!CommonUtil.longIsEmpty(param.getCurrentTime())) {
            criteria.and("endTime").gte(param.getCurrentTime());
            criteria.and("startTime").lte(param.getCurrentTime());
        }

        // 模糊搜索
        List<Criteria> criterias = new ArrayList<>();
        if (!CollectionUtils.isEmpty(criterias)) {
            criteria.andOperator(criterias.toArray(new Criteria[]{}));
        }
        return criteria;
    }

}
