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 charge = await db.getAgentCollection('charge');
  
  let data = [['代理商充值','账号','公司','角色','备注','日期']];
  let _count = 0;

  let agents = await agent.find({}).toArray();
  let charges = await charge.find({oper:"admin@goyoo.com"}).toArray();
  let roleMap = {};
  let companyMap = {}
  let agentMap = {};
  agents.forEach(({email,company,_id, role}) => {
    //accountIDs.push(_id);
    agentMap[ _id + ''] = email;
    roleMap[ _id + ''] = role;
    companyMap[ _id + ''] = company;
  })

  let tasks = [];
  charges.forEach( async ({ money, date, accountID, oper,meta }) => {
    if(roleMap[ accountID + ''] == 2) data.push([ money, agentMap[accountID + ''],companyMap[ accountID + ''], roleMap[ accountID + ''], meta, moment(date).format('YYYY-MM-DD HH') ]);
    _count ++;
    if(_count === charges.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();


