var config = require('../config/index');
var Agent = require('../db/mongo/tao-agent');
var Kouling = require('../db/mongo/tao-kouling');
var Link = require('../db/mongo/tao-link');
var log = require('../db/mongo/tao-log');
var Schedule = require('../db/mongo/tao-schedule');
var mongoose = require('mongoose');
const TopClient = require('./topClient')['TopClient'];


var client = new TopClient({
      'appkey': config.taobao.appKey,
      'appsecret': config.taobao.appSecret,
      'REST_URL': 'http://gw.api.taobao.com/router/rest'
});
exports.saveKouling = async (data,cb)  => {
	try {
		var kouling = new Kouling(data);
		cb(null,await kouling.save());
	} catch(e){
		cb(e);
	}
}

exports.saveLink = async (data,cb)  => {
	try {
		var link = new Link(data);
		cb(null,await link.save());
	} catch(e){
		cb(e);
	}
}


exports.saveSchedule = async (data,cb)  => {
	try {
		var schedule = new Schedule(data);
		cb(null,await schedule.save());
	} catch(e){
		cb(e);
	}
}

exports.saveAgent = async (data,cb)  => {
	console.dir(data);
	try {
		var agent = new Agent(data);
		cb(null,await agent.save())
	} catch(e){
		cb(e);
	}
}


exports.findAgent = async (qs,cb) =>  {
	try {
		cb(null,await Agent.find(qs))
	} catch(e){
		cb(e);
	}
}

exports.findKouling = async (qs,cb) => {
	try {
		cb(null,await Kouling.find(qs))
	} catch(e){
		cb(e);
	}
}

exports.getGood = (id) => {
	return new Promise((r,d) => {
		client.execute('taobao.tbk.item.info.get',
	    {
	      'fields':'num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url',
	      'platform':'1',
	      'num_iids':id
	    },function(error, response) {
	    	console.dir(error);
	    	console.dir(response);
	      if(response.results && response.results.n_tbk_item && response.results.n_tbk_item[0] && !error) r(response.results.n_tbk_item[0]);
	      else d(error || 'unknown error');
	    });	
	});
}

exports.createTbkl = (title,url,pic) => {
	return new Promise((r,d) => {
		client.execute('taobao.tbk.tpwd.create', {
	    'text':title,
	    'url':url,
	    'logo':pic
		}, function(error, response) {
			console.dir(error);
			console.dir(response);
	   	 	if (response && response.data && !error) r(response.data);
	    	else d(error);
		})
	});
}


exports.createnormalTbkl = (title,url,pic) => {
	return new Promise((r,d) => {
	var data = { 
		'text':title,
	    'url':url
	};
	if(pic)
		data['logo'] = pic;
	client.execute('taobao.wireless.share.tpwd.create', {tpwd_param:data}, function(error, response) {
		console.dir(error);
		console.dir(response);
	  if (response && !error) r(response);
	   else d(error);
	})
	});
}