<?php 

	defined('IN_TS') or die('Access Denied.');

	include_once 'sharegoods.php';
	class taobao_sharegoods implements interface_sharegoods
{
	public function fetch($url)
	{
		global $db;
		
		$id = $this->getID($url);
		
		if($id == 0)
		return false;
		$taobao_url  = "http://item.taobao.com/item.htm?id=".$id;
		$tmall_url  = "http://detail.tmall.com/item.htm?id=".$id;
		
		
		$key = 'taobao_'.$id;
		$share_goods = 0;
		$share_goods = $db->once_fetch_assoc("select * from ".dbprefix."share_goods where url = '$taobao_url'");
		
		if($share_goods)
		{
			$result['status'] = -1;
			$result['goods_id'] = $share_goods['goods_id'];
			return $result;
		}

		$content  =  $this->gethtml($taobao_url);
		if(!$content) $content  =  $this->gethtml($tmall_url);

		$content = mb_convert_encoding($content,"UTF-8","gbk");



		//获取价格
		
        preg_match('/price:(.*),/', $content, $price);
		
		if(!$price[1]){
			 preg_match('/\"reservePrice\":\"(.*)\",\"sellerNickName\"/', $content, $price);
		}
		
		
		//获取标题
		preg_match('/<h3 class=\"tb-item-title\">(.*)<\/h3>/', $content, $name);
		
		if(!$name[1]){
			 preg_match('/<title>(.*)<\/title>/',$content,$name);
			$name[1] =  str_replace("-tmall.com天猫","",$name[1]);
			$name[1] =  str_replace("-淘宝网","",$name[1]);
		}
		
		//获取商品图片
		$pic_url = $this->GetMorepic($content);
		$result['item']['key'] = $key;
		$result['item']['nick'] = $goods['nick'];
		$result['item']['name'] =$name[1];
		$result['item']['price'] = $price[1];
		$result['item']['coupon_price'] = '0.00';
		$result['item']['img'] = $goods['item_imgs'];
		$result['item']['server_code'] = $image['server_code'];
		$result['item']['pic_url'] =$pic_url;
		$result['item']['url'] = $taobao_url;

		return $result;
	}
	
	
	public function getID($url)
	{
		$id = 0;
		$parse = parse_url($url);
		if(isset($parse['query']))
		{
		parse_str($parse['query'],$params);
		if(isset($params['id']))
		$id = $params['id'];
		elseif(isset($params['item_id']))
		$id = $params['item_id'];
		elseif(isset($params['default_item_id']))
		$id = $params['default_item_id'];
		}
		return $id;
	}
	
	public function getKey($url)
	{
		$id = $this->getID($url);
		return 'taobao_'.$id;
	}

	 /**
     * 获取商品列表
     * 返回商品列表和总数
     */
    public function _get_list($map, $p) {
		
        $client = $this->_get_client();
		$req = new TaobaokeItemsGetRequest;
        $req->setFields('num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume');
		
		$strOption = fileRead('options.php','data','system');
		$tao_ke_pid = $strOption['PID'];
		if(!empty($tao_ke_pid)) $req->setPid($tao_ke_pid);
        $req->setPageNo($p);
        $req->setPageSize(20);
        $map['keyword'] && $req->setKeyword($map['keyword']); //关键词
        $map['cid'] && $req->setCid($map['cid']); //分类
        $map['start_price'] && $req->setStartPrice($map['start_price']); //价格下限
        $map['end_price'] && $req->setEndPrice($map['end_price']); //价格上限
        $map['start_commissionRate'] && $req->setStartCommissionRate($map['start_commissionRate'] * 100); //佣金比率下限
        $map['end_commissionRate'] && $req->setEndCommissionRate($map['end_commissionRate'] * 100); //佣金比率上限
        $map['start_commissionNum'] && $req->setStartCommissionNum($map['start_commissionNum']); //30天推广量下限
        $map['end_commissionNum'] && $req->setEndCommissionNum($map['end_commissionNum']); //30天推广量上限
        $map['start_totalnum'] && $req->setStartTotalnum($map['start_totalnum']); //总销量下限
        $map['end_totalnum'] && $req->setEndTotalnum($map['end_totalnum']); //总销量上限
        $map['start_credit'] && $req->setStartCredit($map['start_credit']); //卖家信用下限
        $map['end_credit'] && $req->setEndCredit($map['end_credit']); //卖家信用上限
        $map['mall_item'] && $req->setMallItem('true'); //是否天猫商品
        $map['guarantee'] && $req->setGuarantee('true'); //是否消保卖家
        $map['sevendays_return'] && $req->setSevendaysReturn('true'); //是否支持7天退换
        $map['real_describe'] && $req->setRealDescribe('true'); //是否先行赔付
        $map['cash_coupon'] && $req->setCashCoupon('true'); //是否支持抵价券
        $map['sort'] && $req->setSort($map['sort']);
        $req->setStartCommissionRate(1000);
        $req->setEndCommissionRate(2000);
        
        $resp = $client->execute($req);
        $count = $resp->total_results;
        //列表内容
        $iids = array();
        $resp_items = (array) $resp->taobaoke_items;
        $taobaoke_item_list = array();
		
		
        foreach ($resp_items['taobaoke_item'] as $val) {
            $val = (array) $val;
            //喜欢数
            switch ($map['like_init']) {
                case 'volume':
                    $val['likes'] = $val['volume'];
                    break;
                default:
                    $val['likes'] = 0;
                    break;
            }
            $taobaoke_item_list[$val['num_iid']] = $val;
        }
	
        //$taobaoke_item_list[$val['num_iid']]['imgs'] = $this->_Get_Item_Img($taobaoke_item_list);

        //返回
        return array(
            'count' => intval($count),
            'item_list' => $taobaoke_item_list,
        );
    }
	
	
	
	//获取商品相册信息
	public function _Get_Item_Img($taobaoke_item_list) {
		
		$client = $this->_get_client();
        $iids = array_keys($taobaoke_item_list);
       	$req = new ItemsListGetRequest;
        $req->setFields('num_iid,item_img');
        $req->setNumIids(implode(',', $iids));
        $resp = $client->execute($req);
        $resp_items = (array) $resp->items;
        $resp_item_list = $resp_items['item'];
        foreach ($resp_item_list as $val) {
            $imgs = array();
            $val = (array) $val;
            $item_imgs = (array) $val['item_imgs'];
            $item_imgs = (array) $item_imgs['item_img'];
            foreach ($item_imgs as $_img) {
                $_img = (array) $_img;
                if ($_img['url']) {
                    $imgs[] = array(
                        'url' => $_img['url'],
                        'surl' => $_img['url'] . '_100x100.jpg',
                        'ordid' => $_img['position']
                    );
                }
            }
            return $imgs;
        }
	}
	
	
	public function GetMorepic($content){
			
		preg_match_all('/<img src=\"(.*?)_60x60q90.jpg\" /', $content, $arrpic);
		if(!$arrpic[1]){
			
				preg_match_all('/<img data-src=\"(.*?)_60x60.jpg\" /', $content, $arrpic);
		}
		
		if(!$arrpic[1]){
			
				preg_match_all('/<img data-src=\"(.*?)_50x50.jpg\" /', $content, $arrpic);
		}
		
		if(!$arrpic[1]){
			
				preg_match_all('/<img src=\"(.*?)_60x60.jpg\" /', $content, $arrpic);
		}
		
		if(!$arrpic[1]){
			
				preg_match_all('/<img src=\"(.*?)_50x50.jpg\" /', $content, $arrpic);
		}

		foreach($arrpic[1] as $key=>$item){
			$pic[] = $item.'_100x100.jpg';
		}
		
		
		return $pic;

		}
		
	
	
	
	
	
	//获取淘宝分类
	public function _GetTaobaocats($cid = 0) {
        $client = $this->_get_client();
		$req = new ItemcatsGetRequest;
		$req->setFields("cid,parent_cid,name,is_parent");
		$req->setParentCid($cid);
		$resp = $client->execute($req);
		if(!isset($resp))
		return false;
        $res_cats = (array) $resp->item_cats;
        $item_cate = array();
		
        foreach ($res_cats['item_cat'] as $val) {
            $val = (array) $val;
            $item_cate[] = $val;
        }
        return $item_cate;
    }
	
	 public function _get_client() {
		include_once 'fun.base.php';
		$strOption = fileRead('options.php','data','system');
        $client = new TopClient;
		$client->appkey = $strOption['AppKey'];
		$client->secretKey = $strOption['AppSecret'];
        return $client;
    }
	
	
	public function gethtml($url)
	{
		$is_HK = 0;
		$urlid= $this->getID($url);
		$taobao_url  = "http://item.taobao.com/item.htm?id=".$urlid;
		$tmall_url  = "http://detail.tmall.com/item.htm?id=".$urlid;
		
		$url = $is_HK?"http://www.letushuo.com/index.php?app=share&ac=ajax&taobaourl=".$taobao_url:$taobao_url;
		$content      =  file_get_contents($url);
		if(strlen($content)<300){
			$content = $this ->snoopy($url);
		}
		if(strlen($content)<300){
			
			$url = $is_HK?"http://www.letushuo.com/index.php?app=share&ac=ajax&taobaourl=".$tmall_url:$tmall_url;
			
			$content      =  file_get_contents($url);
			if(strlen($content)<300){
				
				$content = $this ->snoopy($url);
			}
			
		}
	
	
			return $content;
	}
	
	public function snoopy($url)
	{
		
			include_once THINKROOT.'/letutao/Snoopy.class.php';
					
				$snoopy = new Snoopy();  
				  
				$snoopy->agent = "(compatible; MSIE 8.01; MSN 2.5; AOL 4.0; Windows xp)";  
				$snoopy->referer = "http://www.tuntron.com";  
				   
				$snoopy->cookies["SessionID"] = '238472834723489';  
				$snoopy->cookies["favoriteColor"] = "RED";  
				  
				$snoopy->rawheaders["Pragma"] = "no-cache";  
				  
				$snoopy->maxredirs = 2;  
				$snoopy->offsiteok = false;  
				$snoopy->expandlinks = false;  
				  
				$snoopy->user = "joe";
				$snoopy->pass = "bloe";  
						
				if($snoopy->fetch($url)) {  
					$content = $snoopy->results;  
			} else {  
				$content = "error fetching document: " . $snoopy->error . "\n";  
			}  
			
			return $content;
		
		}
	
	

}

?>