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 _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','扣款状态','类型','直客扣款','直客账户','渠道商扣款','渠道账户','开始日期','结束日期','endTime','已返回数量','预扣中']];
  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 = [];
  let _tasks = [];
  let tasks1 = [];
  bills.forEach( async ({ accountID, _id, meta, type, number, agent, date,endTime, endDate, pre}) => {

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

    _tasks.push(new Promise(async (r,e) => {
         r(await _agent
                      .count({ "preNumber.billID": {$in:[_id,_id + '']} }) ||  0);
    }));


    data.push([_id + '', meta,  pre ? '预扣' : '实扣', typeMap[type], (number || 0), accountMap[accountID + ''], (agent && agent.number ? agent.number : 0), agentMap[ fromMap[accountID + ''] ], date, endDate,endTime ]);
    _count ++;
    if(_count === bills.length) {
       //console.dir(JSON.stringify(data));
       let _arrs = await Promise.all(tasks);
       let _arrs1 = await Promise.all(_tasks);
       data = data.map( (x,i) => {
        return (x.length ? x : []).concat([_arrs[i] || 0]).concat([_arrs1[i] || 0])
       })
      data.forEach( x => {
        if(x[2] == '实扣' ) {
          //console.dir(x);
          let _id = x[0];
          let endTime = x[10];
         
          if(!endTime) {
            endTime = Date.now();
          }
          let endDate = moment(endTime,'x').format('YYYYMMDD');
          let num = x[11] * 8;
          let agent_num = x[11] * 8 * 0.3;
          let update_num = agent_num.toFixed(1);
          console.dir({_id, endTime, num, agent_num, update_num});
          tasks1.push(new Promise(async (r,e) => {
            //let p = await _agent.update({  "preNumber.billID": { $in:[x[0], db.ObjectID(x[0]) ]} }, { $set: { bak_balace: ag.balace }, $pull: { preNumber: { billID:{ $in:[x[0], db.ObjectID(x[0]) ]} }}, $inc: { balace: -update_num   }});
              console.dir({ number: num, "agent.number": update_num, endTime: endTime, endDate: endDate  });
              let p1 = await bill.update({ _id:db.ObjectID(x[0]) },{ $set: { number: num, "agent.number": update_num, endTime: endTime, endDate: endDate  }})
              console.dir(p1.result.nModified);
              r('===' + p1.result.nModified);
          }))
        }
       });

       console.dir(tasks1.length + '==========>')
       console.dir(await Promise.all(tasks1));



       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();


