'use strict';

const mongoose = require('mongoose');
const Promise = require('bluebird');
mongoose.Promise = Promise;
  // mongoose.set('debug', (coll, method, query, doc, options) => {
  //   console.log(`${coll} ${method} ${JSON.stringify(query)} ${JSON.stringify(doc)} ${options}`);
  // });
mongoose.connect('mongodb://192.168.132.129/test');

const Schema = mongoose.Schema;

const personSchema = Schema({
    age: {type: Number},
    v1: Number,
    v2: Number,
    v3: Number,
    v4: Number,
    v5: Number,
    v6: Number,
    v7: Number,
    v8: Number,
    v9: Number,
    v10: Number,
    v11: Number,
    v12: Number,
    v13: Number,
    v14: Number,
    v15: Number,
    v16: Number,
    v17: Number,
    v18: Number,
    v19: Number,
    name: String,
}, {
    autoIndex: false
})

let Person = mongoose.model('Person', personSchema, 'person');

let createIndex = function () {
  return new Promise((resolve, reject) => {
      console.log(`创建索引....`)
      mongoose.connection.collections['person'].ensureIndex({ "name": 1 }, (err) => {
        if (err) {
          console.log(`Create index ${err}`)
        } else {
          console.log('Create Index is Done!!')
        }
        resolve();
    })
  });
}

let removeIndex = function() {
  return new Promise((resolve, reject) => {
      console.log(`删除索引....`)
      mongoose.connection.collections['person'].dropIndex({ "name": 1 }, (err) => {
        if (err) {
          console.log(`Drop index ${err}`)
        } else {
          console.log('Drop Index is Done!!')
        }
        resolve();
      })
  });
}

const maxItem = 10000;

let task = Promise.coroutine(function* () {
  yield Person.remove();
  yield removeIndex();

  console.log(`造数据....`)
  let persons = [];
  for (let i = 0; i < maxItem; i++) {
      persons.push({v1: i, v2: i, v3: i, v4: i, v5: i, v6: i, v7: i, v8: i,
        v9: i, v10: i, v11: i, v12:i, v13: i, v14: i, v15: i, v16:i, v17: i,
        v18: i, v19: i,
        name: 'Lucy' + i, age: i});
  }
  yield Person.create(persons);

  // mongoose.set('debug', true);

  yield findTest();

  yield createIndex();
  yield findTest();
});

// 效果还是相当的明显的
// 删除索引....
// Drop Index is Done!!
// 造数据....
// ------统计-----
// 总时间:99428
// 平均:9.9428
// 创建索引....
// Create Index is Done!!
// ------统计-----
// 总时间:11571
// 平均:1.1571
// All done!

task().then((r) => {
    console.log('All done!')
    mongoose.connection.close();
});

let findTest = Promise.coroutine(function* (loopTime) {
  loopTime = loopTime || maxItem;
  let sum = 0;
  for (let i = 0; i < loopTime; i++) {
    let start = new Date();
    yield Person.findOne({name: 'Lucy' + (maxItem -100) }).exec();
    let used = new Date() - start;
    sum += used;
  }
  console.log(`------统计-----`)
  console.log(`总时间:` + sum)
  console.log(`平均:` + sum/loopTime);
})

