const db = require('../db');
const xlsx = require('node-xlsx').default;
const fs = require('fs');
const _ = require('lodash');
const moment = require('moment');
async function task(argument) {
	  const agent = await db.getAgentCollection('account');
  const account = await db.getCollection('account');
  const dspRecognition = await db.getCollection('dspRecognition');
  const group = await db.getCollection('dspCallGroups');
  let group_arrs = await group.find({}).limit(1000000000000).toArray();
  let agents = await agent.find({}).toArray();
  let groupMap = {};
  let agentMap = {};
  let agentcompanyMap = {}
  group_arrs.forEach((data) => {
    if(data && data._id) {
     groupMap[data._id + ''] = data.dspgroup;
    }
  })

  agents.forEach(({email,company,_id}) => {
    agentMap[ _id + ''] = email
    agentcompanyMap[ _id + ''] = company
  })
  console.dir(groupMap);

  let data = [['unikey','订单ID','客户','公司','代理商账户','代理商公司']];
  let _count = 0;
  let _arrs = await account.find({}).limit(1000000000000).toArray();
  let accountMap = {};
  let accountcompanyMap = {};
  _arrs.forEach(({email,company,_id}) => {
    accountMap[ _id + ''] = email 
    accountcompanyMap[ _id + ''] =  company 
  })
  console.dir(accountMap);
  console.dir('begin ====>');
  let arrs = await dspRecognition.find({ createdDate: { $gte:"20181101", $lte: "20181131"} }).limit(1000000000000).toArray();
  console.dir(arrs.length);
  arrs.forEach( async ({ tags,createdDate, fromID, unikey, _id, groupID, billID, remark, systemTags, calledInfo, accountID }) => {
    let [ tag1,tag2,tag3,tag4,tag5] = tags;
    data.push([unikey, billID, accountMap[accountID],accountcompanyMap[accountID], agentMap[fromID], agentcompanyMap[fromID], createdDate])
    console.dir((++_count) + '==' + arrs.length);
    if(_count === arrs.length) {
        console.dir('ii');
        console.dir(data.length);
        var buffer = xlsx.build([{name: "mySheetName", data: data}]);
        fs.writeFile('./dongdong3.xlsx', buffer, function(err) {
          console.dir(err + '====>')
              if (err) {
                  throw err;
              }
              console.log('Hello.');
        });
    }


  });

}


task();


