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

import com.zhongshu.card.server.core.dao.org.extend.CollectionIdDaoExtend;
import com.zhongshu.card.server.core.domain.org.CollectionId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
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.data.mongodb.core.query.Update;

public class CollectionIdDaoImpl implements CollectionIdDaoExtend {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Long getNextId(String collectionName) {
        Query query = new Query(Criteria.where("collectionName").is(collectionName));
        Update update = new Update();
        update.inc("aid", 1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);
        CollectionId collectionId = mongoTemplate.findAndModify(query, update, options, CollectionId.class);
        return collectionId.getAid();
    }

    @Override
    public Long getNextId(String oid, String collectionName) {
        Query query = new Query(Criteria.where("collectionName").is(collectionName).and("epId").is(oid));
        Update update = new Update();
        update.inc("aid", 1);
        //update.set("epId",epId);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);
        CollectionId collectionId = mongoTemplate.findAndModify(query, update, options, CollectionId.class);
        return collectionId.getAid();
    }
}
