<?php
namespace wstmart\app\controller;
use wstmart\common\model\GoodsCats;
/**
 * ============================================================================
 * 商品控制器
 */
class Goods extends Base{
    protected $beforeActionList = [
          'checkAuth' => ['only'=>'history']
    ];
    public function tmp(){
    return;
        $orderNo = [100066190,100066186,100065840,100065770,100065490,100065420,100065405,100065276,100064963,100064930,100064926,100064915,100064510,100064322,100064274,100064226,100064215,100064090,100064053,100063762,100063655,100063493,100063482,100063471,100063460,100063375,100063224,100063106,100063095,100063084,100063062,100063040,100063036,100063025,100063014,100063003,100062992,100062815,100066422,100066411,100066396,100066245];
        foreach ($orderNo as &$key) {
            echo $key;
            dump(model('OrderRefunds')->byRefund($key));
        }
    }
	/**
	 * 商品主页
	 */
	public function detail(){
        
		$m = model('goods');
        //获取商品id mark 20180323
        $goods_id = input('goodsId/d');
        $goods = $m->getBySale($goods_id);
        hook('mobileControllerGoodsIndex',['getParams'=>input()]);
        // 找不到商品记录
        if(empty($goods)) exit(jsonReturn("此商品已下架或被删除!".$goods_id, -22));
        //记录用户浏览商品
        $userId = (int)session('WST_USER.userId');
        if($userId){
            $data['userId']= $userId;
            $data['goodsId']=$goods['goodsId'];
            $data['path']='3';
            $data['create_time']=time();
            $result=db('page_view')->insert($data);
        }
        $goods['goodsDesc']=htmlspecialchars_decode($goods['goodsDesc']);
        $rule = '/<img src="\/(upload.*?)"/';
        preg_match_all($rule, $goods['goodsDesc'], $images);

        foreach($images[0] as $k=>$v){
            $goods['goodsDesc'] = str_replace('/'.$images[1][$k], '__ROOT__/'.WSTConf("CONF.goodsLogo") . "\"  data-echo=\"__ROOT__/".WSTImg($images[1][$k],0), $goods['goodsDesc']);
        }
        if(!empty($goods)){
            // $history = cookie("wx_history_goods");
            // $history = is_array($history)?$history:[];
            // array_unshift($history, (string)$goods['goodsId']);
            // $history = array_values(array_unique($history));
            // if(!empty($history)){
            //     cookie("wx_history_goods",$history,25920000);
            // }
                        
            $goods['imgcount'] =  count($goods['gallery']);
            //$goods['imgwidth'] = 'width:'.$goods['imgcount'].'00%';
        }
        //添加注册推荐人 mark 20180323
        $goods['goods_url'] = url('mgoods-'.$goods_id.'.html','pName='.session('WST_USER.loginName'),'',true);
        $goods['goodsCount'] = $m->getGoodsCount($goods['shopId']);//全部商品数
        $goods['shopAccreds'] = model('shops')->shopAccreds($goods['shopId']);//店铺认证      
        $goods['newGoodsCount'] = $m->getNewGoodsCount($goods['shopId']);//上新数
        $goods['favoritesShopsNum'] = model('favorites')->getFavoritesShopsNum($goods['shopId']);//关注数
        $goods['isFavorites'] = 0;//未关注该商品
        if($userId){
            $isFavorites = model('favorites')->isGetFavorites($goods['goodsId'],$userId);
            if($isFavorites){
                $goods['isFavorites'] = 1;//已关注该商品
            }
        }
        $couponList = $this->getCouponList(0);
        if(isset($couponList['data'])){
            $goods['couponList'] = $couponList['data'];//优惠券列表
        }else{
            $goods['couponList'] = [];//优惠券列表
        }

        $goods['promotionList'] = $this->getPromotionList($goods['shopId'], $goods['goodsId'],0);//获取可用的满减活动
        $goods['oneAppraises'] = model('goods_appraises')->getOneAppraises($goods['goodsId']);//获取一个评论  
         
        $goods['showWhsle'] = 0;//是否显示批发价
        // $hyhlm_id = session('WST_USER.hyhlm_id');//联盟ID
        // if($hyhlm_id){
        //     $lm_info = getLMUserByID($hyhlm_id,'u_level');
        //     if($lm_info['u_level'] >= 1){
        //         $goods['showWhsle'] = 1;
        //     }
        // }
       // hook('afterGetGoods',['params'=>&$goods]);
        
        //dump($goods);die;
        //exit(json_encode($goods));
         // dump(hook('mobileDocumentGoodsPropDetail'));
         //    dump(hook('mobileDocumentGoodsPromotionDetail',['goods'=>$goods]));
         //die;
        $rsv = jsonReturn('', 1,$goods);
     
        exit($rsv);
	}
    function gbk_to_utf8($data) {
        if( is_array($data) ) {
            foreach ($data as $k => $v) {
                if ( is_array($v) ) {
                    $data[$k] = $this->gbk_to_utf8($v);
                } else {
                    $data[$k] = iconv('GBK', 'UTF-8//IGNORE', $v); 
                }
            }
            return $data;
        } else {
            $data = iconv('GBK', 'UTF-8//IGNORE', $data);
            return $data;
        }
    }
    /**
     * 获取优惠券列表
     * @param  integer $returnJson [是否返回json数据]
     * @return [type]              [description]
     */
    public function getCouponList($returnJson = 1){
    	return;
        $m = new \addons\coupon\model\Coupons();
        $data = $m->getCouponsByGoods();
        if($returnJson  == 1){
          exit(json_encode($data));
        }else{
          return $data;
        }
    }
    /**
     * 获取满就送列表
     * @param  [type]  $shopId     [商铺ID]
     * @param  [type]  $goodsId    [商品ID]
     * @param  integer $returnJson [是否返回json数据]
     * @return [type]              [description]
     */
    public function getPromotionList($shopId=0,$goodsId=0,$returnJson = 1){
    	return;
        $shopId = ($shopId==0)?(int)input('shopId'):$shopId;
        $goodsId = ($goodsId==0)?(int)input('goodsId'):$goodsId;
        $rm = new \addons\reward\model\Rewards(); 
        $data = $rm->getAvailableRewards($shopId, $goodsId);
        if($returnJson  == 1){
          exit(json_encode("",1,$data));
        }else{
          return $data;
        }
    }
	/**
     * 商品列表
     */
    public function lists(){
    	$this->assign("keyword", input('keyword'));
    	$this->assign("catId", input('catId/d'));
    	$this->assign("brandId", input('brandId/d'));
    	return $this->fetch('goods_list');
    }
    /**
     * 获取列表
     */
    public function pageQuery(){
    	$m = model('goods');
    	$gc = new GoodsCats();
    	$catId = (int)input('catId');
    	if($catId>0){
    		$goodsCatIds = $gc->getParentIs($catId);
    	}else{
    		$goodsCatIds = [];
    	}
    	$from = (int)input("from", 0);
        $scale = 0;
    	switch ($from){
            case 1:
                $scale = dataConf('discountRateGtToShopping');
                break;
            case 2:
                $scale = dataConf('discountRateGtToHelp');
                break;
            case 3:
                $scale = dataConf('discountRateGtToHelpShopping');
                break;
        }
        $_where['discountRate'] = [">=", $scale];
    	$rs = $m->pageQuery($goodsCatIds, $_where);
    	foreach ($rs['Rows'] as $key =>$v){
    		$rs['Rows'][$key]['goodsImg'] = WSTImg($v['goodsImg'],2);
    	}
        // `券`标签
        hook('afterQueryGoods',['page'=>&$rs]);
    	exit(jsonReturn("", 1,$rs));
    }

    /**
    * 浏览历史页面
    */
    public function history(){
        return $this->fetch('users/history/list');
    }
    /**
    * 获取浏览历史
    */
    public function historyQuery(){
        $rs = model('goods')->historyQuery();
        if(!empty($rs)){
	        foreach($rs['Rows'] as $k=>$v){
	            $rs['Rows'][$k]['goodsImg'] = WSTImg($v['goodsImg'],3);
	        }
        }
        return $rs;
    }
}