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

import com.github.microservice.components.data.mongo.mongo.helper.DBHelper;
import com.zhongshu.card.client.model.operLogs.OperationLogsSearchParam;
import com.zhongshu.card.server.core.dao.BaseImpl;
import com.zhongshu.card.server.core.dao.user.extend.OperationLogsDaoExtend;
import com.zhongshu.card.server.core.domain.operlog.OperationLogs;
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 OperationLogsDaoImpl extends BaseImpl implements OperationLogsDaoExtend {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private DBHelper dbHelper;

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

        if (StringUtils.isNotEmpty(param.getUid())) {
            criteria.and("uid").is(param.getUid());
        }

        if (StringUtils.isNotEmpty(param.getOid())) {
            criteria.and("oid").is(param.getOid());
        }

        if (param.getLevel() != null) {
            criteria.and("level").is(param.getLevel());
        }

        // 日志关联数据ID
        if (StringUtils.isNotEmpty(param.getDataId())) {
            criteria.and("dataId").is(param.getDataId());
        }

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

        criteria.and("isDelete").is(Boolean.FALSE);
        Sort sort = buildSort(param);

        Query query = Query.query(criteria);
        query.with(sort);
        return dbHelper.pages(query, pageable, OperationLogs.class);
    }

}
