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 charge = await db.getCollection('recharge');
  
  let data = [['直客账号','直客公司','代理商账户','代理商公司','备注','日期','直客充值','直客户订单数','最近一次下单','最近一次反数']];
  let _count = 0;
  let accounts = await account.find({}).toArray();
  let agents = await agent.find({}).toArray();
  let charges = await charge.find({}).toArray();
  let roleMap = {};
  let companyMap = {}
  let agentMap = {};
  let accountMap = {};
  let accountcompanyMap = {};
  let fromMap = {};
  agents.forEach(({email,company,_id, role}) => {
    //accountIDs.push(_id);
    agentMap[ _id + ''] = email;
    roleMap[ _id + ''] = role;
    companyMap[ _id + ''] = company;
  })

  accounts.forEach(({email,company,_id,fromID}) => {
    accountMap[ _id + ''] = email + '[' + company + ']'
    fromMap[ _id + ''] = fromID;
  })

  let tasks = [];
  charges.forEach( async ({ number, accountID, meta, createdAt }) => {
    data.push([ number, accountMap[accountID + ''],accountcompanyMap[ accountID + ''], agentMap[ fromMap[accountID + '']], companyMap[fromMap[accountID + '']], meta, moment(createdAt).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();


