<?php
	/*
	 * 淘宝网采集商品--没有折扣
	 */

	 function combineURL($baseURL,$keysArr){
        $combined = $baseURL."&";
        $valueArr = array();

        foreach($keysArr as $key => $val){
            $valueArr[] = "$key=$val";
        }

        $keyStr = implode("&",$valueArr);
        $combined .= ($keyStr);

        return $combined;
    }

	switch($ts){

		//筛选
		case "":

			include template("admin/spider_tao");
			break;

		//搜索结果
		case  "search":

			$taobaoke_item_list = array();

			$map['keyword'] = _get('keyword', 'trim'); //关键词

				$p = _get('p', 'intval', 1);

				if (!$map['keyword']) {
					qiMsg("关键词必须要设置，多个请用空格分开！",'<a href="index.php?app=share&ac=admin&mg=spider">点击返回</a>');
				}else{
					$q = '&q='.urlencode($map['keyword']);
				}

				$map['start_price']                = _get('start_price', 'trim'); //价格下限
				$map['end_price']                  = _get('end_price', 'trim'); //价格上限
				$map['start_commissionRate']       = _get('start_commissionRate', 'trim'); //佣金比率下限
				$map['end_commissionRate']         = _get('end_commissionRate', 'trim'); //佣金比率上限
				$map['start_commissionNum']        = _get('start_commissionNum', 'intval'); //30天推广量下限
				$map['end_commissionNum']          = _get('end_commissionNum', 'intval'); //30天推广量上限
				$map['start_totalnum']             = _get('start_totalnum', 'intval'); //总销量下限
				$map['end_totalnum']               = _get('end_totalnum', 'intval'); //总销量上限
				$map['start_credit']               = _get('start_credit', 'intval'); //卖家信用下限
				$map['end_credit']                 = _get('end_credit', 'trim'); //卖家信用上限
				$map['user_type']                  = _get('user_type'); //天猫还是集市，还是所有
				$map['discountId']          	   = _get('discountId'); //打折类型
				$map['like_init']                  = _get('like_init', 'trim');
				$map['p']                  		   = '';

				if($map['start_price']>$map['end_price'] ){
					qiMsg("最低价格不能高于最高价格");
				}else{
					$q.='&filter=reserve_price%5B'.$map['start_price'].'%2C'.$map['end_price'].'%5D';
				}

				if($map['user_type'] == 1){
					$q.='&tab=mall&isprepay=1';
				}else{
					$q.='&tab=all&apassall=1';
				}
				$s=($p-1)*44;

				$url = combineURL('index.php?app=share&ac=admin&mg=spidertao&ts=search',$map);

				$url_taobao='http://s.taobao.com/search?'.$q.'&style=grid&fs=0&cps=yes&initiative_id=staobaoz_20140606&promote=0&s='.$s.'#J_relative';

				include_once '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_taobao)) {
					$content =  $snoopy->results;
			} else {
				echo "error fetching document: " . $snoopy->error . "\n";
				exit;
			}
			$content = mb_convert_encoding($content,"UTF-8","gbk");

			$pre = '/{"data":{"banner":(.*?)"status":"show"}/s';
		
			//正则匹配
			if(preg_match_all($pre, $content, $matchitem)) {

				$matchitem = json_decode($matchitem[0][0],true);
				$matchitem = $matchitem['data']['auctions'];

				foreach($matchitem as $value){
					$itemarray['title']=$value['raw_title'];
					$itemarray['pictUrl']=$value['pic_url'];
					$itemarray['auctionId']=$value['nid'];
					$itemarray['sellerId']=$value['user_id'];
					$itemarray['reservePrice']=$value['view_price'];
					$itemarray['likes']=rand(1,100);
					$itemarray['volume']=$value['view_sales'];
					$itemarray['nick']=$value['nick'];
					$itemarray['auctionUrl']=$value['detail_url'];
					$itemarray['shopUrl']=$value['shopLink'];
					$itemarray['zkPrice']=$value['view_price'];
					$itemarray['commentCount']=rand(1,999);
					$itemarray['coupon_start_time']=time();
					$results_arr['item_list'][]=$itemarray;
				}
//				for($i=0;$i<count($matchitem[0]);$i++){
//
//					$item=$matchitem[1][$i];
//					$titlebar = get_word($item,'<h3 class="summary">','<\/h3>');
//					$title = get_word($titlebar,'title="','"');//标题
//
//					$img = get_word($item,'<img data-ks-lazyload="','"');//图片
//					if(!$img){
//						$img = get_word($item,'<img data-ks-lazyload="_210x210.jpg','');
//					}
//
//					$auctionId = get_word($item,'data-item="','"');//商品id
//					$reservePrice = get_word($item,'<strong>','<\/strong>');//商品价格
//					$volume	= get_word($item,'<div class="col end dealing" >','<\/div>');//购买人数
//					$sellerId = get_word($item,'user_number_id=','"');//卖家ID
//
//					$nick = get_word($item,'data-nick="','"');//卖家昵称
//                    $nick = urldecode($nick);
//
//                    $auction = get_word($item,'<p class="pic-box">','<\/p>');
//                    $auctionUrl = get_word($auction,'<a href="','"');//商品地址
//
//                    $shop = get_word($item,'<div class="col seller','<\/div>');
//                    $shopUrl = get_word($shop,'href="','"');//卖家店铺地址
//
//					if(!$volume){$volume=0;}
//
//					$price = trim($price);
//					$itemarray['title']=$title;
//					$itemarray['pictUrl']=$img;
//					$itemarray['auctionId']=$auctionId;
//					$itemarray['sellerId']=$sellerId;
//					$itemarray['reservePrice']=$reservePrice;
//					$itemarray['likes']=rand(1,100);
//					$itemarray['volume']=$volume;
//					$itemarray['nick']=$nick;
//					$itemarray['auctionUrl']=$auctionUrl;
//					$itemarray['shopUrl']=$shopUrl;
//					$itemarray['zkPrice']=$reservePrice;
//					$itemarray['commentCount']=rand(1,999);
//					$itemarray['coupon_start_time']=time();
//					if($title && $img && $auctionId ){
//						$results_arr['item_list'][]=$itemarray;
//					}
//
//				}

			}else{
				qiMsg('采集结束！');
			}
				//分页
				//列表内容
				foreach($results_arr['item_list'] as $key=>$item){
					$id = $item['auctionId'];
					$taobaoke_item_list[$id] = $item;
				}
				$taobaoke_item_list && F('taobaoke_item_list', $taobaoke_item_list);
				$pageUrl = pagination(100, 1, $p, $url);

			include template("admin/search_tao");
   		 break;

		case  "publish":

        		//发布已选商品
				$url = _post('url');
				$ids = implode(',',_post('num_iid'));
			    $users  = $db->fetch_all_assoc("select userid,username FROM ".dbprefix."user_info");
				$userarray=array();
				foreach($users as $key=>$item){
					$userarray[]=$item;
				}
				include template("admin/publish_tao");


		break;

		case  "redirect":

			$url = _post('url')?urlencode(_post('url', 'trim')):urlencode(_get('url', 'trim'));
			$ids = _post('ids', 'trim')?_post('ids', 'trim'):_get('ids', 'trim');
			$catename = _post('catename', 'trim')?_post('catename', 'trim'):_get('catename', 'trim');
			$tag = _post('tag', 'trim')?_post('tag', 'trim'):_get('tag', 'trim');
			$i=_get('step', 'trim',0);

			$i=$i+1;
			$stop = false;//采集完毕
			$isExists=false;//商品存在
			$Cantresizeimage=false;//无法生成缩略图

			//从缓存中获取本页商品数据
			$ids_arr = explode(',', $ids);

			$taobaoke_item_list = F('taobaoke_item_list');
			$auid=$_REQUEST['auid'];

			$users  = $db->fetch_all_assoc("select userid FROM ".dbprefix."user");
			$users = arr2_arr1($users,'userid');
			if(!$auid){
			$users_key = array_rand($users);
			$adduid = $users[$users_key];
			}else{
			$adduid = $auid;
			}
			if ($ids_arr[$i-2]) {

				$result =$new['share']->publish_good($taobaoke_item_list[$ids_arr[$i-2]], $catename,$tag,$adduid);
				$result=='isExists' && $isExists = true;
				$result=='Cantresizeimage' && $Cantresizeimage = true;
			}

			if($i>=count($ids_arr)+1) $stop = true;

			include template("admin/redirect_tao");

		break;

	}