<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 15/12/4
 * Time: 上午11:07
 */
class tm_pagereq
{
    private $appkey;
    private $secretKey;
    private $sessionKey;

    private $total_items;
    private $num_iids;
    private $leftcount;

    public function __construct($appKey,$sercetCode,$sessionKey)
    {
        $this->appkey = $appKey;
        $this->secretKey = $sercetCode;
        $this->sessionKey = $sessionKey;

        $this->total_items = 0;
        $this->leftcount = -1;
        $this->num_iids = array();
    }

    public function proc()
    {
        $page_no = 1;
        do
        {
            if($this->get_onsale($page_no) == false) {
                Log::record("error request.",Log::ERR);
                return NULL;
            }
            $page_no++;
        } while($this->leftcount > 0);

        return $this->num_iids;
    }

    public function get_onsale($page_no)
    {
        $page_size = 200;

        $c = new TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secretKey;
        $req = new ItemsOnsaleGetRequest;

        $req->setFields('approve_status,num_iid');
        $req->setPageSize($page_size);
        $req->setPageNo($page_no);

        $resp = $c->execute($req,$body,$this->sessionKey);

        if(!empty($resp))
        {
            $this->total_items = $resp->total_results;
            Log::record("total={$this->total_items}\r\n",Log::DEBUG);
            $items = $resp->items->item;
            if($items == NULL) {
                Log::record("total={$this->total_items}\r\n",Log::DEBUG);
                echo "total={$this->total_items}\r\n";
                flush();
                return NULL;
            }

            if($this->leftcount < 0) {
                $this->leftcount = $this->total_items;
            }
            $this->leftcount -= count($items);

            foreach($items as $item) {
                array_push($this->num_iids,$item);
            }
            return true;
        } else {
            return NULL;
        }
    }
}