const db = require('../db');
const xlsx = require('node-xlsx').default;
const fs = require('fs');
const _ = require('lodash');
const moment = require('moment');
const INFINITE = 1000000000;
async function task(argument) {
  const clues = await db.getNewCollection('clues');
  const calltasks = await db.getNewCollection('calltasks');
  const orders = await db.getNewCollection('orders');
  //const analysis = await db.getCollection('analysis');
  
  let agents = await db.getNewCollection('agent_caches');
  let _agents = await agents.find({}).limit(1000000).toArray();
  let accounts = await db.getNewCollection('accounts');
  let _accounts = await accounts.find({role:1}).limit(1000000).toArray();
  //let _calltasks = await calltasks.find({duration:{$gt:0}}).limit(100000000).toArray();
  let _orders = await orders.find({}).limit(1000000).toArray();
  let agentMap = {};
  let accountMap = {};

  let orderMap = {};
  let provinceMap = {};
  let aMap = {};
  let agMap = {};
  let oMap = {}
  for(let a of _agents){
  	let { _id } = a;
  	agentMap[_id + ''] = a;
  }

  for(let a of _accounts){
  	let { _id, discount } = a;
  	let agent = discount ? (discount.junior || discount.agent) : null;
  	accountMap[_id + ''] = a;
  	if(agent) accountMap[_id + ''].agent = agent ? agentMap[ agent.id + '' ]: null;
  }

  for(let o of _orders) {
  	oMap[o._id + ''] = o.code || o._id + ''; 
  }

  //console.dir(accountMap);
  
  let _count = 0;
  let _c = 0
  let map = {};
  /*for(let c of _calltasks) {
  	let { account, unikey } = c;
  	await clues.update({ unikey, account: db.ObjectID(account) }, {
  		$set:{
  			ping: true
  		}
  	});
  	console.dir(_c ++ );
  }*/
  let _clues = await clues.find({type:"group"}).limit(INFINITE).toArray();
  console.dir(_clues.length + '==条数据');
  for(clue of _clues) {
    let { unikey, account, selfTag, remark, key, app, host, systemTag, order, province, from, calledHistory, ping } = clue;
    //let orderObj = await orders.findOne({ _id: db.ObjectID(order) });
    /*let tasks = await calltasks.find({ unikey, account }).limit(10000).toArray();
    let duration = 0;
    if(tasks && tasks.length) {
    	for(let task of tasks) {
    		duration += (task.duration || 0)
    	} 	
    }*/
    let orderID = oMap[order] || (order + '');
    let data = {
    	all: 0,
    	favor: 0,
    	pinged: 0,
    	called: 0,
    	ctccall: 0,
    	ctccfavor: 0,
    	ctccpinged: 0,
    	ctcccalled: 0
    }
    let favor = (systemTag == '有意向'  ? 1 : 0);
    let pinged = ping ? 1 : 0;
    let called = calledHistory && calledHistory.length ? 1 : 0;
    if(from == 'ctcc') {
    	data.ctccall = 1;
    	data.ctccfavor = favor;
    	data.ctcccalled = called;
    	data.ctccpinged = pinged;
    } else {
    	data.all = 1;
    	data.favor = favor;
    	data.called = called;
    	data.pinged = pinged;
    }
    
    setObj(aMap, account + '', data);
    setObj(orderMap, orderID + '', data);
    setObj(provinceMap, province + '', data);
    console.dir('处理第' + (_count++) + '条数据' );
  }

  let as = [['账户','代理商','联通线索','联通拨打线索','联通拨通线索','联通意向线索','电信线索','电信拨打线索','电信拨通线索','电信意向线索']];
  for(let k of Object.keys(aMap)) {
  	let {
    	all=0,
    	favor=0,
    	pinged=0,
    	called=0,
    	ctccall=0,
    	ctccfavor=0,
    	ctccpinged=0,
    	ctcccalled=0
    } = aMap[k];
    as.push([ (accountMap[k] ? accountMap[k].company : '-'), (accountMap[k] && accountMap[k].agent ? accountMap[k].agent.company: '-'), all, called, pinged, favor, ctccall, ctcccalled, ctccpinged, ctccfavor])
    console.dir('===')
  }
	console.dir('===go')
  let buffer = xlsx.build([{name: "mySheetName", data: as}]);
	fs.writeFile('./按账户分析.xlsx', buffer, function(err) {
	  console.dir(err + '====>')
	      if (err) {
	          throw err;
	      }
	      console.log('Hello1.');
	});

	let os = [['订单id','联通线索','联通拨打线索','联通拨通线索','联通意向线索','电信线索','电信拨打线索','电信拨通线索','电信意向线索']];
	for(let k of Object.keys(orderMap)) {
  	let {
    	all=0,
    	favor=0,
    	pinged=0,
    	called=0,
    	ctccall=0,
    	ctccfavor=0,
    	ctccpinged=0,
    	ctcccalled=0
    } = orderMap[k];
    os.push([ k, all, called, pinged, favor, ctccall, ctcccalled, ctccpinged, ctccfavor])
    console.dir('===1')
  }
console.dir('===1go'  )
  let buffer1 = xlsx.build([{name: "mySheetName", data: os}]);
	fs.writeFile('./按订单ID分析.xlsx', buffer1, function(err) {
	  console.dir(err + '====>')
	      if (err) {
	          throw err;
	      }
	      console.log('Hello2.');
	});
let ps = [['省份','联通线索','联通拨打线索','联通拨通线索','联通意向线索','电信线索','电信拨打线索','电信拨通线索','电信意向线索']];
	
for(let k of Object.keys(provinceMap)) {
  	let {
    	all=0,
    	favor=0,
    	pinged=0,
    	called=0,
    	ctccall=0,
    	ctccfavor=0,
    	ctccpinged=0,
    	ctcccalled=0
    } = provinceMap[k];
    ps.push([ k, all, called, pinged, favor, ctccall, ctcccalled, ctccpinged, ctccfavor])
    console.dir('===2')
  }
console.dir('===2go')
  let buffer2 = xlsx.build([{name: "mySheetName", data: ps}]);
	fs.writeFile('./按省份分析.xlsx', buffer2, function(err) {
	  console.dir(err + '====>')
	      if (err) {
	          throw err;
	      }
	      console.log('Hello3.');
	});
}


function setObj(target, key, Obj ) {
    if(target[ key ]) {
        for(var k in Obj) {
            if(Array.isArray(Obj[k])) target[ key ][ k ] =  (target[ key ][ k ] || []).concat(Obj[k] || []); 
            else target[ key ][ k ] = (target[ key ][ k ] || 0 ) + (Obj[k] || 0)
        }
    } else {
        target[ key ] = Obj;
    }
}

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


