<?php

define('IN_ASC', true);



require(dirname(__FILE__) . '/includes/init.php');
require(ROOT_PATH.'quick_buy_init.php');

if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}

$affiliate = json_decode($GLOBALS['_CFG']['affiliate'],true);
$smarty->assign('affiliate', $affiliate);

/*------------------------------------------------------ */
//-- INPUT
/*------------------------------------------------------ */

$goods_id = isset($_REQUEST['id'])  ? intval($_REQUEST['id']) : 0;

/*------------------------------------------------------ */
//-- 改變屬性、數量時重新計算商品價格
/*------------------------------------------------------ */

if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'price')
{
    include('includes/cls_json.php');

    $json   = new JSON;
    $res    = array('err_msg' => '', 'result' => '', 'qty' => 1);

    $attr_id    = !empty($_REQUEST['attr']) ? explode(',', $_REQUEST['attr']) : 0;
    $number     = (isset($_REQUEST['number'])) ? intval($_REQUEST['number']) : 1;

    if ($goods_id == 0)
    {
        $res['err_msg'] = $_LANG['err_change_attr'];
        $res['err_no']  = 1;
    }
    else
    {
		//預售，檢查庫存是否足夠--start
        if ($number == 0)
        {
            $res['qty'] = $number = 1;
        }
        else
        {
            $res['qty'] = $number;
        }
        if(empty($attr_id)){
        	$attr_id = 0;
        }
        $res['attr_num'] = get_product_attr_num($goods_id,$attr_id);

        $shop_price  = get_final_price($goods_id, $number, true, $attr_id);
        $mark_price = get_mark_price($goods_id);

		$shop_price = ($shop_price>=0) ? $shop_price : 0;

        $res['shop_price'] = price_format($shop_price);
        $res['result'] = price_format($shop_price * $number);
        $res['result1'] = price_format($mark_price);
		$res['result_jf'] = floor($shop_price * $number);
		
		$current_number = $res['attr_num'];
		if($number > $current_number && !empty($current_number))
		{
			$res['err_msg'] = sprintf($_LANG['err_shortage_little'], $current_number);
			$res['qty'] = $current_number;
			$res['err_no']  = 1;
		}
		//預售，檢查庫存是否足夠--end
    }

    die($json->encode($res));
}

/*預售信息 start*/
if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'allprice')
{
	include('includes/cls_json.php');

    $json   = new JSON;
    $res    = array('err_msg' => '', 'result' => '', 'qty' => 1);
    $number     = (isset($_REQUEST['number'])) ? intval($_REQUEST['number']) : 1;
    $attr_id    = isset($_REQUEST['attr']) ? $_REQUEST['attr'] : array();
    
	if(empty($attr_id)){
       $attr_id = 0;
    }
    $res['attr_num'] = get_product_attr_num($goods_id,$attr_id);
    
    $min_price  = get_final_price($goods_id, $number, true, 0);
    $mark_price_min = get_mark_price($goods_id);

	$res['result'] = price_format($min_price * $number);
	$res['result1'] = price_format($mark_price_min * $number);
	$ret_result = array('min_price'=>$min_price,'max_price'=>$max_price);

    die($json->encode($res));
    
    
}
/*預售信息 end*/

/*------------------------------------------------------ */
// 商品屬性關聯庫------開始
/*------------------------------------------------------ */
if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'get_products_info')
{
include('includes/cls_json.php');
$json = new JSON;
// $res = array('err_msg' => '', 'result' => '', 'qty' => 1);
$spce_id = $_GET['id'];
$goods_id = $_GET['goods_id'];
$row = get_products_info($goods_id,explode(",",$spce_id));
//$res = array('err_msg'=>$goods_id,'id'=>$spce_id);
die($json->encode($row));
}

/*------------------------------------------------------ */
//-- 商品購買記錄ajax處理
/*------------------------------------------------------ */

if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'gotopage')
{
    include('includes/cls_json.php');

    $json   = new JSON;
    $res    = array('err_msg' => '', 'result' => '');

    $goods_id   = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    $page    = (isset($_REQUEST['page'])) ? intval($_REQUEST['page']) : 1;

    if (!empty($goods_id))
    {
        $need_cache = $GLOBALS['smarty']->caching;
        $need_compile = $GLOBALS['smarty']->force_compile;

        $GLOBALS['smarty']->caching = false;
        $GLOBALS['smarty']->force_compile = true;

        /* 商品購買記錄 */
        $sql = 'SELECT u.user_name, og.goods_number, oi.add_time, IF(oi.order_status IN (2, 3, 4), 0, 1) AS order_status ' .
               'FROM ' . $ecs->table('order_info') . ' AS oi LEFT JOIN ' . $ecs->table('users') . ' AS u ON oi.user_id = u.user_id, ' . $ecs->table('order_goods') . ' AS og ' .
               'WHERE oi.order_id = og.order_id AND ' . time() . ' - oi.add_time < 2592000 AND og.goods_id = ' . $goods_id . ' ORDER BY oi.add_time DESC LIMIT ' . (($page > 1) ? ($page-1) : 0) * 5 . ',5';
        $bought_notes = $db->getAll($sql);

        foreach ($bought_notes as $key => $val)
        {
            $bought_notes[$key]['add_time'] = local_date("Y-m-d G:i:s", $val['add_time']);
        }

        $sql = 'SELECT count(*) ' .
               'FROM ' . $ecs->table('order_info') . ' AS oi LEFT JOIN ' . $ecs->table('users') . ' AS u ON oi.user_id = u.user_id, ' . $ecs->table('order_goods') . ' AS og ' .
               'WHERE oi.order_id = og.order_id AND ' . time() . ' - oi.add_time < 2592000 AND og.goods_id = ' . $goods_id;
        $count = $db->getOne($sql);


        /* 商品購買記錄分頁樣式 */
        $pager = array();
        $pager['page']         = $page;
        $pager['size']         = $size = 5;
        $pager['record_count'] = $count;
        $pager['page_count']   = $page_count = ($count > 0) ? intval(ceil($count / $size)) : 1;;
        $pager['page_first']   = "javascript:gotoBuyPage(1,$goods_id)";
        $pager['page_prev']    = $page > 1 ? "javascript:gotoBuyPage(" .($page-1). ",$goods_id)" : 'javascript:;';
        $pager['page_next']    = $page < $page_count ? 'javascript:gotoBuyPage(' .($page + 1) . ",$goods_id)" : 'javascript:;';
        $pager['page_last']    = $page < $page_count ? 'javascript:gotoBuyPage(' .$page_count. ",$goods_id)"  : 'javascript:;';

        $smarty->assign('notes', $bought_notes);
        $smarty->assign('pager', $pager);


        $res['result'] = $GLOBALS['smarty']->fetch('library/bought_notes.lbi');

        $GLOBALS['smarty']->caching = $need_cache;
        $GLOBALS['smarty']->force_compile = $need_compile;
    }

    die($json->encode($res));
}

/*------------------------------------------------------ */
//-- 商品屬性 api
/*------------------------------------------------------ */

if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'getattr')
{
    $properties = get_goods_properties($goods_id);  // 獲得商品的規格和屬性

    //sku 功能
    $sql = "SELECT goods_attr_id, attr_value FROM " . $GLOBALS['ecs']->table('goods_attr') . " WHERE goods_id = '$goods_id'";
    $results_goods_pro = $GLOBALS['db']->getAll($sql);
    $return_arr = array();
    foreach ($results_goods_pro as $value_mb5)
    {
        $return_arr[$value_mb5['goods_attr_id']] = $value_mb5['attr_value'];
    }

    $prod_options_arr=[];
    
    $prod_exist_arr = [];

    $sql_prod  = "select goods_attr from ". $GLOBALS['ecs']->table('products') ." where product_number>0 and goods_id='$goods_id' order by goods_attr";

    $res_prod = $db->query($sql_prod);

    while ($row_prod = $GLOBALS['db']->fetchRow($res_prod))
    {
        $prod_exist_arr[] = "|". $row_prod['goods_attr'] ."|";			
    }

    $GLOBALS['smarty']->assign('prod_exist_arr', $prod_exist_arr);

    $selected_first = [];

    foreach ($properties['spe'] AS $skey_mb5=>$sval_mb5)
    {
        $hahaha_zhyh = 0;
        $sskey_goods_pro = '-1';
        foreach ($sval_mb5['values'] AS $sskey_mb5=>$ssval_mb5)
        {				
            if ( is_exist_prod($selected_first, $ssval_mb5['id'], $prod_exist_arr))
            { 
                $hahaha_zhyh = $hahaha_zhyh ? $hahaha_zhyh : $ssval_mb5['id'];
                $sskey_goods_pro = ($sskey_goods_pro != '-1') ? $sskey_goods_pro : $sskey_mb5;
            }
            else
            {
                $properties['spe'][$skey_mb5]['values'][$sskey_mb5]['disabled'] = "disabled";
            }

        }
        if ($hahaha_zhyh)
        {
            $selected_first[$skey_mb5] =  $hahaha_zhyh;
        }
        if ($sskey_goods_pro!='-1')
        {
            $properties['spe'][$skey_mb5]['values'][$sskey_goods_pro]['selected_key_mb5'] = "1";
        }
    }

    print_r(json_encode(['code'=>200,'data'=>$properties]));
    exit;
}    

/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */

/* 判斷是否為正在預售的商品 */
$pre_sale_id = is_pre_sale_goods($goods_id);

if($pre_sale_id != null)
{
	$uri = build_uri("pre_sale", array("pre_sale_id" => $pre_sale_id));
	ecs_header("Location: $uri\n");
	exit;
}
/* 判斷是否為正在預售的商品 */
$cache_id = $goods_id . '-' . $_SESSION['user_rank'].'-'.$_CFG['lang'];
$cache_id = sprintf('%X', crc32($cache_id));
if (!$smarty->is_cached('goods.html', $cache_id) || 1==1)
{
    $smarty->assign('image_width',  $_CFG['image_width']);
    $smarty->assign('image_height', $_CFG['image_height']);
    $smarty->assign('helps',        get_shop_help()); // 網店幫助
    $smarty->assign('id',           $goods_id);
    $smarty->assign('type',         0);
    $smarty->assign('cfg',          $_CFG);
    $smarty->assign('promotion',       get_promotion_info($goods_id));//促銷信息
	$smarty->assign('comment_percent',     comment_percent($goods_id));  //獲取評分
    $smarty->assign('promotion_info', get_promotion_info());

    /* 獲得商品的信息 */
    $goods = get_goods_info($goods_id);
    if ($goods === false)
    {
        /* 如果沒有找到任何記錄則跳回到首頁 */
        ecs_header("Location: ./\n");
        exit;
    }
    else
    {
        if ($goods['brand_id'] > 0)
        {
            $goods['goods_brand_url'] = build_uri('brand', array('bid'=>$goods['brand_id']), $goods['goods_brand']);
        }

        $shop_price   = $goods['shop_price'];
        $linked_goods = get_linked_goods($goods_id);

        $goods['goods_style_name'] = add_style($goods['goods_name'], $goods['goods_name_style']);

        /* 購買該商品可以得到多少錢的紅包 */
        if ($goods['bonus_type_id'] > 0)
        {
            $time = gmtime();
            $sql = "SELECT type_money FROM " . $ecs->table('bonus_type') .
                    " WHERE type_id = '$goods[bonus_type_id]' " .
                    " AND send_type = '" . SEND_BY_GOODS . "' " .
                    " AND send_start_date <= '$time'" .
                    " AND send_end_date >= '$time'";
            $goods['bonus_money'] = floatval($db->getOne($sql));
            if ($goods['bonus_money'] > 0)
            {
                $goods['bonus_money'] = price_format($goods['bonus_money']);
            }
        }

        $smarty->assign('goods',              $goods);
        $smarty->assign('goods_id',           $goods['goods_id']);
        $smarty->assign('promote_end_time',   $goods['gmt_end_time']);
        $smarty->assign('categories',         get_categories_tree());  // 分類樹
		$smarty->assign('sales_count',        get_sales_count($goods_id));

        /* meta */
        $smarty->assign('keywords',           htmlspecialchars($goods['keywords']));
        $smarty->assign('description',        htmlspecialchars($goods['goods_brief']));


        $catlist = array();
        foreach(get_parent_cats($goods['cat_id']) as $k=>$v)
        {
            $catlist[] = $v['cat_id'];
        }

        assign_template('c', $catlist);

         /* 上一個商品下一個商品 */
        $prev_gid = $db->getOne("SELECT goods_id FROM " .$ecs->table('goods'). " WHERE cat_id=" . $goods['cat_id'] . " AND goods_id > " . $goods['goods_id'] . " AND is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0 LIMIT 1");
        if (!empty($prev_gid))
        {
            $prev_good['url'] = build_uri('goods', array('gid' => $prev_gid), $goods['goods_name']);
            $smarty->assign('prev_good', $prev_good);//上一個商品
        }

        $next_gid = $db->getOne("SELECT max(goods_id) FROM " . $ecs->table('goods') . " WHERE cat_id=".$goods['cat_id']." AND goods_id < ".$goods['goods_id'] . " AND is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0");
        if (!empty($next_gid))
        {
            $next_good['url'] = build_uri('goods', array('gid' => $next_gid), $goods['goods_name']);
            $smarty->assign('next_good', $next_good);//下一個商品
        }

        $position = assign_ur_here($goods['cat_id'], $goods['goods_name']);

        /* current position */
        $smarty->assign('page_title',          $position['title']);                    // 頁面標題
        $smarty->assign('ur_here',             $position['ur_here']);                  // 當前位置

        $properties = get_goods_properties($goods_id);  // 獲得商品的規格和屬性

        //sku 功能
        $sql = "SELECT goods_attr_id, attr_value FROM " . $GLOBALS['ecs']->table('goods_attr') . " WHERE goods_id = '$goods_id'";
		$results_goods_pro = $GLOBALS['db']->getAll($sql);
		$return_arr = array();
		foreach ($results_goods_pro as $value_mb5)
		{
			$return_arr[$value_mb5['goods_attr_id']] = $value_mb5['attr_value'];
		}

		$prod_options_arr=[];
		
		$prod_exist_arr = [];

        $sql_prod  = "select goods_attr from ". $GLOBALS['ecs']->table('products') ." where product_number>0 and goods_id='$goods_id' order by goods_attr";

        $res_prod = $db->query($sql_prod);

        while ($row_prod = $GLOBALS['db']->fetchRow($res_prod))
		{
			$prod_exist_arr[] = "|". $row_prod['goods_attr'] ."|";			
		}

        $GLOBALS['smarty']->assign('prod_exist_arr', $prod_exist_arr);

		$selected_first = [];

		foreach ($properties['spe'] AS $skey_mb5=>$sval_mb5)
		{
			$hahaha_zhyh = 0;
			$sskey_goods_pro = '-1';
			foreach ($sval_mb5['values'] AS $sskey_mb5=>$ssval_mb5)
			{				
				if ( is_exist_prod($selected_first, $ssval_mb5['id'], $prod_exist_arr))
				{ 
					$hahaha_zhyh = $hahaha_zhyh ? $hahaha_zhyh : $ssval_mb5['id'];
					$sskey_goods_pro = ($sskey_goods_pro != '-1') ? $sskey_goods_pro : $sskey_mb5;
				}
				else
				{
					$properties['spe'][$skey_mb5]['values'][$sskey_mb5]['disabled'] = "disabled";
				}

			}
			if ($hahaha_zhyh)
			{
				$selected_first[$skey_mb5] =  $hahaha_zhyh;
			}
			if ($sskey_goods_pro!='-1')
			{
				$properties['spe'][$skey_mb5]['values'][$sskey_goods_pro]['selected_key_mb5'] = "1";
			}
		}
		$smarty->assign('is_goods_page', 1);
		// echo '<pre>';
		// print_r($properties);
		// echo '</pre>';

        $smarty->assign('properties',          $properties['pro']);                              // 商品屬性

        $smarty->assign('specification',       $properties['spe']);                              // 商品規格
		
		//print_r($properties['spe']);
        $smarty->assign('attribute_linked',    get_same_attribute_goods($properties));           // 相同屬性的關聯商品
        $smarty->assign('related_goods',       $linked_goods);                                   // 關聯商品
        $smarty->assign('goods_article_list',  get_linked_articles($goods_id));                  // 關聯文章
        $smarty->assign('fittings',            get_goods_fittings(array($goods_id)));                   // 配件
        $smarty->assign('rank_prices',         get_user_rank_prices($goods_id, $shop_price));    // 會員等級價格

        $t_pictures = get_goods_gallery($goods_id);
        $i=0;
        foreach($t_pictures as $key => $val){
            $pictures[$i][]=$val;
            if(($key % 3) == 2){
                $i++;
            }
        }
        $smarty->assign('pictures',            $pictures);                    // 商品相冊
        $smarty->assign('bought_goods',        get_also_bought($goods_id));                      // 購買了該商品的用户還購買了哪些商品
        $smarty->assign('goods_rank',          get_goods_rank($goods_id));                       // 商品的銷售排名
		$smarty->assign('best_goods',      get_recommend_goods('best'));    // 推薦商品
		$smarty->assign('related_cat',         get_related_cat($goods['cat_id'])); 
		
		$smarty->assign('related_brand',         get_related_brand($goods['cat_id'])); 
		
		$smarty->assign('top10_brand',          get_top10_brand($goods['brand_id'])); 
		
		$smarty->assign('top10_category',       get_top10($goods['cat_id'])); 
		
		$smarty->assign('top10_price',       get_top10_price($goods['shop_price'])); 
		
		

		//by mike start
        //組合套餐名
        $comboTabIndex = array('一', '二', '三','四','五','六','七','八','九','十');
        $smarty->assign('comboTab',$comboTabIndex);
        //組合套餐組
        $fittings_list = get_goods_fittings(array($goods_id));
        if(is_array($fittings_list)){
                foreach($fittings_list as $vo){
                        $fittings_index[$vo['group_id']] = 1;//關聯數組
                }
        }
        ksort($fittings_index);//重新排序
        $smarty->assign('fittings_tab_index', $fittings_index);//套餐數量

        //by mike end
		
        //獲取tag
        $tag_array = get_tags($goods_id);
        $smarty->assign('tags',                $tag_array);                                       // 商品的標記

        //獲取關聯禮包
        $package_goods_list = get_package_goods_list($goods['goods_id']);
        $smarty->assign('package_goods_list',$package_goods_list);    // 獲取關聯禮包

        assign_dynamic('goods');
        $volume_price_list = get_volume_price_list($goods['goods_id'], '1');
        $smarty->assign('volume_price_list',$volume_price_list);    // 商品優惠價格區間
    }
}

/* 記錄瀏覽歷史 */
if (!empty($_COOKIE['ECS']['history']))
{
    $history = explode(',', $_COOKIE['ECS']['history']);

    array_unshift($history, $goods_id);
    $history = array_unique($history);

    while (count($history) > $_CFG['history_number'])
    {
        array_pop($history);
    }

    setcookie('ECS[history]', implode(',', $history), gmtime() + 3600 * 24 * 30);
}
else
{
    setcookie('ECS[history]', $goods_id, gmtime() + 3600 * 24 * 30);
}


/* 更新點擊次數 */
$db->query('UPDATE ' . $ecs->table('goods') . " SET click_count = click_count + 1 WHERE goods_id = '$_REQUEST[id]'");
$smarty->assign('now_time',  time());           // 當前系統時間
$smarty->display('goods.html',      $cache_id);

/*------------------------------------------------------ */
//-- PRIVATE FUNCTION
/*------------------------------------------------------ */

/**
 * 獲得指定商品的關聯商品
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_linked_goods($goods_id)
{
    $sql = 'SELECT g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, ' .
                "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ".
                'g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date ' .
            'FROM ' . $GLOBALS['ecs']->table('link_goods') . ' lg ' .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = lg.link_goods_id ' .
            "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ".
                    "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
            "WHERE lg.goods_id = '$goods_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".
            "LIMIT " . $GLOBALS['_CFG']['related_goods_number'];
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$row['goods_id']]['goods_id']     = $row['goods_id'];
        $arr[$row['goods_id']]['goods_name']   = $row['goods_name'];
        $arr[$row['goods_id']]['short_name']   = $GLOBALS['_CFG']['goods_name_length'] > 0 ?
            sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $arr[$row['goods_id']]['goods_thumb']  = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']    = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['market_price'] = price_format($row['market_price']);
        $arr[$row['goods_id']]['shop_price']   = price_format($row['shop_price']);
        $arr[$row['goods_id']]['url']          = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);

        if ($row['promote_price'] > 0)
        {
            $arr[$row['goods_id']]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $arr[$row['goods_id']]['formated_promote_price'] = price_format($arr[$row['goods_id']]['promote_price']);
        }
        else
        {
            $arr[$row['goods_id']]['promote_price'] = 0;
        }
    }

    return $arr;
}

/**
 * 獲得指定商品的關聯文章
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  void
 */
function get_linked_articles($goods_id)
{
    $sql = 'SELECT a.article_id, a.title, a.file_url, a.open_type, a.add_time ' .
            'FROM ' . $GLOBALS['ecs']->table('goods_article') . ' AS g, ' .
                $GLOBALS['ecs']->table('article') . ' AS a ' .
            "WHERE g.article_id = a.article_id AND g.goods_id = '$goods_id' AND a.is_open = 1 " .
            'ORDER BY a.add_time DESC';
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['url']         = $row['open_type'] != 1 ?
            build_uri('article', array('aid'=>$row['article_id']), $row['title']) : trim($row['file_url']);
        $row['add_time']    = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']);
        $row['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ?
            sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title'];

        $arr[] = $row;
    }

    return $arr;
}

/**
 * 獲得指定商品的各會員等級對應的價格
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_user_rank_prices($goods_id, $shop_price)
{
    $sql = "SELECT rank_id, IFNULL(mp.user_price, r.discount * $shop_price / 100) AS price, r.rank_name, r.discount " .
            'FROM ' . $GLOBALS['ecs']->table('user_rank') . ' AS r ' .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . " AS mp ".
                "ON mp.goods_id = '$goods_id' AND mp.user_rank = r.rank_id " .
            "WHERE r.show_price = 1 OR r.rank_id = '$_SESSION[user_rank]'";
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {

        $arr[$row['rank_id']] = array(
                        'rank_name' => htmlspecialchars($row['rank_name']),
                        'price'     => price_format($row['price']));
    }

    return $arr;
}

/**
 * 獲得購買過該商品的人還買過的商品
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_also_bought($goods_id)
{
    $sql = 'SELECT COUNT(b.goods_id ) AS num, g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price, g.promote_price, g.promote_start_date, g.promote_end_date ' .
            'FROM ' . $GLOBALS['ecs']->table('order_goods') . ' AS a ' .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('order_goods') . ' AS b ON b.order_id = a.order_id ' .
            'LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = b.goods_id ' .
            "WHERE a.goods_id = '$goods_id' AND b.goods_id <> '$goods_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 " .
            'GROUP BY b.goods_id ' .
            'ORDER BY num DESC ' .
            'LIMIT ' . $GLOBALS['_CFG']['bought_goods'];
    $res = $GLOBALS['db']->query($sql);

    $key = 0;
    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$key]['goods_id']    = $row['goods_id'];
        $arr[$key]['goods_name']  = $row['goods_name'];
        $arr[$key]['short_name']  = $GLOBALS['_CFG']['goods_name_length'] > 0 ?
            sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $arr[$key]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$key]['goods_img']   = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$key]['shop_price']  = price_format($row['shop_price']);
        $arr[$key]['url']         = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);

        if ($row['promote_price'] > 0)
        {
            $arr[$key]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $arr[$key]['formated_promote_price'] = price_format($arr[$key]['promote_price']);
        }
        else
        {
            $arr[$key]['promote_price'] = 0;
        }

        $key++;
    }

    return $arr;
}

/**
 * 獲得指定商品的銷售排名
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  integer
 */
function get_goods_rank($goods_id)
{
    /* 統計時間段 */
    $period = intval($GLOBALS['_CFG']['top10_time']);
    if ($period == 1) // 一年
    {
        $ext = " AND o.add_time > '" . local_strtotime('-1 years') . "'";
    }
    elseif ($period == 2) // 半年
    {
        $ext = " AND o.add_time > '" . local_strtotime('-6 months') . "'";
    }
    elseif ($period == 3) // 三個月
    {
        $ext = " AND o.add_time > '" . local_strtotime('-3 months') . "'";
    }
    elseif ($period == 4) // 一個月
    {
        $ext = " AND o.add_time > '" . local_strtotime('-1 months') . "'";
    }
    else
    {
        $ext = '';
    }

    /* 查詢該商品銷量 */
    $sql = 'SELECT IFNULL(SUM(g.goods_number), 0) ' .
        'FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS o, ' .
            $GLOBALS['ecs']->table('order_goods') . ' AS g ' .
        "WHERE o.order_id = g.order_id " .
        "AND o.order_status = '" . OS_CONFIRMED . "' " .
        "AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
        " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) .
        " AND g.goods_id = '$goods_id'" . $ext;
    $sales_count = $GLOBALS['db']->getOne($sql);

    if ($sales_count > 0)
    {
        /* 只有在商品銷售量大於0時才去計算該商品的排行 */
        $sql = 'SELECT DISTINCT SUM(goods_number) AS num ' .
                'FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS o, ' .
                    $GLOBALS['ecs']->table('order_goods') . ' AS g ' .
                "WHERE o.order_id = g.order_id " .
                "AND o.order_status = '" . OS_CONFIRMED . "' " .
                "AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
                " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . $ext .
                " GROUP BY g.goods_id HAVING num > $sales_count";
        $res = $GLOBALS['db']->query($sql);

        $rank = $GLOBALS['db']->num_rows($res) + 1;

        if ($rank > 10)
        {
            $rank = 0;
        }
    }
    else
    {
        $rank = 0;
    }

    return $rank;
}

/**
 * 獲得商品選定的屬性的附加總價格
 *
 * @param   integer     $goods_id
 * @param   array       $attr
 *
 * @return  void
 */
function get_attr_amount($goods_id, $attr)
{
    $sql = "SELECT SUM(attr_price) FROM " . $GLOBALS['ecs']->table('goods_attr') .
        " WHERE goods_id='$goods_id' AND " . db_create_in($attr, 'goods_attr_id');

    return $GLOBALS['db']->getOne($sql);
}

/**
 * 取得跟商品關聯的禮包列表
 *
 * @param   string  $goods_id    商品編號
 *
 * @return  禮包列表
 */
function get_package_goods_list($goods_id)
{
    $now = gmtime();
    $sql = "SELECT pg.goods_id, ga.act_id, ga.act_name, ga.act_desc, ga.goods_name, ga.start_time,
                   ga.end_time, ga.is_finished, ga.ext_info
            FROM " . $GLOBALS['ecs']->table('goods_activity') . " AS ga, " . $GLOBALS['ecs']->table('package_goods') . " AS pg
            WHERE pg.package_id = ga.act_id
            AND ga.start_time <= '" . $now . "'
            AND ga.end_time >= '" . $now . "'
            AND pg.goods_id = " . $goods_id . "
            GROUP BY ga.act_id
            ORDER BY ga.act_id ";
    $res = $GLOBALS['db']->getAll($sql);

    foreach ($res as $tempkey => $value)
    {
        $subtotal = 0;
        $row = unserialize($value['ext_info']);
        unset($value['ext_info']);
        if ($row)
        {
            foreach ($row as $key=>$val)
            {
                $res[$tempkey][$key] = $val;
            }
        }

        $sql = "SELECT pg.package_id, pg.goods_id, pg.goods_number, pg.admin_id, p.goods_attr, g.goods_sn, g.goods_name, g.market_price, g.goods_thumb, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price
                FROM " . $GLOBALS['ecs']->table('package_goods') . " AS pg
                    LEFT JOIN ". $GLOBALS['ecs']->table('goods') . " AS g
                        ON g.goods_id = pg.goods_id
                    LEFT JOIN ". $GLOBALS['ecs']->table('products') . " AS p
                        ON p.product_id = pg.product_id
                    LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp
                        ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]'
                WHERE pg.package_id = " . $value['act_id']. "
                ORDER BY pg.package_id, pg.goods_id";

        $goods_res = $GLOBALS['db']->getAll($sql);

        foreach($goods_res as $key => $val)
        {
            $goods_id_array[] = $val['goods_id'];
            $goods_res[$key]['goods_thumb']  = get_image_path($val['goods_id'], $val['goods_thumb'], true);
            $goods_res[$key]['market_price'] = price_format($val['market_price']);
            $goods_res[$key]['rank_price']   = price_format($val['rank_price']);
            $subtotal += $val['rank_price'] * $val['goods_number'];
        }

        /* 取商品屬性 */
        $sql = "SELECT ga.goods_attr_id, ga.attr_value
                FROM " .$GLOBALS['ecs']->table('goods_attr'). " AS ga, " .$GLOBALS['ecs']->table('attribute'). " AS a
                WHERE a.attr_id = ga.attr_id
                AND a.attr_type = 1
                AND " . db_create_in($goods_id_array, 'goods_id');
        $result_goods_attr = $GLOBALS['db']->getAll($sql);

        $_goods_attr = array();
        foreach ($result_goods_attr as $value)
        {
            $_goods_attr[$value['goods_attr_id']] = $value['attr_value'];
        }

        /* 處理貨品 */
        $format = '[%s]';
        foreach($goods_res as $key => $val)
        {
            if ($val['goods_attr'] != '')
            {
                $goods_attr_array = explode('|', $val['goods_attr']);

                $goods_attr = array();
                foreach ($goods_attr_array as $_attr)
                {
                    $goods_attr[] = $_goods_attr[$_attr];
                }

                $goods_res[$key]['goods_attr_str'] = sprintf($format, implode('，', $goods_attr));
            }
        }

        $res[$tempkey]['goods_list']    = $goods_res;
        $res[$tempkey]['subtotal']      = price_format($subtotal);
        $res[$tempkey]['saving']        = price_format(($subtotal - $res[$tempkey]['package_price']));
        $res[$tempkey]['package_price'] = price_format($res[$tempkey]['package_price']);
    }

    return $res;
}

 /* 商品累計銷量帶自定義_新增加 */  
function get_sales_count($goods_id)  
{  
    /* 查詢該商品的自定義銷量 */  
    $sales_base = $GLOBALS['db']->getOne('SELECT sales_volume_base FROM '.$GLOBALS['ecs']->table('goods').' WHERE goods_id = '.$goods_id);  
    /* 查詢該商品的實際銷量 */  
    $sql = 'SELECT IFNULL(SUM(g.goods_number), 0) ' .
        'FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS o, ' .
            $GLOBALS['ecs']->table('order_goods') . ' AS g ' .
        "WHERE o.order_id = g.order_id " .
        "AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
        " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) .
        " AND g.goods_id = '$goods_id'" ;
    $sales_count = $GLOBALS['db']->getOne($sql);
    /* 商品累計銷量默認顯示方式 */  
    if ($GLOBALS['_CFG']['show_sales_type'])  
    {  
        $row['sales_volume_total'] =  $sales_count; //實際銷量  
    }  
    else  
    {  
        $row['sales_volume_total'] =  $sales_base + $sales_count; //自定義銷量+實際銷量  
    }  
    return ($row['sales_volume_total']);  
}

/**
 * 獲取相關屬性的庫存
 * @param int $goodid 商品id
 * @param string(array) $attrids 商品屬性id的數組或者逗號分開的字符串
 */
function get_product_attr_num($goodid,$attrids=0){
	$ret = array();
	
	/* 判斷商品是否參與預售活動，如果參與則獲取商品的（預售庫存-已售出的數量） */
	if(!empty($_REQUEST['pre_sale_id']))
	{
		$pre_sale = pre_sale_info($_REQUEST['pre_sale_id'], $goods_num);
		//如果預售為空或者預售庫存小於等於0則認為不限購
		if(!empty($pre_sale) && $pre_sale['restrict_amount'] > 0){
			
			$product_num = $pre_sale['restrict_amount'] - $pre_sale['valid_goods'];
			
			return $product_num;
		}
	}
	
	if(empty($attrids)){
		$ginfo = get_goods_attr_value($goodid,'goods_number');
		return $ginfo['goods_number'];
	}
	if(!is_array($attrids)){
		$attrids = explode(',',$attrids);
	}

	$goods_attr_array = sort_goods_attr_id_array($attrids);

    if(isset($goods_attr_array['sort']))
    {
        $goods_attr = implode('|', $goods_attr_array['sort']);

		$sql = "SELECT product_id, goods_id, goods_attr, product_sn, product_number
                FROM " . $GLOBALS['ecs']->table('products') . " 
                WHERE goods_id = $goodid AND goods_attr = '".$goods_attr."' LIMIT 0, 1";
		$row = $GLOBALS['db']->getRow($sql);
		
		return $row['product_number'];
    }
}

/**
 * 獲取商品的相關信息
 * @param int $goodsid 商品id
 * @param string $name  要獲取商品的屬性名稱,多個，就用逗號分隔
 */
function get_goods_attr_value($goodsid,$name='goods_sn,goods_name')
{
	$sql = "select ".$name." from ". $GLOBALS['ecs']->table('goods') ." where goods_id=".$goodsid;
	$row = $GLOBALS['db']->getRow($sql);
	return $row;
}

function get_mark_price($goods_id)
{
	$sql = "SELECT market_price".
           " FROM " .$GLOBALS['ecs']->table('goods').
           " WHERE goods_id = '$goods_id'";
	$res = $GLOBALS['db']->getRow($sql);
	return $res['market_price'];
}

?>