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 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 groupMap = {}
  group_arrs.forEach((data) => {
    if(data && data._id) {
     groupMap[data._id + ''] = '';
      for(var k in data) {
        console.dir(data[k])
        if(k == '_id' || k == 'createdAt') {
          groupMap[data._id + ''] += ''
        }
       else {
          groupMap[data._id + ''] += (Array.isArray(data[k])  ?  data[k].join(',') : data[k])
        }
      }
    }
  })
  console.dir(groupMap);




  let data = [['账单','客户','筛选条件','出数','拨打次数','标签','备注']];
  let _count = 0;
  let _arrs = await account.find({}).limit(1000000000000).toArray();
  let accountMap = {};
  _arrs.forEach(({email,company,_id}) => {
    accountMap[ _id + ''] = email + '[' + company + ']'
  })
  let arrs = await dspRecognition.find({}).limit(1000000000000).toArray();
  let map = {};

  arrs.forEach( async ({ tags, _id, groupID, billID, remark, systemTags, calledInfo, accountID }) => {
    if(map[billID]) {
      map[billID].remark  =  map[billID].remark.concat(remark || []);
      map[billID].systemTags  =  map[billID].systemTags.concat(systemTags || []) ;
      map[billID].called  =  map[billID].called + (calledInfo && calledInfo.length  ?  calledInfo.length : 0);
      map[billID].count = map[billID].count + 1;
    } else {
      map[billID] = {
        remark : remark || [],
        systemTags: systemTags || [],
        called: calledInfo && calledInfo.length  ? calledInfo.length : 0,
        count: 1,
        account: accountMap[accountID + ''],
        group: groupMap[groupID + ''],
      }
    }
    console.dir((++_count) + '==' + arrs.length);
    if(_count === arrs.length) {
        console.dir('ii');
        for(var k in map) {
          console.dir(k)
          data.push([k, map[k].account, map[k].group,map[k].count, map[k].called, (map[k].systemTags || []).join('、'), (map[k].remark || []).join('、')])
        }
        console.dir(data.length);
        var buffer = xlsx.build([{name: "mySheetName", data: data}]);
        fs.writeFile('./标签.xlsx', buffer, function(err) {
          console.dir(err + '====>')
              if (err) {
                  throw err;
              }
              console.log('Hello.');
        });
    }

  });

}


task();


