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 _arrs1 = await account.find({}).limit(1000000000000).toArray();
  let accountMap = {};
  let accountcompanyMap = {};
  _arrs1.forEach(({email,company,_id}) => {
    accountMap[ _id + ''] = email 
    accountcompanyMap[ _id + ''] =  company 
  })
  console.dir(accountMap);
  console.dir('begin ====>');
	
  const dspCallTask = await db.getCollection('dspCallTask');
  const bills = await db.getCollection('bills');
  let billMap = {};
  let calls = await bills.find({ type: { $in: ['tycall','dspcall'] }, "date" : {$gte:'20181001'}}).limit(1000000000000).toArray();
  calls.forEach(({accountID,taskID, number}) => {
    billMap[ accountID + '' + taskID] = number 
  })


  let data = [['话单ID','秒数','通话分钟数','主叫','被叫','客户','公司','代理商账户','代理商公司', '消耗费用', '开始时间','结束时间', '录音']];
  let _count = 0;

  let arrs = await dspCallTask.find({"date": { $gte:"20181101", $lte: "20181130"}}).limit(1000000000000).toArray();
  console.dir(arrs.length);
  let map = {};

  arrs.forEach( async ({ _id, unikey, duration, date, pubID,result,caller,called, url, updateTime , startTime,  fromID }) => {
    data.push([_id, (duration || 0) / 60, duration,  called, caller,  accountMap[pubID],  accountcompanyMap[pubID], agentMap[fromID], agentcompanyMap[fromID], billMap[pubID + '' + _id], startTime ? moment(startTime,'x').format('YYYYMMDD HH:mm') : '', updateTime ? moment(updateTime,'x').format('YYYYMMDD HH:mm'): '' , url, result])
    console.dir((++_count) + '==' + arrs.length);
    if(_count === arrs.length) {
      
        var buffer = xlsx.build([{name: "mySheetName", data: data}]);
        fs.writeFile('./话单2.xlsx', buffer, function(err) {
          console.dir(err + '====>')
              if (err) {
                  throw err;
              }
              console.log('Hello.');
        });
    }


  });

}


task();


