<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 15/11/3
 * Time: 下午7:51
 */
class tmrequest
{
    private $appkey;
    private $secretKey;
    private $sessionKey;
    private $tm_shop;
    private $tm_goods;


    public function __construct()
    {
        $this->tm_shop = Model('tm_shop');
        $this->tm_goods = Model('tm_goods');
    }
    public function proc_one($shopid)
    {
        $items = $this->tm_shop->where(array('shop_id' => $shopid))->field('shop_id,shop_name,appKey,sercetCode,sessionKey')->limit(false)->select();
        $this->request($items);

    }

    public function proc()
    {
        $items = $this->tm_shop->field('shop_id,shop_name,appKey,sercetCode,sessionKey')->limit(false)->select();
        $this->request($items);
    }

    //添加基础数据。
    private function store_data($body,$desc,$shop_id)
    {
        $response = json_decode($body, true);
        $item = &$response['item_seller_get_response']['item'];
        if($item['approve_status'] != 'onsale') {
            return;
        }

        $cid = $item['cid'];
        $num_iid = $item['num_iid'];
        $title = $item['title'];


        //把数据添加到商品临时表里面
        $iid = $this->tm_goods->insert(array("num_iid" => $num_iid,'shop_id' => $shop_id,'body' => $body,'cid' => $cid,'product_id' =>$item['product_id'],'title' => $title, 'description' => $desc));
        if(!$iid) {
            Log::record("Can not insert num_iid=$num_iid into tm_goods table.");
        }
    }

    private function get_body($num_iid)
    {
        $fields = 'cid,seller_cids,props,input_pids,input_str,pic_url,num,list_time,delist_time,stuff_status,location,
has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,auto_repost,approve_status,postage_id,product_id,
item_img, is_virtual,is_taobao,is_ex,is_timing,
is_3D,score,one_station,second_kill,violation,is_prepay,ww_status,wap_detail_url,cod_postage_id,sell_promise,period_sold_quantity,detail_url,
num_iid,title,nick,type,sku,
props_name,created,promoted_service,is_lightning_consignment,is_fenxiao,auction_point,property_alias,volume,
sell_point,valid_thru,outer_id,
barcode,sold_quantity,price,post_fee,express_fee,ems_fee,global_stock_type,global_stock_country,prop_img';

        //desc wireless_desc wap_desc
        $c = new TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secretKey;

        $req = new ItemSellerGetRequest;
        $req->setFields($fields);
        $req->setNumIid($num_iid);
        $resp = $c->execute($req,$body,$this->sessionKey);

        if(!empty($resp)) {
            $item = &$resp->item;
            if(!empty($item)) {
                return $body;
            }
        }
        return false;
    }

    private function get_desc($num_iid)
    {
        $c = new TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secretKey;

        $req = new ItemSellerGetRequest;
        $req->setFields("desc");
        $req->setNumIid($num_iid);
        $resp = $c->execute($req,$body,$this->sessionKey);

        if(!empty($resp))
        {
            $item = &$resp->item;
            if(!empty($item)) {
                return $item->desc;
            }
        }

        return false;
    }

    private function get_onsale()
    {
        $req = new tm_pagereq($this->appkey,$this->secretKey,$this->sessionKey);
        return $req->proc();
    }

    /**
     * @param $items
     */
    private function request($items)
    {
        foreach ($items as $item)
        {
            Log::record("Inof: shop id =" . $item["shop_id"] . " name=" . $item["shop_name"] . " appKey=" . $item['appKey'] . " sercetCode=" . $item['sercetCode'] . " sessionKey=" . $item['sessionKey'],Log::DEBUG);

            $this->appkey = $item['appKey'];
            $this->secretKey = $item['sercetCode'];
            $this->sessionKey = $item['sessionKey'];

            $shop_id = $item["shop_id"];

            $sale_items = $this->get_onsale();
            if (empty($sale_items)) {
                Log::record("get product info from taobao err where " . "shop id =" . $item["shop_id"] . " name=" . $item["shop_name"],Log::ERR);
            }
            else
            {
                foreach ($sale_items as $sale_item)
                {
                    $num_iid = $sale_item->num_iid;
                    $issale = $sale_item->approve_status == "onsale" ? true : false;
                    if ($issale) {
                        $body = $this->get_body($num_iid);
                        $desc = $this->get_desc($num_iid);
                        if (!empty($body)) {
                            $this->store_data($body, $desc, $shop_id);
                        }
                    }
                }
            }
        }
    }
}