package com.liquidnet.service.adam.test;

import com.mongodb.BasicDBObject;
import com.mongodb.client.model.IndexModel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: TestMongodbIndexCreate
 * @Package com.liquidnet.service.adam.test
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/6/7 17:02
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class TestMongodbIndexCreate {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Test
    public  void createMongodbIndex(){
        String[] collectionNames = {"AdamUserInfoVo","AdamRealInfoVo","AdamThirdPartInfoVo","AdamUserMemberVo","AdamMemberVo"};
        HashMap<String,String[]> colNameMap = new HashMap();
        colNameMap.put("AdamUserInfoVo", new String[]{"uid","state"});
        colNameMap.put("AdamRealInfoVo",new String[]{"uid","state"});
        colNameMap.put("AdamThirdPartInfoVo",new String[]{"uid","state"});
        colNameMap.put("AdamUserMemberVo",new String[]{"uid"});
        colNameMap.put("AdamMemberVo",new String[]{"member_id"});
        for(String collectionName:collectionNames){
            if(mongoTemplate.collectionExists(collectionName)){
                System.out.printf("执行错误！");
                return;
            }
            for(Map.Entry<String, String[]> entry: colNameMap.entrySet()) {
                System.out.print(entry.getKey() + ":" + entry.getValue() + "\t");
                if(entry.getKey().equalsIgnoreCase(collectionName)){
                    //需要创建的索引集合
                    List<IndexModel> indexModels = new ArrayList<>();

                    String[] indexColArray = entry.getValue();
                    for(String indexName:indexColArray){
                        BasicDBObject index1 = new BasicDBObject();
                        index1.put(indexName,1);
                        indexModels.add(new IndexModel(index1));
                    }
                    mongoTemplate.createCollection(collectionName).createIndexes(indexModels);
                }
            }
        }
    }
}
