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 header = [['账单ID','meta','扣款状态','类型','直客扣款','直客账户','渠道商扣款','渠道账户','开始日期','结束日期','已返回数量']];
  let _count = 0;
  console.dir(accounts.length);
  let [ start , end ] = ISODateRange('20181001', '20181031');
  let data = [];
  let bills = await bill.find({ type: { '$in': ['dspbuynumber_ctcc' ]}, date: { $gte: '20180914'} }).toArray();
  console.dir(bills.length);
  let tasks = [];
  bills.forEach( async ({ accountID, _id, meta, type, number, agent, date, endDate, pre}) => {

    tasks.push(new Promise(async (r,e) => {
          console.dir({ billID: _id + ''});
         r(await dspRecognition
                      .count({ billID: _id + '' }) ||  0);
    }))

    data.push([_id + '', meta,  pre ? '预扣' : '实扣', typeMap[type], (number || 0), accountMap[accountID + ''], (agent && agent.number ? agent.number : 0), agentMap[ fromMap[accountID + ''] ], date, endDate ]);
    _count ++;
    if(_count === bills.length) {
       let _arrs = await Promise.all(tasks);
       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('./账单1.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();


