const db = require('../db');
const xlsx = require('node-xlsx').default;
const fs = require('fs');
const _ = require('lodash');
const moment = require('moment');
function generateCode(leng,num) {
  let s = '';
  if(leng  <=  (num + '').length) return num + '';
  for (var i = 0; i < leng - (num + '').length; i++) {
    s += '0';
  }
  return s + (num + '');
}

async function task(email) {
   console.dir(  '=====1');
  const agent = await db.getNewCollection('agent_caches');
  const account = await db.getNewCollection('accounts');
  const orders = await db.getNewCollection('orders');
  const order_productions = await db.getNewCollection('order_productions');
  const groups = await db.getNewCollection('groups');
  const group_behaviors = await db.getNewCollection('group_behaviors');
  const clues = await db.getNewCollection('clues');
  const bills = await db.getNewCollection('bills');
  const dspRecognition = await db.getCollection('dspRecognition');
  const Recognition = await db.getCollection('recognition');
  const bill = await db.getCollection('bills');
  const dspCallTask = await db.getCollection('dspCallTask');
  console.dir(  '====2');
  let data = [['unikey','账单批次','账户','账户信息','金额','一级代理商信息','金额','录入日期']];
  let recognition_data = [['unikey','备案时间','账户','账户信息','金额','一级代理商信息','金额']];
  let call_data = [['通话unikey','时长','分钟','账户','账户信息','金额','一级代理商信息','金额','通话日期']];

  //let email = "834693562@qq.com";
  let agentInfo = await agent.findOne({  username: email });
  console.dir(agentInfo._id + '');
  let accounts = await account.find({ "discount.agent.id": agentInfo._id  }).limit(1000).toArray();
  console.dir(accounts);
  let accountsQuery = [];
  let map = {};
  let agentCode = agentInfo.code;
  accounts = accounts.forEach(x => {
    //accountsQuery.push(x._id);
    accountsQuery.push(x._id + '');
    map[x._id + ''] = {
      email: x.email,
      company: x.company,
      code: x.code
    }
  });
  console.dir(accountsQuery);


  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();
  
  let billMap = {}; // account  agent  money  info
  let money = 0;
  // 有客精选数据扣费
  let _count = 0;
  console.dir(a.length + '=====');
  for( x of a) {
    let { _id,unikey, billID, accountID, createdAt, tags, city, province, gender, groupID, carrier, systemTags, remark, tokenInfo } = x;
    money += (createdAt > mark ? 8 : 3);
    console.dir(billID);
    if(!billMap[ billID ]) {
      let { date, preNum = 0, createdAt, endTime } = await bill.findOne({_id: db.ObjectID(billID) })
      let { lastmodify } = await groups.findOne({ _id: db.ObjectID(groupID) });
      billMap[ billID ] = {
        code: 'D' + date + generateCode(3,_count),
        account: accountID,
        agent: agentInfo._id + '',
        count: (preNum || 0) / 3,
        money: 0,
        groupID,
        lastmodify,
        agentMoney: 0,
        clue:0,
        createdAt: moment(createdAt).toDate(),
        endAt: endTime ? moment(endTime).toDate() : moment(createdAt).toDate()
      }
    }
    
    billMap[ billID ].money += (createdAt > mark ? 8 : 3);
    billMap[ billID ].agentMoney += (createdAt > mark ? 8 * 0.3 : 0);
    billMap[ billID ].clue += 1;
    console.dir(tokenInfo);
    let data = {
      _id,
      tags: tags,
      calledHistory: [],
      account: db.ObjectID(accountID),
      city: city,
      province: province,
      unikey: unikey,
      code: _id + '',
      type: 'group',
      from: carrier ? carrier : 'cucc',
      key: tags.join(','),
      sex: gender,
      //token: tokenInfo && tokenInfo.tokenID ? db.ObjectID((tokenInfo.tokenID + '').replace(/saleGroupId_/,"")) : null,
      selfTag: systemTags && systemTags.length ? systemTags[systemTags.length -1] : null,
      remark: remark && remark.length ? remark[remark.length -1] : null,
      createdAt: createdAt,
      updatedAt: createdAt
    };
    if(tokenInfo && tokenInfo.tokenID ){
      if((tokenInfo.tokenID + '').indexOf('saleGroupId') >= 0) data.salegroup = db.ObjectID(tokenInfo.tokenID.replace(/saleGroupId_/,""))
      else data.token = db.ObjectID(tokenInfo.tokenID);
   }
   console.dir(data);
    await clues.insert(data);
    //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')]);
  }

  console.dir(billMap);
  for(let billID of Object.keys(billMap)) {
    let { account, agent, money, agentMoney, clue = 0, createdAt, endAt, groupID, lastmodify, count } = billMap[billID];
    let order = await orders.insert({
      award: false,
      clue,
      count: count,
      subOrder:[],
      account: db.ObjectID(account),
      meta: '',
      type: 'data',
      group: db.ObjectID(groupID),
      status: '已关闭',
      "history" : [ 
        {
            "status" : "审核中",
            "operator" : "",
            "date" : createdAt
        }, 
        {
            "status" : "执行中",
            "operator" : "",
            "date" : createdAt
        }, 
        {
            "status" : "已关闭",
            "operator" : "",
            "date" : endAt
        }
     ],
     createdAt: createdAt,
     updatedAt: endAt
    })
    let orderid = order.ops[0]._id;
    let sub = await order_productions.insert({
      group: db.ObjectID(groupID),
      groupbehavior: lastmodify,
      createdAt: createdAt,
      updatedAt: endAt,
      count: clue || 0,
      order: orderid
    })
    await bills.insert({
      _id: db.ObjectID(billID),
      createdAt: createdAt,
      updatedAt:endAt,
      subOrder:sub.ops[0]._id,
      account: db.ObjectID(account),
      money: money,
      moneyReal: money,
      moneyAward: 0,
      type : "data",
      count : clue,
      price : money / clue,
      agent : {
          id : db.ObjectID(agentInfo._id),
          "money" : agentMoney,
          "moneyReal" :agentMoney,
          "moneyAward" : 0,
          "discount" : 0.3
      }
    })
  }

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


/*  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);
    await task(email);
  }
} 

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


