<?php

namespace WebPlugin;

use WebPlugin\Paging;
use LibModels\Web\Product\BrandData;
use LibModels\Web\Product\SearchData;
use Api\Yohobuy;
use Api\Sign;
/**
 * 搜索辅助类
 */
class HelperSearch
{
    //请求时用的所有参数
    public static $params = array();

    public static $options = array();
    //当前页
    public static $page = 1;
    public static $pageTotal;
    public static $filter;

    //选中的条件
    public static $selected = array();

    //list分类面包屑
    public static $listNav = array();

    //设置导航
    private static function setListNav()
    {
        $options = self::$options;
        $cookieChannel = isset($_COOKIE['_Channel']) ? $_COOKIE['_Channel'] : 'boys';
        if (isset($options['brandName']) && !empty($options['brandName'])) {
            $initNav = $options['brandName'];
        }else{
            $initNav = '列表';
        }
        self::$listNav[0] = array(
            'href' => '',
            'name' => $cookieChannel
        );
        self::$listNav[1] = array(
            'href' => '',
            'name' => $initNav
        );
    }
    /**
     * 组织搜索模板数据
     * @param array $data
     * @param array $options
     * @return array
     */
    public static function getList($data = array() , $options = array())
    {
        $result = array();
        self::$params = $_GET;
        self::$options = $options;
        unset(self::$params['/']);
        unset(self::$params['page']);
        self::$filter = isset($data['product']['filter']) ? $data['product']['filter'] : array();
        //产品列表
        $result['goods'] = isset($data['product']['product_list']) ? self::getProductList($data['product']['product_list'], $options['imgSize']) : array();
        //总页数
        $result['page_total'] = isset($data['product']['page_total']) ? $data['product']['page_total'] : '';
        self::$pageTotal = $result['page_total'];
        //当前页
        $result['page'] = isset($data['product']['page']) ? $data['product']['page'] : '';
        self::$page = $result['page'];
        //筛选条件
        $result['filters'] = isset($data['product']['filter']) ? self::filter() : array();
        //排序方式、显示数量等其他选项
        $result['opts']  = isset($data['product']['filter']) ? self::getOpts() : array();
        //下一页
        if (isset($data['product']['page_total'])) {
            $result['hasNextPage'] = self::next($data['product']['page_total']);
        }
        //全部折扣
        if ($data['discount']['discount'] && !empty($data['discount']['discount'])) {
            $result['leftContent'][]['allDiscount'] = self::getDiscount($data['discount']['discount']);
        }
        //分类条件(搜索页面)
        if (isset($data['sort']) && isset($options['controller']) && $options['controller'] != 'Search') {
            $result['filters']['sort'] = self::searchSort($data['sort']['sort']);
        }
        //左侧分类分类
        $result['leftContent'][]['allSort'] = isset($data['sort']) ? self::groupSort($data['sort']['sort']) : array();
        //一周新品上架
        $result['leftContent'][]['newSales'] = isset($data['recent']) ? self::recentShelve($data['recent']['recent']) : array();
        //品牌banner
        $result['brandBanner'] = isset($data['brand']) ? self::getBannerFormat($data['brand'], $options['brandBanner']) : array();
        //总记录数
        $result['totalCount'] = $data['product']['total'];
        //品牌店铺信息
        $result['shopEntry'] = isset($data['shop']) && !empty($data['shop']) ? self::shop($data['shop'], $data['sort']['sort']) : array();
        //分页
        $result['pager'] = self::pager($result['totalCount'],$options['viewNum']-1);
        //浏览记录
        if (isset($options['reviewNum']) && !empty($options['reviewNum'])) {
            $result['latestWalk'] = $options['reviewNum'];
        }
        //选中条件
        $result['filters']['checkedConditions'] = self::getSelected();
        if (isset($options['controller']) && $options['controller'] == 'Search') {
            self::setSearchNav($data['product']['total']);
        }
        if (empty($result['goods'])) {
            $result['filters'] = array();
            $result['opts'] = array();
        }
        $result['pathNav'] = isset($options['controller']) && $options['controller'] == 'Sale' ? array() : self::$listNav;
        return $result;
    }

    /**
     * TODO 组织商品列表信息
     * @param $product 接口返回商品列表
     * @author sefon 2015-12-21 17:24:04
     * @return array
     */
    public static function getProductList($product,$imgSize)
    {
        $params = self::$params;
        $goods = array();
        if (empty($product)) {
            return $goods;
        }
        foreach($product as $key => $val){
            //NEW
            $isNew = $val['is_new'] == 'Y' ? true : false;
            //限量商品
            $isLimit = isset($val['is_limited']) && $val['is_limited'] === 'Y';
            //即将售罄
            $isFew = $val['is_soon_sold_out'] === 'Y' ? true : false;
            //SALE
            //新品节
            //再到着
            //年终大促
            // 年中大促
            foreach($val['goods_list'] as $k => $v){
                $goods_list[$k]['url'] = Helpers::getUrlBySkc($val['product_id'], $v['goods_id'], $val['cn_alphabet']);
                //筛选符合颜色条件的封面图片
                if (isset($params['color']) && $params['color'] == $v['color_id']) {
                    $val['default_images'] = Images::getImageUrl($v['images_url'],$imgSize[0],$imgSize[1]);
                }
            }
            if (!empty($val['default_images'])) {
                $val['default_images'] = Images::getImageUrl($val['default_images'],$imgSize[0],$imgSize[1]);
            }
            $good = array(
                'tags' => array(
                    'isNew' => $isNew,
                    'isLimit' => $isLimit
                ),
                'url' => $goods_list[0]['url'],
                'thumb' => $val['default_images'],
                'name' => $val['product_name'],
                'salePrice' => $val['sales_price'],
                'isFew' => $isFew,
                'skn' => $val['product_skn'],
                'showColBtn' => true,
                'coled' => true
            );
            //市场价不等于售价时显示
            if ($val['market_price'] != $val['sales_price']) {
                $good['marketPrice'] = $val['market_price'];
            }
            $goods[] = $good;
        }
        return $goods;
    }
    /**
     * 版型等其它筛选项
     * @param $filter
     * @return array
     */
    public static function standard($filter)
    {
        $params = self::$params;
        $result = array();
        foreach ($filter as $key => $val) {
            if (substr_compare($key, 'parameter', 0, 9) != 0) {
                continue;
            }
            if (!isset($val['sub']) || empty($val['sub'])) {
                continue;
            }
            $sub = array();
            foreach ($val['sub'] as $pval) {
                if (isset(self::$params['parameter_' . $val['standard_id']]) && self::$params['parameter_' . $val['standard_id']] == $pval['standard_id']) {
                    $tmpParams = self::$params;
                    unset($tmpParams['parameter_' . $val['standard_id']]);
                    self::$selected['parameter_' . $val['standard_id']] = array(
                        'name' => $pval['standard_name'],
                        'href' => self::buildUrl($tmpParams)
                    );
                    if (self::checkSearch('parameter_' . $val['standard_id'])) {
                        return array();
                    }
                }
                $sub[] = array(
                    'name' => $pval['standard_name'],
                    'href' => self::buildUrl(array_merge($params, array(
                        'parameter_' . $val['standard_id'] => $pval['standard_id']
                    ))) ,
                    'checked' => isset(self::$params['parameter_' . $val['standard_id']]) && self::$params['parameter_' . $val['standard_id']] == $pval['standard_id'] ? true : false
                );
            }
            if (!empty($sub) && count($sub) > 1) {
                $result[] = array(
                    'name' => $val['standard_name'],
                    'sub' => $sub
                );
            }
        }
        return $result;
    }

    /**
     * 性别
     * @return array
     */
    public static function gender($filter)
    {
        if (empty($filter) || !isset($filter['gender']) || empty($filter['gender'])) {
            return array();
        }
        $params = self::$params;
        $gender = isset($params['gender']) ? $params['gender'] : '';
        if (isset($params['gender'])) {
            unset($params['gender']);
        }
        //设置选中
        if ($gender == '1,3' || $gender == '2,3') {
            self::$selected['gender'] = array(
                'name' => $gender == '1,3' ? 'BOYS' : 'GIRLS',
                'href' => self::buildUrl($params)
            );
        }

        if (self::checkSearch('gender')) {
            return array();
        }
        $result = array();
        foreach ($filter['gender'] as $key => $val) {
            $result[] = array(
                'name' => $val,
                'href' => self::buildUrl(array_merge($params, array(
                    'gender' => $key,
                ))) ,
                'checked' => isset(self::$params['gender']) && self::$params['gender'] == $key ? true : false
            );
        }
        return $result;
    }

    /**
     * 组织搜索列表页面的左侧分类
     * @param array $sort
     * @return array
     */

    public static function groupSort($sort)
    {
        $options = self::$options;
        if (isset($options['controller']) && $options['controller'] == 'Search') {
            return array();
        }
        //设置导航
        self::setListNav($options);
        $params = self::$params;
        $result = array(
            'all' => array(
                'name' => '全部品类',
                'href' => self::buildUrl() ,
                'active' => isset($params['msort']) ? false : true,
            ) ,
            'list' => array()
        );
        $sortList = array();
        foreach ($sort as $key => $val) {
            //若参数有分类,设置导航
            if (isset($params['msort']) && $params['msort'] == $val['sort_id']) {
                //是否有品牌
                $navIndex = isset($option['brandName']) && $option['brandName'] ? 2 : 1;
                self::$listNav[$navIndex] = array(
                    'name' => $val['sort_name'],
                    'href' => self::buildUrl(array(
                        'msort' => $val['sort_id'],
                    ))
                );
            }
            unset($params['msort']);
            unset($params['misort']);
            $sortList[$key]['name'] = $val['sort_name'];
            $sortList[$key]['active'] = isset(self::$params['msort']) && self::$params['msort'] == $val['sort_id'] ? true : false;
            $sortList[$key]['childList'][] = array(
                'name' => '全部分类',
                'href' => self::buildUrl(array_merge($params, array('msort'=>$val['sort_id'])))
            );
            if (isset($val['sub']) && !empty($val['sub'])) {
                foreach ($val['sub'] as $k => $v) {
                    $sortList[$key]['childList'][$k+1]['name'] = $v['sort_name'];
                    $sortList[$key]['childList'][$k+1]['href'] = self::buildUrl(array_merge($params, array('msort' => $val['sort_id'], 'misort' => $v['sort_id'])));
                    $sortList[$key]['childList'][$k+1]['childActive'] = isset(self::$params['misort']) && self::$params['misort'] == $v['sort_id'] ? true : false;
                }
            }
        }
        $result['list'] = $sortList;
        return $result;
    }

    public static function searchSort($sort)
    {
        $result = array();
        $options = self::$options;
        $params = self::$params;
        foreach ($sort as $key => $val) {
            $result[$key]['id'] = $val['sort_id'];
            $result[$key]['name'] = $val['sort_name'];
            if (isset($val['sub']) && !empty($val['sub'])) {
                foreach ($val['sub'] as $k => $v) {
                    $result[$key]['sub'][$k]['href'] = self::buildUrl(array_merge($params,array('msort' => $val['sort_id'], 'misort' => $v['sort_id'])));
                    $result[$key]['sub'][$k]['name'] = $v['sort_name'];
                    if (isset($params['misort']) && $params['misort'] == $v['sort_id']) {
                        unset($params['msort']);
                        unset($params['misort']);
                        self::$selected['sort'] = array(
                            'name' => $v['sort_name'],
                            'href' => self::buildUrl($params)
                        );
                    }

                }
            }
        }
        if (self::checkSearch('msrot') || self::checkSearch('misort')) {
            return array();
        }
        return $result;
    }
    /**
     * 品牌,可以多选
     * @param array $filter
     * @return array
     */
    public static function brand($filter)
    {
        $options = self::$options;
        //品牌列表返回空
        if (isset($options['brandName'])) {
            return array();
        }
        $result = array(
            'default' => array() ,
            'brandIndex' => array(
                array(
                    'index' => 'all',
                    'name' => '全部'
                )
            ),
            'brandsShow' => array()
        );
        $params = self::$params;
        //url中的品牌ids
        $brandIds = isset($params['brand']) && !empty($params['brand']) ? explode(',', $params['brand']) : array();
        if (isset($filter['brand']) && !empty($filter['brand'])) {
            $brand = $filter['brand'];
            //已选中品牌数量
            $existBrandNum = 0;
            //已选中品牌标签名
            $existName = '';
            foreach ($brand as $key => $v) {
                $selectBrandIds = $brandIds;
                //品牌已被选中
                if (in_array($v['id'], $brandIds)) {
                    $filterKey = array_search($v['id'], $selectBrandIds);
                    unset($selectBrandIds[$filterKey]);
                    $url = self::buildUrl(array_merge($params, array(
                        'brand' => implode(',', $selectBrandIds)
                    )));
                    if ($existBrandNum === 0) {
                        $existName .= $v['brand_name'].'、';
                    }
                    if ($existBrandNum === 1){
                        $existName .= substr($v['brand_name'], 0, 3).'...';
                    }
                    $existBrandNum++;
                }
                //该品牌未被选中
                else {
                    $selectBrandIds[] = $v['id'];
                    $url = self::buildUrl(array_merge($params, array(
                        'brand' => implode(',', $selectBrandIds)
                    )));
                }
                $this_brand = array(
                    'id' => $v['id'],
                    'href' => $url,
                    'name' => $v['brand_name'],
                    'key' => strtolower($v['brand_name']),
                    'checked' => in_array($v['id'], $brandIds) ? true : false
                );
                if (is_numeric($v['brand_alif'])) {
                    $this_brand['index'] = '0-9';
                }
                else {
                    $this_brand['index'] = strtolower($v['brand_alif']);
                }
                //默认品牌
                if (count($result['default']) < 10) {
                    $result['default'][] = $this_brand;
                }
               //品牌列表
                $brandList[$v['brand_alif']][] = $this_brand;
                $brandAll[$v['id']] = $v['brand_name'];
            }
            //清空品牌参数
            unset($params['brand']);
            //设置选中
            if (isset(self::$params['brand']) && !empty(self::$params['brand'])) {
                self::$selected['brand'] = array(
                    'name' => rtrim($existName, '、'),
                    'href' => self::buildUrl($params)
                );
            }
            ksort($brandList);
            //品牌列表排序, 添加品牌索引
            $index_key = array();
            foreach ($brandList as $key => $val) {
                if ($key && !in_array($key, $index_key) && !is_numeric($key)) {
                    $index['index'] = strtolower(($key));
                    $index['name'] = $key;
                    $index_key[] = $index;
                }
                if ($key && !in_array($key, $index_key) && is_numeric($key) && count($result['brandIndex']) === 1) {
                    $index['index'] = '0-9';
                    $index['name'] = '0~9';
                    $result['brandIndex'][] = $index;
                }
                if (is_array($val)) {
                    foreach ($val as $v) {
                        $result['brandsShow'][] = $v;
                     }
                }
            }
            $result['brandIndex'] = array_merge($result['brandIndex'], $index_key);
            unset($brandList);
        }
        //搜索页已选中,返回空
        if (self::checkSearch('brand')) {
            return array();
        }
        //品牌数量小于等于10,隐藏更多按钮
        if (count($result['brandsShow']) < 11) {
            $result['hideMore'] = true;
        }
//        print_r($result); exit;
        return $result;
    }
    /**
     * 尺码的链接,不能多选
     * @param array $filter
     * @return array
     */
    public static function size($filter, $isAjax = false)
    {
        $params = self::$params;
        $paramsValue = array_filter($params);
        $sizeId = isset($params['size']) && !empty($params['size']) ? $params['size'] : '';
        if (isset($params['size'])) {
            unset($params['size']);
        }
        $result = array();
        if (!$isAjax && empty($paramsValue)) {
            return array();
        }
        if (isset($filter['size']) && !empty($filter['size'])) {
            $size = $filter['size'];
            foreach ($size as $k=> $v) {
                //设置选中
                if ($v['size_id'] == $sizeId) {
                    self::$selected['size'] = array(
                        'name' => $v['size_name'],
                        'href' => self::buildUrl($params)
                    );
                }
                $result[] = array(
                    'name' => $v['size_name'],
                    'href' => self::buildUrl(array_merge($params, array(
                        'size' => $v['size_id']
                    ))) ,
                    'checked' => isset(self::$params['size']) && self::$params['size'] == $v['size_id'] ? true : false
                );
            }
            if ( self::checkSearch('size')) {
                return array();
            }
        }
        return $result;
    }

    /**
     * 颜色,不能多选
     * @param array $filter
     * @return array
     */
    public static function color($filter)
    {
        $params = self::$params;
        $colorId = isset($params['color']) && !empty(self::$params['color']) ? self::$params['color'] : '';
        if (isset($params['color'])) {
            unset($params['color']);
        }
        $result = array();
        $color = $filter['color'];
        foreach ($color as $v) {
            //设置已选中
            if ($v['color_id'] == $colorId) {
                $background = empty($v['color_value']) ? '#' . $v['color_code'] : "url(" . $v['color_value'] . ")";
                self::$selected['color'] = array(
                    'color' =>  $background,
                    'href' => self::buildUrl($params)
                );
            }
            $result[] = array(
                'name' => $v['color_name'],
                'rgb' => empty($v['color_value']) ? '#' . $v['color_code'] : "url({$v['color_value']})",
                'href' => self::buildUrl(array_merge($params, array(
                    'color' => $v['color_id']
                ))) ,
            );
        }
        if (self::checkSearch('color')) {
            return array();
        }
        return $result;
    }

    /**
     * 获取价格,不能多选
     * @param array $filter
     * @return array
     */
    public static function price($filter)
    {
        $params = self::$params;
        $priceId = isset($params['price']) && !empty(self::$params['price']) ? self::$params['price'] : '';
        if (isset($params['price'])) {
            unset($params['price']);
        }
        $result = array();
        //设置已选中价格
        if (!empty($priceId) && isset($filter['price'][$priceId])) {
            self::$selected['price'] = array(
                'name' => $filter['price'][$priceId],
                'href' => self::buildUrl($params)
            );
        }else{
            $price = explode(',', $priceId);
            if (count($price) == 2) {
                if (!$price[0]) {
                    $price[0] = 0;
                }
                if (!$price[1]) {
                    $price[1] = 99999;
                }
                self::$selected['price'] = array(
                    'name' => self::$params['price'] == '2000,99999' ? '¥2000以上' : '¥' . (int)$price[0] . '-' . (int)$price[1],
                    'href' => self::buildurl($params)
                );
            }
        }
        if (self::checkSearch('price')) {
            return array();
        }
        //返回价格条件
        foreach ($filter['price'] as $key => $val) {
            $val = trim($val,'¥');
            $result[] = array(
                'name' => $val,
                'href' => self::buildUrl(array_merge($params, array(
                    'price' => $key
                ))) ,
                'checked' => isset(self::$params['price']) && self::$params['price'] == $key ? true : false
            );
        }
        return $result;
    }

    /**
     * 获取自定义价格要提交的地址
     */
    public static function customPrice($filter)
    {
        $params = self::$params;
        $result = array(
            'min' => '',
            'max' => ''
        );
        $priceId = isset($params['price']) && !empty(self::$params['price']) ? self::$params['price'] : '';
        if (isset($params['price']) && !isset($filter['price'][$priceId])  ) {
            $price = explode(',', $params['price']);
            unset($params['price']);
            if (!$price[0]) {
                $price[0] = 0;
            }
            if (!$price[1]) {
                $price[1] = 99999;
            }
            $result = array(
                'min' => $price[0],
                'max' => $price[1]
            );
        }
        return $result;
    }

    /**
     * 风格,可以多选
     * @param array $filter
     * @return array
     */
    public static function style($filter)
    {
        $params = self::$params;
        $styleIds = isset($params['style']) && !empty($params['style']) ? explode(',', $params['style']) : array();
        if (isset($params['style'])) {
            unset($params['style']);
        }
        $result = array();
        $style = $filter['style'];
        $styleNum = 0;
        $styleName = '';
        foreach ($style as $v) {
            //选中的筛选条件
            if (in_array($v['style_id'], $styleIds)) {
                if (!$styleNum) {
                    $styleName = $v['style_name']."、";
                }
                elseif ($styleNum ===1){
                    $styleName .= substr($v['style_name'], 0, 3).'...';
                }
                $styleNum ++;
            }
            $selectedStyle = isset(self::$params['style']) && !empty(self::$params['style']) ? explode(',', self::$params['style']) : array();
            //风格id在提交的参数中,构造url参数去除该风格id
            if (in_array($v['style_id'], $selectedStyle)) {
                $filterKey = array_search($v['style_id'], $selectedStyle);
                unset($selectedStyle[$filterKey]);
                $url = self::buildUrl(array_merge($params, array(
                    'style' => implode(',', $selectedStyle)
                )));
            }
            //该风格url参数中添加该风格的id
            else {
                $selectedStyle[] = $v['style_id'];
                $url = self::buildUrl(array_merge($params, array(
                    'style' => implode(',', $selectedStyle)
                )));
            }
            $result[] = array(
                'id' => $v['style_id'],
                'name' => $v['style_name'],
                'href' => $url,
            );
        }
        if (isset(self::$params['style']) && !empty(self::$params['style'])) {
            self::$selected['style'] = array(
                'name' => rtrim($styleName, '、'),
                'href' => self::buildUrl($params)
            );
        }
        $data[0] = array(
            'attr' => 'style',
            'name' => '风格',
            'showMulti' => true,
            'sub' => $result
        );
        return $data;
    }
    /**
     * 高级选项
     */
    public static function seniorChose($filter)
    {
        $style = self::style($filter);
        $other = self::standard($filter);
        $result = array_merge($style,$other);
        //搜索页已选中,返回空
        if (self::checkSearch('style') || self::checkSearch('parameter')) {
            return array();
        }
        return $result;
    }

    /**
     *  每页显示数量
     */
    public static function viewNum()
    {
        $params = self::$params;
        $viewNum = array(60, 100, 200);
        $result = array();
        foreach ($viewNum as $value) {
            $params['viewNum'] = $value;
            $params['page'] = 1;
            $result[] = array(
                'count' => $value,
                'href' => self::buildUrl($params)
            );
        }
        return $result;
    }

    /**
     *  显示行数
     */
    public static function rowNum($num = 5)
    {
        $params = self::$params;
        $params['rowNum'] = $num;
        return self::buildUrl($params);
    }

    /**
     * 是否特价
     */
    public static function specialoffer()
    {
        $selected = '';
        $params = self::$params;
        if (isset($params['specialoffer']) && !empty($params['specialoffer'])) {
            unset($params['specialoffer']);
            $selected = true;
        }
        else {
            $params['specialoffer'] = 'Y';
        }
        return array(
            'name' => '打折',
            'href' => self::buildUrl($params) ,
            'checked' => $selected
        );
    }

    /**
     * 是否限量
     */
    public static function limited()
    {
        $selected = '';
        $params = self::$params;
        if (isset($params['limited']) && !empty($params['limited'])) {
            unset($params['limited']);
            $selected = true;
        }
        else {
            $params['limited'] = 'Y';
        }
        return array(
            'name' => '限量',
            'href' => self::buildUrl($params) ,
            'checked' => $selected
        );
    }

    /**
     * 是否新品
     */
    public static function isnew()
    {
        $params = self::$params;
        $selected = '';
        if (isset($params['new']) && !empty($params['new'])) {
            unset($params['new']);
            $selected = true;
        }
        else {
            $params['new'] = 'Y';
        }
        return array(
            'name' => '新品',
            'href' => self::buildUrl($params) ,
            'checked' => $selected
        );
    }

    /**
     *  排序是否最新
     */
    public static function orderTime()
    {
        $params = self::$params;
        if (isset($params['order'])) {
            unset($params['order']);
        }
        $result = array(
            'name' => '最新',
            'href' => isset(self::$params['order']) && self::$params['order'] == 's_t_desc' ? self::buildUrl($params) : self::buildUrl(array_merge($params, array(
                'order' => 's_t_asc'
            ))) ,
            'active' => isset(self::$params['order']) && self::$params['order'] == 's_t_asc' ? true : ''
        );
        return $result;
    }

    /**
     *  排序是否默认
     */
    public static function orderDefault()
    {
        $params = self::$params;
        if (isset($params['order'])) {
            unset($params['order']);
        }
        $result = array(
            'name' => '默认',
            'href' => self::buildUrl($params) ,
            'active' => !isset(self::$params['order']) || empty(self::$params['order']) ? true : ''
        );
        return $result;
    }

    /**
     *  价格排序
     */
    public static function orderPrice()
    {
        $params = self::$params;
        if (isset($params['order'])) {
            unset($params['order']);
        }
        if (!isset(self::$params['order']) || empty(self::$params['order']) || !in_array(self::$params['order'], array(
                's_p_asc',
                's_p_desc'
            ))) {
            $url = self::buildUrl(array_merge($params, array(
                'order' => 's_p_asc'
            )));
            $active = '';
            $desc = '';
        }
        else if (self::$params['order'] == 's_p_asc') {
            $url = self::buildUrl(array_merge($params, array(
                'order' => 's_p_desc'
            )));
            $active = true;
            $desc = true;

        }
        else {
            $url = self::buildUrl(array_merge($params, array(
                'order' => 's_p_asc'
            )));
            $active = true;
            $desc = false;
        }
        $result = array(
            'name' => '价格',
            'href' => $url,
            'hasSortOrient' => true,
            'active' => $active,
            'desc' => $desc
        );
        return $result;
    }

    /**
     *  折扣排序
     */
    public static function orderDiscount()
    {
        $params = self::$params;
        if (isset($params['order'])) {
            unset($params['order']);
        }
        if (!isset(self::$params['order']) || empty(self::$params['order']) || !in_array(self::$params['order'], array(
                'p_d_asc',
                'p_d_desc'
            ))) {
            $url = self::buildUrl(array_merge($params, array(
                'order' => 'p_d_asc'
            )));
            $active = '';
            $desc = true;
        }
        else if (self::$params['order'] == 'p_d_asc') {
            $url = self::buildUrl(array_merge($params, array(
                'order' => 'p_d_desc'
            )));
            $desc = true;
            $active = true;
        }
        else {
            $url = self::buildUrl(array_merge($params, array(
                'order' => 'p_d_asc'
            )));
            $desc = false;
            $active = true;
        }
        $result = array(
            'name' => '折扣',
            'href' => $url,
            'hasSortOrient' => true,
            'active' => $active,
            'desc' => $desc,
        );

        return $result;
    }

    /**
     * 组织参数
     * @param array $params
     * @return string
     */
    private static function buildUrl($params = array())
    {
        if (empty($params)) {
            return self::current();
        }
        $queryPath = explode('?', $_SERVER['REQUEST_URI']);
        $params_arr = array();
        foreach ($params as $key => $val) {
            if (is_array($val) || $val === '') {
                continue;
            }
            $params_arr[] = $key . '=' . $val;
        }
        if (empty($params_arr)) {
            return self::current();
        }
        else {
            return (empty($queryPath[0]) ? '/' : $queryPath[0]) . '?' . implode('&', $params_arr);
        }
    }

    /**
     * 获取选中的条件
     */
    public static function getSelected()
    {
        $result = array();
        $data = array();
        foreach (self::$selected as $key => $val) {
                $data[] = $val;
        }
        if ($data) {
            $result['conditions'] = $data;
            $result['clearUrl'] = self::current();
        }
        return $result;
    }

    /**
     * 打折区间
     * @param array $list
     * @return array
     */
    public static function getDiscount(array $list = array())
    {
        $params = self::$params;
        $query = array();
        $total = 0;
        foreach ($list as $k => $v) {
            $total += $v['count'];
            $query['p_d'] = $k;
            $list[$k]['href'] = self::buildUrl($query);
            $list[$k]['active'] = isset($params['p_d']) && $params['p_d'] == $k ? true : false;
        }
        $result = array(
            'list' => array_values($list)
        );
        return $result;
    }

    /**
     * 最新上架
     */
    public static function recentShelve($list = array())
    {
        if (empty($list)) {
            return array();
        }
        $params = self::$params;
        $query = array();
        $data = array();
        $i = 0;
        foreach ($list as $k => $v) {
            $star_time = strtotime($k);
            $end_time = $star_time+60*60*24;
            $query['shelve_time'] = '';
            $query['shelve_time'] = $star_time.','.$end_time;
            if (isset($params['shelve_time']) && $query['shelve_time'] == $params['shelve_time']) {
                $data[$i]['active'] = true;
            }
            $data[$i]['href'] = self::buildUrl($query);
            $data[$i]['name'] = $k;
            $i++;
        }
        $result = array(
            //'updateNum' => $total,
            'list' => $data
        );
        unset($data);
        unset($query);
        return $result;
    }
    /**
     * 当前页地址
     */
    public static function current()
    {
        $url =  explode('?', 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        self::$listNav[0]['href'] = $url[0];
        return $url[0];
    }
    /**
     * 下一页
     */
    public static function next($total)
    {
        $param = self::$params;
        $page = self::$page;
        $next = array();
        if ($page < $total) {
            $page ++;
            $param['page'] = $page;
            $nextUrl = self::buildUrl($param);
            $next = array(
                'href' => $nextUrl,
                'src' => 'http://img10.static.yhbimg.com/product/2014/01/15/11/01fa01614784f6239760f1b749663016f1.jpg?imageMogr2/thumbnail/235x314/extent/235x314/background/d2hpdGU=/position/center/quality/90'
            );
        }
        return $next;
    }

    /**
     * 组织产品的图片
     * @param $product
     * @param $options
     * @return array
     */
    public static function getProductPic($product, $options)
    {
        $result = array();
        if (isset($product[0]['goods_list']) && !empty($product[0]['goods_list'])){
            foreach ($product[0]['goods_list'] as $key => $val){
                $result[$key]['coverImg'] = Images::getImageUrl($val['images_url'], $options['imgSize'][0], $options['imgSize'][1]);
                $result[$key]['url'] = Helpers::getUrlBySkc($product[0]['product_id'], $val['goods_id'], $product[0]['cn_alphabet']);
                $result[$key]['src'] = Images::getImageUrl($val['images_url'], $options['imgSize'][0], $options['imgSize'][1]);
            }
        }
        return $result;
    }

    /**
     * 分页
     * @param $total
     * @param $viewNum
     * @return mixed
     */
    public static function pager($total, $viewNum){
        $Paging = new Paging('Yoho');
        return $Paging->setTotal($total)->setSize($viewNum)->view(0);
    }
    
    //组织静态资源数据格式
    public static function formatNodeContent($code)
    {
        $nodeContent = BrandData::getByNodeContent($code);
            if (isset($nodeContent['code']) && $nodeContent['code'] === 200) {
                $result = array();
                
                $string = $nodeContent['data'];
                $hrefPatten="/<a href=[\'\"]?([^\'\" ]+).*?>/";
                preg_match_all($hrefPatten, $string, $href);

                $pattern = "/[img|IMG].*?src=['|\"](.*?(?:[.gif|.jpg]))['|\"].*?[\/]?>/";
                preg_match_all($pattern,$string,$img);
                
                foreach($href[1] as $key=>$vo){
                        $result[$key]['href'] = $vo;
                        $result[$key]['src'] = $img[1][$key];
                }
               return $result;
            }
    }

    /**
     * 组织品牌店铺信息
     * @param $shop
     * @param $shopSort
     * @return array
     */
    public static function shop($shop, $shopSort)
    {
        $url = Helpers::url('','',$shop['brand_domain']);
        $shopEntry = array();
        $sort = array();
        foreach ($shopSort as $msort) {
            if (!isset($msort['sub']) || empty($msort['sub'])) {
                continue;
            }
            foreach ($msort['sub'] as $mkey=>$misort) {
                if (count($sort) >= 10) {
                    break 2;
                }
                $sortInfo['href'] = $url.'/?msort=' . $msort['sort_id'] . '&misort=' . $misort['sort_id'];
                $sortInfo['name'] = $misort['sort_name'];
                $sort[] = $sortInfo;
            }

        }
        $shopEntry['home'] = $url;
        $shopEntry['logo'] = Images::getSourceUrl($shop['brand_ico'],'brandLogo');
        $shopEntry['shopName'] = $shop['brand_name'];
        $shopEntry['sort'] = $sort;
        return $shopEntry;
    }

    public static function checkSearch($param)
    {
        if (isset(self::$options['controller']) && self::$options['controller'] == 'Search') {
            foreach (self::$params as $key =>$val) {
                if (strpos($key, $param) !== false) {
                    return true;
                }
            }
        }

    }

    /**
     * 设置搜索页导航
     * @param $total
     */
    public static function setSearchNav($total)
    {
        self::$listNav[0] = array(
            'href' => '/',
            'name' => '首页'
        );
        $param = self::$params;
        $options = self::$options;
        if (isset($options['controller']) && $options['controller'] == 'Search' && isset($param['query'])) {
            self::$listNav[1] = array(
                'href' => '',
                'name' => '搜索“<span id="nav_keyword">'.$param['query'].'</span>”共<span id="nav_keyword_count">'.$total.'</span>个结果'
            );
        }else{
            self::$listNav[1] = array(
                'href' => '',
                'name' => '所有商品'
            );
        }

    }
    
    /**
     * 并行调接口url获取(搜索产品数据)
     * @param 
     */
    public static function getProductUrl($condition)
    {
        // 排序数据映射表
        $orderMaps = array(
            's_t_desc' => 'shelve_time:desc',
            's_t_asc' => 'shelve_time:asc',
            's_p_asc' => 'sales_price:asc',
            's_p_desc' => 'sales_price:desc',
            'p_d_desc' => 'discount:desc',
            'p_d_asc' => 'discount:asc',
            'skn_desc' => 'product_skn:desc',
            'skn_asc' => 'product_skn:asc',
            'activities_desc' => 'activities.order_by:desc',
            'activities_asc' => 'activities.order_by:asc',
            's_n_asc' => 'sales_num:asc',
            's_n_desc' => 'sales_num:desc',
            'activities_id_desc' => 'activities.activity_id:desc',
            'activities_id_asc' => 'activities.activity_id:asc',
        );
        $param = array();
        $param['status'] = 1; // 是否上架,1表示在架,2表示不在
        $param['sales'] = 'Y'; // 只搜索销售的产品
        $param['stocknumber'] = 1; // 过滤掉已售罄的商品
        if (!isset($condition['order'])) {
            $param['order'] = $orderMaps['s_t_desc'];
        } else {
            $param['order'] = $orderMaps[$condition['order']];
        }
        if (!isset($condition['page'])) {
            $param['page'] = 1;
        }
        
        if(isset($condition['viewNum'])) {
            $param['viewNum'] = $condition['viewNum'];
        }  else if (!isset($condition['limit'])) {
            $param['viewNum'] = 60;
        } else {
            $param['viewNum'] = $condition['limit'];
            unset($condition['limit']);
        }
        if (!empty($condition)) {
            $param += $condition;
        }
        return Yohobuy::httpBuildQuery(SearchData::getUrl(), $param);
    }
    
    /**
     * 并行调接口url获取(产品分类)
     * @param 
     */
    
    public static function getClassesUrl($condition)
    {
        $condition['sales'] = 'Y';  //在销售商品分类
        $condition['status'] = 1;   //上架商品分类
        $condition['stocknumber'] = 1;    //过滤掉已售罄
        return Yohobuy::httpBuildQuery(SearchData::getUrl('sort'), $condition);
    }
    
    /**
     * 并行调接口url获取(获取折扣区间)
     * @param 
     */
    
    public static function getDiscountUrl($param = array())
    {
        return Yohobuy::httpBuildQuery(SearchData::getUrl('discount'), $param);
    }
    
    /**
     * 并行调接口url获取(获取最新上架)
     */
    public static function getRecentShelveUrl($param = array())
    {
        return Yohobuy::httpBuildQuery(SearchData::getUrl('recent'), $param);
    }
    
     /**
      * 并行调接口url获取(获取品牌数据)
      */
    public static function getBrandUrl($customOptions = array())
    {
        // 构建必传参数
        $param = Yohobuy::param();
        $param['brand_id'] = $customOptions['brandId'];
        $param['uid'] = $customOptions['uid'];
        $param['method'] = 'app.brand.getBrandIntro';
        $param['client_secret'] = Sign::getSign($param);
        
        return Yohobuy::httpBuildQuery(Yohobuy::API_URL, $param);
    }
    


    /**
     * 获取品牌店铺接口地址
     * @param $param
     * @return string
     */
    public static function getShopUrl($param)
    {
        return Yohobuy::httpBuildQuery(SearchData::getUrl('shop'), $param);
    }
    
    /**
     * 获取品牌首页banner条
     * 
     * @return array 品牌banner条数据
     */
    public static function getBannerFormat($brand, $brandBanner) 
    {
        // 根据品牌Id获取品牌banner图
        $bannerImg = Helpers::getImageUrl($brandBanner, '', 150);
        $brandHome = Helpers::url('/product/index/brand', '', $brand['brand_domain']);
        $brandIntro = Helpers::url('/product/index/brandIntro', '', $brand['brand_domain']);
        $is_favorite = false;
        if(isset($brand['is_favorite'])){
            // 获取是否收藏
            if ($brand['is_favorite'] == 'Y') {
                $is_favorite = true;
            } elseif ($brand['is_favorite'] == 'N') {
                $is_favorite = false;
            }
        }
        
        // 返回banner数据
        return array(
                'bannerHeight' => '150',
                'coled' => $is_favorite,
                'banner' => $bannerImg,
                'brandHome' => $brandHome,
                'brandIntro' => $brandIntro
            );
    }

    /**
     * 搜索条件
     */
    public static function filter()
    {
        $result = array();
        //频道
        $result['channel'] = array();
        //性别
        $result['gender'] = self::gender(self::$filter);
        //品牌
        $result['brand'] = self::brand(self::$filter);
        //价格
        $result['price'] = self::price(self::$filter);
        $result['customPrice'] = self::customPrice(self::$filter);
        //颜色
        $result['color'] = self::color(self::$filter);
        //尺寸
        $result['size'] = self::size(self::$filter);
        //高级选项
        $result['seniorChose'] = self::seniorChose(self::$filter);
        return $result;
    }
    /**
     * 其他选项
     */
    public static function getOpts()
    {
        //排序方式
        $result['sortType'] = array( self::orderDefault(),self::orderTime(),self::orderPrice(),self::orderDiscount());
        //特殊:新品、特价、限量
        $result['checks'] = array(self::isnew(),self::specialoffer(),self::limited());
        //每行显示5个产品
        $result['fivePerLine'] = true;
        //每行显示6个产品
        $result['sixPerLineHref'] = true;
        //每页显示的数量
        $result['countPerPage'] = self::$options['viewNum'];
        //可选每页显示数量
        $result['pageCounts'] = self::viewNum();
        $result['curPage'] = self::$page;
        $result['pageCount'] = self::$pageTotal;
        $result['nextHref'] = ($next = self::next(self::$pageTotal, self::$filter)) ? $next['href'] : '';
        return $result;
    }
}