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');
  
  let data = [['代理商','总余额','显示余额','预扣账单／金额']];
  let _count = 0;

  let datas = await agent.find({ "role" : 2 }).toArray();
  let tasks = [];
  datas.forEach( async ({ email, company, balance,role, preNumber }) => {
    let count = 0;
    for(var k in preNumber) {
      count += (preNumber[k].number || 0)
    }
    data.push([email + company,balance, balance - count, (preNumber || []).map( x => x.billID + '') ]);
    _count ++;
    if(_count === datas.length) {
       var buffer = xlsx.build([{name: "mySheetName", data: data}]);
       fs.writeFile('./代理商信息.xlsx', buffer, function(err) {
            if (err) {
                throw err;
            }
            console.log('Hello.');
        });
    }

  });
}

function ISODateRange(date) {
    const startAt = moment(date).format(`YYYY-MM-DD 00:00:00`)
        , endAt = moment(date).add(1, 'd').format(`YYYY-MM-DD 00:00:00`)
    return [new Date(startAt), new Date(endAt)];
}

task();


