const config = require('../config/index');
const tao = require('./tao');
const mongoose = require('mongoose');
const moment = require('moment');
const Log = require('../db/mongo/tao-log');
const Kouling = require('../db/mongo/tao-kouling');
const Link = require('../db/mongo/tao-link');
const Click = require('../db/mongo/tao-log-click');
const Session = require('../db/mongo/session');
const Agent = require('../db/mongo/tao-agent');
const Schedule = require('../db/mongo/tao-schedule');
const GatherData = require('../db/mongo/tao-data');
const Ip = require('../db/mongo/tao-ip');
const Nonetkl = require('../db/mongo/tao-nonetkl-log');
const url = require('url');
const not_full = 'params not full error';
const not_right = 'params not right error';
const not_login = 'please login first';
const not_auth = 'auth error';
const {ObjectId} = mongoose.SchemaTypes;

function dateFormat(target,format) {
  return moment(new Date(target.getTime()),'x').format(format || 'YYYYMMDD HH:mm:ss');
};

function urlArgs(query) {
    var args = {};
    var pairs = query.split("&");
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf("=");
        if (pos == -1) {
            continue;
        }
        var name = pairs[i].substring(0, pos);
        var value = pairs[i].substring(pos + 1);
        args[name] = value;
    }
    return args;
}
exports.putAgent = async  (req, res, next) => {
   	let {user,password,role = 'channel'} = req.body;
   	if(!user || !password) res.status(400).send(not_full);
   	else{
   		var u = await agent.findOne({user:user});
   		if(!u) 
   			tao.saveAgent({user,password,role},function(e,result){
   				res.send({status:'ok',result:result});
   			});
   		else 
   			res.status(400).send('already  exsits error');
   	}
}
exports.putTbkl = async (req, res, next) => {
  	let {info,creater,status = 'use'} = req.body;
   	if(!info || !creater) res.status(400).send(not_full);
   	else{
   		var kl = await Kouling.findOne({info:info});
   		creater = mongoose.Types.ObjectId(creater);
   		if(!kl) 
   			tao.saveKouling({info,creater,status},function(e,result){
   				res.send({status:'ok',result:result});
   			});
   		else 
   			res.status(400).send('already  exsits error');
   	}	 
};

exports.logs = async (req, res, next) => {
    //const condition = {'$and': [{'createdAt': {'$gte': moment(start, 'YYYYMMDD').startOf('day').toDate()}}, {'createdAt': {'$lt': moment(end, 'YYYYMMDD').endOf('day').toDate()}}]};
    let sess = req.cookies['sess'];
    if(sess){
      let {limit = 100,skip = 0,sort = 'updatedAt'} = req.query;
      var sort_body = {};
      if(sort) sort_body[ sort ] = -1;
      sort_body['updatedAt'] = -1;
      let options = {limit:parseInt(limit),skip:parseInt(skip)*limit,sort:sort_body};
      var session_body  = await Session.findById(sess);
      var logs = [];
      var total = 0;
      if(session_body){
        var user = session_body.toJSON().user;
        let qs = {};
        if(user != '5a1e81f8c86fa7aa4b51b18b'){
            let schedules = await Schedule.find({qd:user},null,{limit:1000});
            schedules = schedules.map(x => { return { schedule: x.toJSON()._id }});
            qs = { $or:schedules };
            if( schedules && schedules.length ) {
              total = await Log.count(qs,null);
              logs = await Log.find(qs,null,options).populate({path:"schedule",select:"links qd",populate:{path:'qd',select:'user'}});
           }
        }
        else{
          logs = await Log.find(qs,null,options).populate({path:"schedule",select:"links qd",populate:{path:'qd',select:'user'}});
          total = await Log.count(qs,null);
        }
        logs = logs.map(x => { var d = x.toJSON();d['updatedAt'] = dateFormat(d['updatedAt']);return d;});
        res.send({ status:'ok',result:logs,pagination:{total:total,skip:parseInt(skip)+1,limit:limit}});
      }
      else{
          res.status(400).send(not_login);
      }
    }
    else{
          res.status(400).send(not_login);
    }
}

exports.getIps =  async(req,res,next) => {
  let now = moment().add(8,'hours').format('YYYYMMDD');
  let { qd = 'all', date = now,limit = 100,skip = 0} = req.query;
  if(!qd ) return res.status(400).send(not_full);
  let sess = req.cookies['sess'];
  if(sess){
      var none_tkls = [];
      var session_body  = await Session.findById(sess);
      if(session_body){
        var user = session_body.toJSON().user;
        if(user != '5a1e81f8c86fa7aa4b51b18b'){
            res.status(400).send(not_auth);
        }
        else{
          var qs = {date:date};
          if(qd != 'all')
            qs['qd'] = mongoose.Types.ObjectId(qd);
          let options = {limit:parseInt(limit),skip:parseInt(skip)*limit,sort:{times:-1}};
          console.dir(qs);
          var result =  await Ip.find(qs,null,options).populate('qd','user');
          var total =  await Ip.count(qs);
          res.send({ status:'ok',result:result,pagination:{total:total,skip:parseInt(skip)+1,limit:limit}});
        }   
      }
      else
        res.status(400).send(not_auth);
  }
  else
      res.status(400).send(not_login);
}


exports.getQdGatherData = async (req, res, next) => {
    let {limit = 100,skip = 0,sort = {'date': -1},qd} = req.query;
    let options = {limit:parseInt(limit),skip:parseInt(skip)*limit,sort};
    let sess = req.cookies['sess'];
    var qs = {};
    var clickData = {};
    var date = moment().add(8,'hours').format('YYYYMMDD');
    if(sess){
      if(qd)
        qs['qd'] = qd;
      var none_tkls = [];
      var session_body  = await Session.findById(sess);
      if(session_body){
        var user = session_body.toJSON().user;
        var match_qs = {date:date};
        var kl_qs = {status:'use'};
        //console.log(user);
        var list = [];
        var none_total = [];
        if(user != '5a1e81f8c86fa7aa4b51b18b'){
          qs = {qd:user};
          let schedules = await Schedule.find({qd:user},null,{limit:1000});
          schedules = schedules.map(x => { return { schedule: x.toJSON()._id }});
          //qs = { $or:schedules };
          if(schedules.length){
              match_qs['$or'] = schedules;
              list = await Log.aggregate([
              {
                $match:match_qs
              },
              {
                $group:{
                  _id: "$schedule",
                  sum:{ $sum:"$times" }
                }
              }
            ])
          } 
          kl_qs['creater'] = user;
        }
        else{
          list = await Log.aggregate([
              {
                $match:match_qs
              },
              {
                $group:{
                  _id: "$schedule",
                  sum:{ $sum:"$times" }
                }
              }
          ]);
          var tasks = [];
          list.forEach( async (item,i) => {
            var schedule = await Schedule.findById(item._id).populate('qd','user');
            list[i]['qd'] = schedule.toJSON().qd;
          });
          clickData = await Click.aggregate([
              {
                $match:{date:date}
              },
              {
                $group:{
                  _id: "$qd",
                  sum:{ $sum:"$times" }
                }
              }
          ]);
          clickData.forEach( async (item,i) => {
            var qd = await Agent.findById(item._id).populate('qd','user');
            //console.dir(qd.toJSON().user);
            clickData[i]['_id'] = qd.toJSON().user;
          });

         none_tkls = await Nonetkl.find({date:match_qs['date']}).populate('qd','user').limit(1000);
        }
        console.dir(qs);
        var gatherDatas = await GatherData.find(qs,null,options).populate('qd','user').populate({path:'schedules.schedule',populate:{path:'links',select:'name'}});
        let total = await GatherData.count(qs,null);
        let tkl_count = await Kouling.count(kl_qs,null);
        gatherDatas = gatherDatas.map(x => { var d = x.toJSON();d['date'] = dateFormat(d['date'],'YYYYMMDD'); return d;});
        res.send({ status:'ok',result:gatherDatas,clickData:clickData,list:list,none_tkls:none_tkls,tkl_count:tkl_count,pagination:{total:total,skip:parseInt(skip)+1,limit:limit}});
      }
      else{
          res.status(400).send(not_login);
      }
    }else{
        res.status(400).send(not_login);
    }
    
}

exports.getDynamic = async(cb) => {
  var date = moment().add(0,'hours').format('YYYYMMDD');
  var list = await Log.aggregate([
              {
                $match:{date:date}
              },
              {
                $group:{
                  _id:null,
                  sum:{ $sum:"$times" }
                }
              }]);
  var clickData = await Click.aggregate([
              {
                $match:{date:date}
              },
              {
                $group:{
                  _id:null,
                  sum:{ $sum:"$times" }
                }
              }]);
  //console.dir({list:list,clickData});
  cb && cb((list[0] && list[0].sum)+','+ (clickData[0]&&clickData[0].sum) +","+ moment().format('x'));
}

exports.putGatherData =  async(req,res,next) => {
  let { dc_times = 0,id} = req.body;
  if(!id ) return res.status(400).send(not_full);
  let sess = req.cookies['sess'];
  if(sess){
      var none_tkls = [];
      var session_body  = await Session.findById(sess);
      if(session_body){
        var user = session_body.toJSON().user;
        if(user != '5a1e81f8c86fa7aa4b51b18b'){
            res.status(400).send(not_auth);
        }
        else{
          console.dir(dc_times);
          console.dir(id);
          var result =  await GatherData.update({_id:id},{$set:{dc_times:dc_times}});
          res.send({status:'ok',result:result});
        }   
      }
      else
        res.status(400).send(not_auth);
  }
  else
      res.status(400).send(not_login);
}

exports.putIp = async(req,res,next) => {
  let { iplimit = 0,id} = req.body;
  if(!id ) return res.status(400).send(not_full);
  let sess = req.cookies['sess'];
  if(sess){
      var none_tkls = [];
      var session_body  = await Session.findById(sess);
      if(session_body){
        var user = session_body.toJSON().user;
        if(user != '5a1e81f8c86fa7aa4b51b18b'){
            res.status(400).send(not_auth);
        }
        else{
          console.dir(iplimit);
          console.dir(id);
          var result =  await Agent.update({_id:id},{$set:{iplimit:iplimit}});
          res.send({status:'ok',result:result});
        }   
      }
      else
        res.status(400).send(not_auth);
  }
  else
      res.status(400).send(not_login);
}

exports.putQdUpdate = async(req,res,next) => {
  let { ipstatus = 'use',id} = req.body;
  if(!id ) return res.status(400).send(not_full);
  let sess = req.cookies['sess'];
  if(sess){
      var none_tkls = [];
      var session_body  = await Session.findById(sess);
      if(session_body){
        var user = session_body.toJSON().user;
        if(user != '5a1e81f8c86fa7aa4b51b18b'){
            res.status(400).send(not_auth);
        }
        else{
          var result =  await Agent.update({_id:id},{$set:{ipstatus:ipstatus}});
          res.send({status:'ok',result:result});
        }   
      }
      else
        res.status(400).send(not_auth);
  }
  else
      res.status(400).send(not_login);
}

exports.getTbkls = async (req, res, next) => {
    let {limit = 100,skip = 0,sort = {'updatedAt': -1}} = req.query;
    let options = {limit:parseInt(limit),skip:parseInt(skip)*limit,sort};
    let tbkls = await Kouling.find({},null,options).populate('link','title target');
    tbkls = tbkls.map(x => { var d = x.toJSON();d['createdAt'] = dateFormat(d['createdAt']);return d;});
    let total = await Kouling.count({},null);
    res.send({ status:'ok',result:tbkls,pagination:{total:total,skip:parseInt(skip)+1,limit:limit}});
}

exports.getLinks = async (req, res, next) => {
    let {limit = 100,skip = 0,sort = {'updatedAt': -1}} = req.query;
    let options = {limit:parseInt(limit),skip:parseInt(skip)*limit,sort};
    let links = await Link.find({},null,options);
    links = links.map(x => { var d = x.toJSON();d['createdAt'] = dateFormat(d['createdAt']);return d;})
    let total = await Link.count({},null);
    var tasks = [];
    links.forEach(item => {
      tasks.push(Schedule.find({status:'use',links:{ '$in':[ item._id ]}}).populate('qd','user').limit(1000));
    });
    var arrs = await Promise.all(tasks);
    arrs.forEach( (x,i) => {
      if(x){
        links[i]['qd'] = '';
        x.forEach( (y,j) =>{
          if(y){
            y = y.toJSON();
              if(links[i]['qd'] += ((j !==0 ? "，" : '') +(y.qd ?  y.qd.user : '')));
          }
        });
      }
    });
    res.send({ status:'ok',result:links,pagination:{total:total,skip:parseInt(skip)+1,limit:limit}});
}

exports.createLink = async (req, res, next) => {
    var {quan,pid,good,name,select = 'target'} = req.body;
    console.dir((select == 'good' && !good) || (select == 'good' && (!pid || !good || !quan  || !name)));
    if((select == 'good' && !good) || (select != 'good' && (!pid || !good || !quan  || !name))) 
       res.status(400).send(not_full);
    else{
      try {
        let quanQuery = '';
        if(select !== 'good' && quan)  quanQuery = urlArgs(url.parse(quan).query);
        let goodQuery = urlArgs(url.parse(good).query);
        console.dir(goodQuery);
        if(!goodQuery['id'])
            res.status(400).send(not_full);
        else{
            let goodInfo  = await tao.getGood(goodQuery['id']);
            let title = (req.body.title && req.body.title.length) ? req.body.title : goodInfo['title'];
            let pic = goodInfo['pict_url'] || '';
            let target  = '';
            console.dir(select);
            if(select == 'target')
               target = 'https://uland.taobao.com/coupon/edetail?activityId='+ quanQuery['activityId']+'&itemId='+goodQuery['id']+'&pid='+pid+'&dx=1&src=tkm_tkmwz'; 
            if(select == 'good')
               target = good;
            if(select == 'quan')
              target = quan;
            console.dir(target);
            tao.saveLink({name,quan,pid,good,title,pic,target},function(e,result){
              if(e) throw e;
              res.send({result:'ok',result:result})
            });
        }
      }catch(e){
        console.dir(e);
        res.status(400).send(e);
      }
    }
}

exports.getSchedules = async (req, res, next) => {
    let {limit = 100,skip = 0,sort = {'createdAt': -1},qd = 'all'} = req.query;
    let options = {limit:parseInt(limit),skip:parseInt(skip)*limit,sort};
    var qs = {};
    if(qd != 'all')
      qs = {qd:qd}
    console.dir(qs);
    let schedules = await Schedule.find(qs,null,options).populate('links','name title target').populate('qd','user');
    var tasks = [];
    schedules.forEach( (item) => {
        tasks.push(Kouling.count({schedule:item._id,status:'use'}));
    });
    //schedules = schedules.map(x => { x = x.toJSON(); ;return x });
    //console.dir(schedules);
    Promise.all(tasks).then(async function(arr){
      let total = await Schedule.count(qs,null);
      schedules = schedules.map( (x,i) => { var a = x.toJSON();if(a.final){ a.final = moment(a.final,'x').format('YYYYMMDD HH:mm:ss') } ;a['createdAt'] = dateFormat(a['createdAt']); a['count'] = arr[i]; return a});
      res.send({ status:'ok',result:schedules,pagination:{total:total,skip:parseInt(skip)+1,limit:limit}});
    });    
}

exports.getQds = async (req, res, next) => {
    let {limit = 100,skip = 0,sort = {'createdAt': -1}} = req.query;
    let options = {limit:parseInt(limit),skip:parseInt(skip)*limit,sort};
    let qds = await Agent.find({user:{$ne:'admin'}},null,options);
    let total = await Agent.count({user:{$ne:'admin'}},null,options);
    var tasks = [];
    var _tasks = [];
    qds.forEach( (item) => {
        tasks.push(Kouling.count({creater:item._id,status:'use'}));
        _tasks.push(Schedule.count({qd:item._id,status:'use'}));
    });
    var arrs = await Promise.all(tasks);
    var _arrs = await Promise.all(_tasks);
    qds = qds.map((x,i) => {
      x = x.toJSON();
      x['tkl_count'] = arrs[i];
      x['schedule_count'] = _arrs[i];
      return x;
    });
    //console.dir(_arrs);
    res.send({ status:'ok',result:qds,pagination:{total:total,skip:parseInt(skip)+1,limit:limit}});   
}

exports.createQd = async (req, res, next) => {
    let {user,info = 'xxx',password = 'abc123',role='channel'} = req.body;
    tao.saveAgent({user,info,password,role},function(e,result){
      if(e) res.status(400),send(e);
      else  res.send({ status:'ok',result:result});  
    });
    
}
exports.updateAutoSchedule = async (req, res, next) => {
    let {scheduleId,auto} = req.body;
    console.dir(req.body);
    let result = await Schedule.update({_id:scheduleId},{$set:{auto:auto}},{multi:true});
    res.send({ status:'ok',schedule:result});
}

exports.updateSchedule = async (req, res, next) => {
    let {scheduleId,status} = req.body;
    var modify_result  = {};

    if(status == 'disable'){
        remove_result  = await Kouling.update({status:'use',schedule:scheduleId},{$set:{status:'disable'}},{multi:true});
        let result = await Schedule.update({_id:scheduleId},{$set:{status:status}},{multi:true});
        res.send({ status:'ok',schedule:result,remove_result:remove_result});
    }
    else{
      var schedule = await Schedule.findById(scheduleId).populate('links');
      schedule = schedule.toJSON();
      var links = schedule.links;
      var qd = schedule.qd;
      var tasks = [];
      links.forEach(item => {
        var data = {
          title:item.title,
          target:item.target,
          pic:item.pic,
          qd:qd,
          link:item._id,
          schedule:schedule._id
        }
        for(var i=0;i<5;i++){
          tasks.push(createTbkl(data));
        }
      });
      var tkls = await Promise.all(tasks);
      if(tkls && tkls.length){
          var ids = [];
          for(var k in tkls){
            ids.push(tkls[k]._id);
          } 
          let result = await Schedule.update({_id:scheduleId},{$set:{status:status}},{multi:true});
          //var remove_result  = await Kouling.update({status:'use',schedule:schedule._id,_id:{'$nin':ids}},{$set:{status:'disable'}},{multi:true});
          res.send({status:'ok',schedule:result,new:tkls});
      }
      else
          res.status(400).send('error');
    }
}

exports.createSchedule = async (req, res, next) => {
    let {user,times,status='use',names,final} = req.body;
    var links = [];
    try{
        if(!user || !times || !names) 
           res.status(400).send(not_full);
        else{
          var agent = await Agent.findOne({user:user});
          names = names.split("@");
          names.forEach(async item => {
             links.push(Link.findOne({name:item}));
          });
          Promise.all(links).then(function(arr){
            arr = arr.map(x => x.toJSON()); //获取所有推广页id
            ids = arr.map(x => x._id);
            if(agent && ids.length){
              var qd = agent.toJSON()['_id'];
              var links = ids;
              var tkl_Tasks = [];
              if(final) final = parseInt(final);
              tao.saveSchedule({qd,links,status,times,final},function(e,result){
                  if(e || !result._id) throw (e || result);
                  var schedule = result._id;
                  arr.forEach(async item => {
                    item['link'] = item._id;
                    item['schedule'] = schedule;
                    item['qd'] = qd;
                    for(let i = 0;i<5;i++){
                       tkl_Tasks.push(createTbkl(item));
                    }
                  });
                  Promise.all(tkl_Tasks).then(function(arrs){
                    arrs.map(x => x.toJSON());
                    res.send({status:'ok',result:result,kls:arrs});
                  });
              });
            }
            else{
              res.status(400).send(not_right);
            }
          });
        }
    }catch(e){
      console.dir(e);
      res.status(400).send(not_right);
    }
}

exports.newTbkl = async (req, res, next) => {
    let {id} = req.body;
    var schedule = await Schedule.findById(id).populate('links');
    schedule = schedule.toJSON();
    var links = schedule.links;
    var qd = schedule.qd;
    var tasks = [];
    links.forEach(item => {
      var data = {
        title:item.title,
        target:item.target,
        pic:item.pic,
        qd:qd,
        link:item._id,
        schedule:schedule._id
      }
      for(var i=0;i<5;i++){
        tasks.push(createTbkl(data));
      }
    });
    var result = await Promise.all(tasks);
    if(result && result.length){
        var ids = [];
        for(var k in result){
          ids.push(result[k]._id);
        } 
        var remove_result  = await Kouling.update({status:'use',schedule:schedule._id,_id:{'$nin':ids}},{$set:{status:'disable'}},{multi:true});
        res.send({result:'ok',new:result,remove_result:remove_result});
    }
    else
      res.send({result:'ok',new:result,remove_result:{nModified:0}});
}


exports.adminTbkl = async(req,res,next) => {

   var { num = 10,quan,pid,good} = req.body;

   if(!pid || !good || !quan ) return res.status(400).send(not_full);
   let sess = req.cookies['sess'];
    if(sess){
      var none_tkls = [];
      var session_body  = await Session.findById(sess);
      if(session_body){
        var user = session_body.toJSON().user;
        if(user != '5a1e81f8c86fa7aa4b51b18b'){
            res.status(400).send(not_auth);
        }
        else{
          var quanQuery = urlArgs(url.parse(quan).query);
          var goodQuery = urlArgs(url.parse(good).query);
          if(!pid || !goodQuery['id'])
              res.status(400).send(not_full);
          else{
              var goodInfo  = await tao.getGood(goodQuery['id']);
              var title = goodInfo['title'];
              var pic = goodInfo['pict_url'] || '';
              var target = 'https://uland.taobao.com/coupon/edetail?activityId='+ quanQuery['activityId']+'&itemId='+goodQuery['id']+'&pid='+pid+'&dx=1&src=tkm_tkmwz';
              goodInfo['target'] = target;
              num = parseInt(num);
              var tasks = [];
              for(var i = 0;i< num;i++){
                tasks.push(tao.createTbkl(title,target,pic));
              }
              var arrs = await Promise.all(tasks);
              res.send({status:'ok',result:arrs,good:goodInfo});
          }
        }
      }
      else
        res.status(400).send(not_auth);
    }else{
      res.status(400).send(not_auth);
    }
}

exports.getAllGatherData = async(req,res,next) => {

   var {start,end} = req.query;
   if(!start || !end) return res.status(400).send(not_full);
   let sess = req.cookies['sess'];
    if(sess){
      var none_tkls = [];
      var session_body  = await Session.findById(sess);
      if(session_body){
        var user = session_body.toJSON().user;
        if(user != '5a1e81f8c86fa7aa4b51b18b'){
            res.status(400).send(not_auth);
        }
        else{
          console.dir(start);
          console.dir(end);
          const condition = {'date': {'$gte': moment(start, 'YYYYMMDD').startOf('day').toDate(),'$lt': moment(end, 'YYYYMMDD').endOf('day').toDate()}};
          var list = await GatherData.aggregate([
              {
                $match:condition
              },
              {
                $group:{
                  _id: "$date",
                  times:{ $sum:"$times" },
                  dc_times:{ $sum:"$dc_times" }
                }
              }
            ]);
          list.map(x => { x._id = moment(x._id).format('YYYYMMDD'); x['date'] = moment(x._id).format('YYYY/MM/DD'); return x;})
          res.send({status:'ok',list:list})
        }
      }
      else
        res.status(400).send(not_auth);
    }else{
      res.status(400).send(not_auth);
    }
}

exports.admin2Tbkl = async(req,res,next) => {
    var { num = 10,logo,text,url} = req.body;
    if(!text || !url ) return res.status(400).send(not_full);
    var tasks = [];
    for(var i = 0;i< num;i++){
        tasks.push(tao.createnormalTbkl(text,url,logo));
    }
    var arrs = await Promise.all(tasks);
    res.send({status:'ok',result:arrs,good:{logo:logo,text:text,url:url}});
}



/*exports.getDetails = async (req,res,next) => {

    var {date,qd} = req.query;
    let now = moment().add(8,'hours').format('YYYYMMDD');
    if(!date || !qd || parseInt(now) - parseInt(date) < 0){
        res.status(400).send(not_right);
    }
    let sess = req.cookies['sess'];
    if(sess){
      var session_body  = await Session.findById(sess);
      if(session_body){
        var user = session_body.toJSON().user;
        if(user != '5a1e81f8c86fa7aa4b51b18b' && user != qd){
           res.status(400).send(not_auth);
        }
        else{

            var list = await Log.aggregate([
              {
                $match:{date:date}
              },
              {
                $group:{
                  _id: "$schedule",
                  sum:{ $sum:"$times" }
                }
              }
            ]);
            var tasks = [];
            list.forEach(item => {
              tasks.push(Schedule.findById(item._id).populate('qd','user').populate('links'));
            });
            var arrs = await Promise.all(tasks);
            var _arrs = [];
            var _list = [];
            var schedules = [];
            arrs.forEach( item => {
                if(item.qd && item.qd._id == qd){
                  schedules.push(item._id + '');
                  _arrs.push(item);
                }
            });
            list.forEach( item => {
              console.dir(schedules.indexOf(item._id+''))
                if(schedules.indexOf(item._id+'') >= 0) _list.push(item);
            });
            res.send({status:'ok',infos:_arrs,result:_list});
        }
      }
      else{
        res.status(400).send(not_login);
      }
    }else{
        res.status(400).send(not_login);
    }

}*/
var createTbkl = async (data) => {
    let {title,target,pic,qd} = data;
    return new Promise(async (r,d) => {
        try {
          let targetQuery = urlArgs(url.parse(target).query);
          var tbklInfo = null;
          console.dir(targetQuery);
          if(targetQuery['pid'])
             tbklInfo = await tao.createTbkl(title,target,pic);
          else
             tbklInfo = await tao.createnormalTbkl(title,target,pic);
          console.dir(tbklInfo);
          let model = tbklInfo.model;
          let _data = { info:model,schedule:data.schedule,link:data.link,creater:qd,status:'use' };
          tao.saveKouling(_data,function(e,result){
            if(e) d(e);
            else r(result);
          });
        }catch(e){
          d(e);
        }
    });
}

exports.createTbkl = createTbkl;