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 bill = await db.getCollection('bills');
  const account = await db.getCollection('account');
  const dspRecognition = await db.getCollection('dspRecognition');
  let accountMap = {};
  let accounts = await account.find({}).toArray();
  let agents = await agent.find({}).toArray();
  let accountIDs = [];
  let agentMap = {};
  let fromMap = {};
  accounts.forEach(({email,company,_id,fromID}) => {
  	accountIDs.push(_id);
    accountMap[ _id + ''] = email + '[' + company + ']'
    fromMap[ _id + ''] = fromID;
  })
  agents.forEach(({email,company,_id}) => {
    accountIDs.push(_id);
    agentMap[ _id + ''] = email + '[' + company + ']'
  })
  let typeMap = {
      msg: '短信(联通)',
      call: '云呼(联通)',
      tycall: '精选云呼(电信)',
      audit: '备案',
      dsp: '精选短信(联通)',
      dspcall: '精选云呼(联通)',
      dspbuynumber: '精选备案(联通)',
      dspbuynumber_ctcc: '精选备案(电信)',
      dsp_ctcc: '精选短信(电信)',
      urlbuynumber: '网址取号备案',
      device: '设备'
  }
  
  let data = [['代理商','总余额','预扣账单／金额']];
  let _count = 0;

  let datas = await agent.find({ "role" : 2 }).toArray();
  let tasks = [];
  datas.forEach( async ({ email, company, balance,role, preNumber }) => {

  
    data.push([email + company,balance, (preNumber || []).map( x => x.billID + '') ]);
    _count ++;
    if(_count === datas.length) {

       data = data.map( (x,i) => {
        return (x.length ? x : []).concat([_arrs[i] || 0])
       })
       data = header.concat(data);
       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();


