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 bills = await bill.find({ pre: false, end }).toArray();
  let data = [['下单时间','订单ID','预定量','下单账户','代理商账户','状态','返还数','来源']];
  let bills = await bill.find({ type: { $in: [ 'dspbuynumber_ctcc', 'dspbuynumber' ] },  "createdAt" : { $gt: moment("2018-08-31T16:00:00.812Z").toDate() } }).toArray();
  let _count = 0;
  bills.forEach( async ({  accountID, _id, type, createdAt, pre, preNum }) => {
    let _account = await account.findOne({_id: accountID });
    let _agent = null;
    if(_account.fromID) {
      _agent = await agent.findOne({_id: db.ObjectID(_account.fromID) });
    }
    let date = moment(createdAt).format('YYYYMMDD HH:mm:ss');
    let _pre = pre ? '预扣' : '实扣';
    let con = _account.email + '[' + _account.company + ']';
    let agent_con = _agent ? (_agent.email + '[' + _agent.company + ']') : '~';
    let a  = await dspRecognition.count({billID: _id + ''});
    let _p = preNum /3;
    let carrir = (type == 'dspbuynumber_ctcc' ? '电信' : '联通');
    _count ++;
    data.push([
      date,
      _id,
      _p,
      con,
      agent_con,
      _pre,
      a,
      carrir
    ]);
    if(_count === bills.length) {
       //console.dir(JSON.stringify(data));
       var buffer = xlsx.build([{name: "mySheetName", data: data}]);
       fs.writeFile('./data1.xlsx', buffer, function(err) {
            if (err) {
                throw err;
            }
            console.log('Hello.');
        });
    }

  });
 
}



task();


