const db = require('../db');
const xlsx = require('node-xlsx').default;
const fs = require('fs');
const _ = require('lodash');
const moment = require('moment');
async function task(email) {
  const agent = await db.getAgentCollection('account');
  const account = await db.getCollection('account');
  const dspRecognition = await db.getCollection('dspRecognition');
  const Recognition = await db.getCollection('recognition');
  const dspCallTask = await db.getCollection('dspCallTask');
  let data = [['unikey','账单批次','账户','账户信息','金额','一级代理商信息','金额','录入日期']];
  let recognition_data = [['unikey','备案时间','账户','账户信息','金额','一级代理商信息','金额']];
  let call_data = [['通话unikey','时长','分钟','账户','账户信息','金额','一级代理商信息','金额','通话日期']];
  let _count = 0;
  //let email = "834693562@qq.com";
  let agentInfo = await agent.findOne({ email });
  console.dir(agentInfo._id + '');
  //console.dir(agentInfo);
  let accounts = await account.find({ fromID: agentInfo._id + '' }).limit(1000).toArray();
  let accountsQuery = [];
  let map = {};
  accounts = accounts.forEach(x => {
    accountsQuery.push(x._id);
    accountsQuery.push(x._id + '');
    map[x._id + ''] = {
      email: x.email,
      company: x.company
    }
  });
  //console.dir(accountsQuery);

  let datas = await agent.find({ "role" : 2 }).toArray();
  let tasks = [];
  let mark = moment('20180913').startOf('day').format('x');
  let a = await dspRecognition.find({ accountID: { $in: accountsQuery } }).limit(100000000000000).toArray();
  let recognitions = await Recognition.find({ pubID: { $in: accountsQuery } }).limit(100000000000000).toArray();
  let calls = await dspCallTask.find({ pubID:  { $in: accountsQuery } }).limit(100000000000000).toArray();
  
  // 有客精选数据扣费
  for( x of a) {
    let { unikey, billID, accountID, createdAt } = x;
    data.push([unikey, billID, map[accountID].email,  map[accountID].company, (createdAt > mark ? 8 : 3), agentInfo.company, (createdAt > mark ? 8 * 0.3 : 0) , moment(createdAt, 'x').format('YYYY-MM-DD HH:mm:dd')]);
  }

  for( x of calls) {
    let { duration = 0, pubID, unikey, startTime } = x;
    let minutes = Math.ceil(duration / 60);
    call_data.push([unikey, duration, minutes, map[pubID].email,map[pubID].company, (startTime > mark ? minutes : '-') , agentInfo.company, (startTime > mark ? minutes * 0.6 : 0), moment(startTime, 'x').format('YYYY-MM-DD HH:mm:dd') ])
  }

  for( x of recognitions ) {
    let { unikey, audit: audits, pubID, audit } = x;
    if(audits) {
      audit.forEach( item => {
        let { audit } = item;
        recognition_data.push([unikey, moment(audit, 'x').format('YYYY-MM-DD HH:mm:dd'), map[pubID].email, (audit > mark ? 8  : 3), agentInfo.company, (audit > mark ? 8 * 2.3  : 0) ])
      });
    }
  }

  console.dir(data.length);

  var buffer = xlsx.build([{name: "mySheetName", data: call_data }]);
  fs.writeFileSync('./bill/' + agentInfo.company +'_话单详单扣费' +'.xlsx', buffer, function(err) {
      if (err) {
          throw err;
      }
      console.log('Hello.');
  });


  var buffer1 = xlsx.build([{name: "mySheetName", data: data}]);
  fs.writeFileSync('./bill/' + agentInfo.company + '_有客精选数据详单扣费.xlsx', buffer1, function(err) {
      if (err) {
          throw err;
      }
      console.log('Hello1.');
  });

  var buffer2 = xlsx.build([{name: "mySheetName", data: recognition_data}]);
  fs.writeFileSync('./bill/'+ agentInfo.company + '_有客通详单扣费.xlsx', buffer2, function(err) {
      if (err) {
          throw err;
      }
      console.log('Hello2.');
  });
}

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)];
}


async function cycle() {
  const agent = await db.getAgentCollection('account');
  const agents = await agent.find({ role: 2, type: 1}).limit(10000).toArray();
  for(let item of agents) {
    let email = item.email;
    console.dir(email);
    task(email);
  }
} 

//task('119882374@xiaoyun.com');
cycle();


