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 recharge = await db.getCollection('recharge');
  const dspRecognition = await db.getCollection('dspRecognition');
	//const _bills = await bills.find({pre:true,fromID:{$exists:1},date:'20180912'}).toArray();
  let accounts = await account.find({ role: 2 }).toArray();
  let data = [['客户账户','客户公司','代理商账户','代理商公司','预购订单量','预购订单数','实际返回订单数']];
  let _count = 0;
  console.dir(accounts.length);
  accounts.forEach( async ({ email, company, fromID, _id }) => {
    let _agent = await agent.findOne({_id: db.ObjectID(fromID) });
    let agent_email = '';
    let agent_company = '';
    if(_agent) {
      agent_email = _agent.email;
      agent_company = _agent.company;
    }
    let bills = await bill.find({ "accountID" : _id , pre: false, type: { $in: [ 'dspbuynumber', 'dspbuynumber_ctcc' ] },  "createdAt" : { $gt: moment("2018-08-31T16:00:00.812Z").toDate() }  }).toArray();
    let leng = bills.length;
    console.dir(bills.map( x => x.preNum));
    let count = 0;
    if(bills.length) {
      count = bills.map( x => x.preNum).reduce((a,b) => { return a + b })/3
    }
    //let count = _.sumBy(data, 'preNum') / 3;
    let a  = await dspRecognition.count({ "accountID" : _id + '', createdDate:{$gte: '20180901', $lte:"20180930"} });
    data.push([email, company,agent_email,agent_company,count,leng, a]);
    _count ++;
    if(_count === accounts.length) {
       //console.dir(JSON.stringify(data));
       var buffer = xlsx.build([{name: "mySheetName", data: data}]);
       fs.writeFile('./data.xlsx', buffer, function(err) {
            if (err) {
                throw err;
            }
            console.log('Hello.');
        });
    }

  });
 
}



task();


