<?php
class taskAction extends FirstendAction{
private $accessKey = '';
public function _initialize()
{
        parent::_initialize();
        $this->accessKey = trim(C('yh_gongju'));

}
public function run(){
set_time_limit(30);
 $this->check_key();
$now = NOW_TIME;
$domain = trim(C('yh_site_url'));
$task = array(
array('value'=>'Tbcollect','query'=>'/index.php?m=task&a=Tbcollect&key='.$this->accessKey,'interval'=>200,'status'=>1),
array('value'=>'DelFailure','query'=>'/index.php?m=task&a=DelFailure&key='.$this->accessKey,'interval'=>1200,'status'=>1),
array('value'=>'Cleartbitems','query'=>'/index.php?m=task&a=Cleartbitems&key='.$this->accessKey,'interval'=>3600,'status'=>1),
);

$data = [];
$t = 0;
	foreach($task as $v=>$k){
	
	if(function_exists('opcache_invalidate')){
	$basedir = $_SERVER['DOCUMENT_ROOT']; 
	$dir=$basedir.'/data/Runtime/Data/task/'.$k['value'].'.php';
	$ret=opcache_invalidate($dir,TRUE);
	}
	$runtime = F($k['value']);
	if(($now - $runtime) > $k['interval'] && $k['status'] == 1){
	$url = $domain.$k['query'].'&t='.$t;
	 $data[]['url'] = $url;
	F($k['value'],$now);
	echo "success:".$k['value'].'<br/>';	
	}
	$t++;
	}
	
	$res = $this->getMultiCurlResult($data);
	
}



public function Cleartbitems(){
$this->timeout();
$this->check_key();
$mod = M('items');
$NowTime = NOW_TIME;
$where = 'coupon_end_time <'.$NowTime;
$res = $mod->where($where)->delete();
$this->Log('Cleartbitems',$res);
 exit();		
	
}


public function DelFailure(){
$this->timeout();
$this->check_key();
$t = I('t');
$map=array(
        'time'=>NOW_TIME.$t,
		'tqk_uid'=>$this->tqkuid
		);
	    $token=$this->create_token(trim(C('yh_gongju')),$map);
        $map['token']=$token;
        $url = $this->tqkapi.'/disabled';
        $content = $this->_curl($url,$map);
        $itemId = json_decode($content, true);
        $this->Log('DelFailure',$content);
		$itemId = $itemId['data'];
        if(!$itemId){
            $json = array(
                'data'=>array(),
                'result'=>array(),
                'state'=>'no',
                'msg'=>'商品ID不能为空'
            );
            
            exit(json_encode($json,JSON_UNESCAPED_UNICODE));
        }
        
       $model = M('items');
       $itemId =  implode(",", $itemId);
        $where = array(
            'num_iid'=>array('in', $itemId)
        );
        $model->where($where)->delete();
        $json = array(
            'data'=>array(),
            'result'=>'ok',
            'state'=>'yes',
            'msg'=>'清理成功'
        );
        
        exit(json_encode($json,JSON_UNESCAPED_UNICODE));
}


protected function getMultiCurlResult($data = [], $timeout = 30)
{
    $request = [];
    $requestResource = curl_multi_init();
    foreach ($data as $k => $v) {
        $option = [
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090730 Firefox/3.5.2 GTB5',
        ];
        if(!isset($v['url']) || !$v['url']) return null;
        $option[CURLOPT_URL] = trim($v['url']);
        if (stripos($v['url'], 'https') === 0) $option[CURLOPT_SSL_VERIFYPEER] = false;
        if (isset($v['data'])) {
            $option[CURLOPT_POST] = true;
            $option[CURLOPT_POSTFIELDS] = http_build_query($v['data']);
        }
        $request[$k] = curl_init();
        curl_setopt_array($request[$k], $option);
        curl_multi_add_handle($requestResource, $request[$k]);
    }
    $running = null;
    $result = [];
    do {
        curl_multi_exec($requestResource, $running);
        curl_multi_select($requestResource);
    } while ($running > 0);
    foreach ($request as $k => $v) {
        $result[$k] = curl_multi_getcontent($v);
        curl_multi_remove_handle($requestResource, $v);
    }
    curl_multi_close($requestResource);
    return $result;
}

protected function asycurl($url) {
	  //  $time = time();
        $ch = curl_init();
        $headers = array("Content-type: application/json;charset='utf-8'",
            "Accept: application/json",
            "Cache-Control: no-cache","Pragma: no-cache");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"GET");
       // curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //
		curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //
        curl_setopt($ch, CURLOPT_URL, $url); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1 );  
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
      //  curl_setopt($ch, CURLOPT_TIMEOUT, 1); 
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1); 
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090730 Firefox/3.5.2 GTB5' );  
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);    
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100); 
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0); 
        $result = curl_exec($ch);
        curl_close($ch);
            return $result;
    }



protected function timeout(){
set_time_limit(30);
ignore_user_abort(true);
if (!function_exists("fastcgi_finish_request")) { 
function fastcgi_finish_request() { } 
}else{
	fastcgi_finish_request();
}

}


public function  Tbcollect(){
 $this->timeout();
 $this->check_key();
 $file = TQK_DATA_PATH.'start.txt';
        if(!file_exists($file)){
            return false;
     }
   $startId = file_get_contents($file);
        if(!$startId){
            $startId = 0;
        }
        $t = I('t');
		$map=array(
		'start'=>$startId,
		'pagesize'=>20,
		'time'=> NOW_TIME.$t,
		'tqk_uid'=>$this->tqkuid
		);
	   $token=$this->create_token(trim(C('yh_gongju')),$map);
       $map['token']=$token;
        $url = $this->tqkapi.'/getitems';
        $content = $this->_curl($url,$map);
        $json = json_decode($content, true);
        $this->Log('Tbcollect',$content);
		$PID= trim(C('yh_taobao_pid'));
		 $json = $json['result'];
		 $count=count($json);
        if($count>0){
         foreach ($json as $key => $val){
        if(C('yh_site_secret')==1 && false === strpos($attach, 'https://')){
		$pic_url=str_replace("http://","https://",$val['pic_url']);
		}else{
		$pic_url=$val['pic_url'];
		}
              $link = 'https://item.taobao.com/item.htm?id=' . $val['num_iid'];
                $raw[]=array(
                'link'=>$link,
		        'click_url'=>'',
		        'pic_url'=>$pic_url,
		        'title'=>$val['title'],
		        'tags'=>$val['tags'],
		        'coupon_start_time'=>$val['coupon_start_time'],
		        'add_time'=>strtotime(date('Y-m-d H:i:s')),
		        'coupon_end_time'=>$val['coupon_end_time'],
		        'ali_id'=>$val['ali_id'],
		        'cate_id'=>$val['cate_id'],
		        'shop_name'=>$val['shop_name'],
		        'shop_type'=>$val['shop_type'],
		        'ems'=>1,
		        'num_iid'=>$val['num_iid'],
	           // 'sellerId'=>$tbdetail['sellerid'],
	             //'volume'=>$tbdetail['volume'],
		        'volume'=>$val['volume'],
		        'commission'=>$val['commission'],
		        'tuisong'=>0,
		        'area'=>0,
		        'pass'=>1,
		        'status'=>'underway',
		        'isshow'=>1,
		       // 'commission_rate'=>'',
                'commission_rate' =>$val['tk_commission_rate'], //佣金比例
		        'tk_commission_rate'=>$val['tk_commission_rate'],
		        'sellerId'=>$val['sellerId'],
		        'nick'=>$val['nick'],
		        'mobilezk'=>0,
		        'hits'=>0,
		        'price'=>$val['price'],
		        'coupon_price'=>$val['coupon_price'],
		        'coupon_rate'=>$val['coupon_rate']?$val['coupon_rate']:0,
		        'intro'=>$val['intro'],
		        'up_time'=>$val['up_time'],
		        'desc'=>'',
		        'isq'=>'1',
		        'quanurl'=>'https://uland.taobao.com/coupon/edetail?e=&activityId='.$val['Quan_id'].'&itemId='.$val['num_iid'].'&pid='. $PID .'',
		        'quan'=>$val['quan'],
		        'Quan_id'=>$val['Quan_id'],
		        'Quan_condition'=>0,
		        'Quan_surplus'=>$val['Quan_surplus']?$val['Quan_surplus']:0,
                'Quan_receive'=>$val['Quan_receive']?$val['Quan_receive']:0,
                'is_commend'=>$val['is_commend']?$val['is_commend']:0
                );
                
               $startId = $val['id'];
            }
          $ret = M('items')->addAll($raw,array(),true);
          file_put_contents($file, $startId);
			$json = array(
                'data'=>array(),
                'total'=>$count,
                'result'=>array(),
                'state'=>'yes',
                'msg'=>'正常'
            );
			
        }else{
        	
        	$json = array(
                'data'=>array(),
                'total'=>0,
                'result'=>array(),
                'state'=>'yes',
                'msg'=>'商品采集完啦！'
            );
		
        }
 exit(json_encode($json,JSON_UNESCAPED_UNICODE));
}

protected  function check_key(){
 $json = array(
         'state'=>'no',
          'msg'=>'通行密钥不正确'
         );
$key = I('key');
if(!$key || $key!=$this->accessKey){
exit(json_encode($json,JSON_UNESCAPED_UNICODE));
}	
 }





protected function Log($name,$data){
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/task/'.$name.'.php';
$ret=opcache_invalidate($dir,TRUE);
}
F('task/'.$name,$data);
}


}