<?php

if ( !function_exists('substr_') ) {
// 安全utf-8字符串截断
function substr_($str, $len) {
    $mbchars = array();
    for( $i=0, $I=strlen($str), $L=0; $L<$len && $i<$I;) {
        $char = substr($str, $i, 1);
        switch ( true ) {
            default :
                $chars[] = substr($str, $i, 1); $L++; $i++; break;
            case ( ord($char) >= 252 ) :
                $chars[] = substr($str, $i, 6); $L++; $i += 6; break;
            case ( ord($char) >= 248 ) :
                $chars[] = substr($str, $i, 5); $L++; $i += 5; break;
            case ( ord($char) >= 240 ) :
                $chars[] = substr($str, $i, 4); $L++; $i += 4; break;
            case ( ord($char) >= 224 ) :
                $chars[] = substr($str, $i, 3); $L++; $i += 3; break;
            case ( ord($char) >= 192 ) :
                $chars[] = substr($str, $i, 2); $L++; $i += 2; break;
        }
    }
    return implode('', $chars);
}

}

class etao_mdl_feed extends shopObject{
    public function __construct(){
        parent::shopObject();

        if ( !$this->seller_id = $this->system->getConf('app.etao.uname') ) {
            //return trigger_error('没有配置etao账户',E_USER_ERROR);
            //return false;            
        }

        class_exists('pageFactory') || require 'pageFactory.php';
        $this->page = new pageFactory();
        $this->page->pagedata['seller_id'] = $this->seller_id;
    }

    public function feedgoods($goods_id){
        if ( !$goods_id = (int)$goods_id ) return;

        $goods = $this->db->selectrow('SELECT goods_id,bn,spec_desc,cat_id,name,price,intro,brand,big_pic FROM sdb_goods WHERE goods_id='.$goods_id);
        if (!$goods) return;
        
        $store = $this->db->selectrow('SELECT SUM(IFNULL(store,0)-IFNULL(freez,0)) as c FROM sdb_products WHERE goods_id='.$goods_id);
        
        $goods['store'] = +$store['c'] > 1 ? 1 : 0;
        $goods['price'] = number_format($goods['price'],2,'.','');
        
        $tags = $this->db->select('SELECT r.tag_id,t.tag_name FROM sdb_tag_rel as r ,sdb_tags as t WHERE t.tag_id=r.tag_id AND rel_id='.$goods_id);
        $count = (count($tags)-1)<5 ? count($tags)-1 : 5;
        for($I=$count;$I>0;$tags_n[]=$tags[$I]['tag_name'],$I--);
        $goods['tags'] = implode('\\',$tags_n);
        
        $sku = unserialize($goods['spec_desc']);
        $specs_ = $specs = array();
        $products = $this->db->select('SELECT product_id,props FROM sdb_products WHERE goods_id='.$goods_id);
        foreach( $products as $k=>$v ){
            $props = unserialize($v['props']);
            foreach( $props['spec_private_value_id'] as $spec_id=>$p_spec_vid) {
                if ( !$specs[$spec_id] ) {
                    $specs[$spec_id] = $this->db->selectrow('SELECT * FROM sdb_specification WHERE spec_id='.intval($spec_id));
                }
                
                $spec_ = $sku[$spec_id][$p_spec_vid];
                $specs_[$spec_id][$p_spec_vid] = $spec_['spec_value'];
            }
        }
        foreach($specs_ as $spec_id=>$spec_v){
            $goods['specs_'][] = $specs[$spec_id]['spec_name'].':'.implode(',', $spec_v);
        }
        $goods['specs_'] = implode(';', $goods['specs_']);
        
        $goods['images'] = $this->db->select('SELECT small,big FROM sdb_gimages WHERE goods_id='.intval($goods_id));
       
        $storageMdl = $this->system->loadModel('system/storager');
        $goods['images_default'] = $storageMdl->getUrl($goods['big_pic']);
        $goods['goods_url'] = $this->system->realUrl('product','index',array($goods_id));
        
        $cate = &$this->db->selectrow('SELECT cat_path,cat_name FROM sdb_goods_cat WHERE cat_id='.$goods['cat_id']);
        if ( $cate ){
            $cates_ = array();
            foreach (explode(',', $cate['cat_path']) as $cat_id) {
                if ( !$cat_id = (int)$cat_id ) continue;
                $cate_ = &$this->db->selectrow('SELECT cat_name FROM sdb_goods_cat WHERE cat_id='.$cat_id);
                if ( !$cate_ || !$cate_['cat_name'] ) break;
                $cates_[] = $cate_['cat_name'];
            }
            $cates_[] = $cate['cat_name'];
            $goods['catpath'] = implode('/', $cates_);
        }

        $this->page->pagedata['goods'] = $goods;
        
        $tmpl = 'file:'.dirname(__FILE__).'/view/feed-tmpl/goods.html';
        return $this->page->fetch($tmpl);
    }
    
    public function feedcate(){
        $cats = $this->db->select("SELECT cat_id,parent_id,cat_name,cat_path FROM sdb_goods_cat WHERE disabled='false'");
        
        $parent = $parent_ = array();
        foreach($cats as $k=>$v){
            if('0' == $v['parent_id']){
                $parent[] = $v;
            }
        }
        foreach($parent as $k=>$v){
            foreach($cats as $k1=>$v1){
                if($v['cat_id'] == $v1['parent_id']){
                    $parent_[$v['cat_id']]['cat_id'] = $v['cat_id'];
                    $parent_[$v['cat_id']]['cat_name'] = $v['cat_name'];
                    $parent_[$v['cat_id']]['c'][] = $v1;
                }
            }
        }
        
        $this->page->pagedata['date'] = date('Y-m-d H:i:s',NOW);        
        $this->page->pagedata['cats'] = $parent_;
        $tmpl = 'file:'.dirname(__FILE__).'/view/feed-tmpl/SellerCats.html';
        $file = HOME_DIR."/tmp/etao/SellerCats.xml";
        file_put_contents($file,$this->page->fetch($tmpl));
    }
    
    // etao定时任务
    public function genfeedfull() {
        //if ( NOW-23*3600 < $this->system->loadModel('system/status')->get('ETAO_INDEX_FLM') ) return;

        $this->page->pagedata['last_m_t'] = date('Y-m-d H:i:s',NOW);
        $this->page->pagedata['item_url'] = $this->system->base_url().'?action_etao-goods.html?feed=';
        $this->page->pagedata['cate_url'] = $this->system->base_url().'home/tmp/etao/SellerCats.xml';

        $tmpl = 'file:'.dirname(__FILE__).'/view/feed-tmpl/index.html';
        file_put_contents(HOME_DIR.'/tmp/etao/FullIndex.xml', $this->page->fetch($tmpl));        
        for ($i=0; $i < 1000; $i++) {
            $offset = $i*300;

            $gs = $this->db->select("SELECT goods_id,disabled,marketable FROM sdb_goods WHERE disabled='false' LIMIT $offset,300");
            if ( !$gs ) break;

            foreach ($gs as $k=>$v) {
                $gs[$k]['_act'] = 'upload';
            }

            $tmpl = 'file:'.dirname(__FILE__).'/view/feed-tmpl/index-item.html';

            $this->page->pagedata['goods'] = $gs;
            file_put_contents(HOME_DIR.'/tmp/etao/FullIndex.xml', $this->page->fetch($tmpl),FILE_APPEND);
        }
        
        file_put_contents(HOME_DIR.'/tmp/etao/FullIndex.xml','</item_ids></root>',FILE_APPEND);

        // 生成category文件
        $this->feedcate();
        $this->system->loadModel('system/status')->set('ETAO_INDEX_FLM',NOW);
    }
    
    public function genfeedinc(){
        if ( NOW-1700 < $this->system->loadModel('system/status')->get('ETAO_INDEX_INCLM') ) return;

        $this->page->pagedata['seller_id'] = $this->seller_id;
        $this->page->pagedata['last_m_t'] = date('Y-m-d H:i:s',NOW);
        $this->page->pagedata['item_url'] = $this->system->base_url().'?action_etao-goods.html?feed=';
        $this->page->pagedata['cate_url'] = $this->system->base_url().'home/tmp/etao/SellerCats.xml';

        $tmpl = 'file:'.dirname(__FILE__).'/view/feed-tmpl/index.html';
        file_put_contents(HOME_DIR.'/tmp/etao/IncrementIndex.xml', $this->page->fetch($tmpl));

        $hour2 = NOW - 1800;
        $where = "WHERE last_modify>=$hour2";
        for ($i=0; $i < 100; $i++) {
            $offset = $i*300;

            $gs = $this->db->select("SELECT goods_id,disabled,marketable FROM sdb_goods {$where} LIMIT $offset,300");
            if ( !$gs ) break;

            foreach ($gs as $k=>$v) {
                $gs[$k]['_act'] = 'upload';
            }

            $tmpl = 'file:'.dirname(__FILE__).'/view/feed-tmpl/index-item.html';
            $this->page->pagedata['goods'] = $gs;
            file_put_contents(HOME_DIR.'/tmp/etao/IncrementIndex.xml', $this->page->fetch($tmpl),FILE_APPEND);
        }
        
        file_put_contents(HOME_DIR.'/tmp/etao/IncrementIndex.xml','</item_ids></root>',FILE_APPEND);

        $this->system->loadModel('system/status')->set('ETAO_INDEX_INCLM',NOW);
    }
}
