const db = require('../db');
const xlsx = require('node-xlsx').default;
const fs = require('fs');
async function task(argument) {
	const agents = await db.getAgentCollection('account');
	const accounts = await db.getCollection('account');
  const bills = await db.getCollection('bills');
	const arrs = await agents.find({}).toArray();
	console.dir(arrs.length);
	let _count = 0;
	let all = [['代理商ID','代理商账户','代理商余额','折扣','直客账户','账户状态','直客余额']];
	let arr = [];
	let count = 0;
  let _arrs = [];
	arrs.forEach(  ( { _id, email, discount, company, balance, oldbalance, preNumber } ) => {
		count ++;
    if(preNumber && preNumber.length){
      _arrs.push({_id,preNumber})  
    }
	});
  _arrs.forEach(async ({_id,preNumber}) => {
    preNumber.forEach(async ({ billID }) => {
       let bill = await bills.findOne({ _id:billID, pre: false });
       if(bill){
        console.dir(bill._id + '-----' + bill.number);
        //console.dir(bill.agent);
       }
     /*  let { pre, number, agent } = bill;
       console.dir({ pre, number, agent } );*/
    })
    //console.dir(preNumber.map( x => x.billID + ''))
  });
}



async function getRechargeByAccount( accountID ) {
  let recharges =  await db
                      .getCollection('recharge');

                  let _recharges =  await recharges.aggregate([
                      {
                        $match:{
                          "accountID": db.ObjectID(accountID),
                          "removed": { $ne: true } 
                        }
                      },
                      {
                        $group:{
                          _id:null,
                          sum:{$sum:"$number"}
                        }
                      }]).toArray();
  return ( (_recharges && _recharges.length) ?  _recharges[0].sum  : 0 );
}

async function getBillByAccount( accountID ) {
  let consumes = await db
                      .getCollection('bills')
   let _consumes =  await  consumes.aggregate([
                      {
                        $match:{
                          "accountID": db.ObjectID(accountID),
                          "removed": { $ne: true }
                       /* "createdAt": { '$gt': start, '$lte': end }*/
                        }
                      },
                      {
                        $group:{
                          _id: null,
                          sum: {$sum:"$number"}
                        }
                      }]).toArray();
  return ( (_consumes && _consumes.length) ?  _consumes[0].sum  : 0 );               
}

task();


