<?php
/**商品
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Mobile\Controller;
class GoodsController extends BaseController {
    public function _initialize(){
        parent::_initialize();
    }
    public function index($type=0) {
        $param=I('param.');
        if(!empty($param['keyword'])){//搜索历史
	        $history_num=5;
	        $value=session('search_history');
	        krsort($value);
	        if(!in_array($param['keyword'],$value)){
		        if(count($value)>=$history_num)array_shift($value);
		        $value[]=$param['keyword'];
		        $value=array_filter(array_unique($value));
		        session("search_history",$value,3600*6);
	        }
	        $title=$param['keyword'];
        }
        $paramm=array();
        if(empty($param['json_param'])) {
            $paramm=$param;
            $this->assign('json_param', json_encode($param));
        }
        else {
            $json_param=json_decode(htmlspecialchars_decode($param['json_param']),true);
            $paramm=array_merge($json_param,$param);
            $this->assign('json_param', $param['json_param']);
        }
        $data=D("Goods")->get_goods_index($paramm);
        if($type==1)return $data;
        if($param['cat_id'])$title=$data['cate_name'];
        $this->assign($param);
        $this->assign($data);
        $list_html=$this->fetch('goods_list');
        $this->assign('list_html',$list_html);
		$before_title=$title?$title:'商品列表';
//		$this->assign('before_title',$before_title);
        $this->assign('page_title',$before_title);
        /*seo开始*/
        $seodata=D('Common/Goods')->format_listseotile($param['brand_id'],$param['cat_id']);
        /*seo结束*/
        $this->assign($seodata);
		$this->display();
	}
    public function get_goods_list(){
        $return['status']=0;
        $data=$this->index(1);
        if(empty($data['goods_list']['list']))$this->ajaxReturn($return);
        $return['status']=1;
        $this->assign($data);
        $list_html=$this->fetch('goods_list');
        $return['data']=$list_html;
        $this->ajaxReturn($return);
    }

    /**
     * 商品详情页
     */
    public function goods_cont(){
        $member_info=session('member_info');
        $this->judge();
        $goods_id=I('id');
        goods_footprint(MID,$goods_id);
        $shop_id=get_wxsmall_shop_id();
        if($shop_id){
            $shop_name=idtoname($shop_id,'Shops');
            $this->assign('shop_name',$shop_name);
        }
        $data=D("Goods")->getmobile_shops_goodscontent($goods_id,$shop_id);
  
        // print_r($data['promat_info']);
        // print_r($data['goods_info']);die;
        // zjn 19-1-18
        $lshop_id=cookie("lshop_id");
        if($lshop_id){
            $re_data=array();
            $re_data=is_sanji(MID,$data['goods_info']);
            $ushop_id=intval(idtoname(MID,'LittleShop','id','uid',false));
            if($lshop_id==$ushop_id){
                $re_data['is_show']=1;
            }else{
                $re_data['is_show']=0;
            }
            // $re_data['is_show']=intval($lshop_id);
            $this->assign('re_data',$re_data);
            $this->assign('lshop_id',$lshop_id);
        }
        // 3-18 zjn
        $param=array();$param['id']=$goods_id;
        $recommend=D('Wxsmall/Takeout')->recommend($param); //猜你喜欢
        // print_r($recommend);die;
        $this->assign('recommend',$recommend);
        if($data['goods_info']['service_ids']){
            $reds=array();
            $reds['id'] = array('IN',$data['goods_info']['service_ids']);
            $data['goods_info']['goods_service']=M('GoodsService')->where($reds)->field(true)->select();
        }
        // zjn 3-30
        //获取商品基本信息
        $price_info=D("Common/PromotExt")->get_fight($goods_id);
        if($price_info['status'] && 1<2){//拼团
            if($price_info['data']['remarks']){
                $goods_info['pt_remarks']=format_price($price_info['data']['remarks']);
                /*
                 * 6-28 fk 
                 */
                $goods_info['pt_group_num']=$member_info['rank_id']<$price_info['data']['user_rank']?0:$price_info['data']['group_number'];
                //$goods_info['pt_group_num']=$price_info['data']['group_number'];
                $goods_info['pt_og_count']=$price_info['data']['og_count'];
            }
        }
        $this->assign('goods_pt_info',$goods_info);
        // ------end--------
        // end------
        // echo "<pre>";print_r($data);exit;
        $title = $data['goods_info']['goods_name'];
        $map=array();
        $map['goods_id']=$goods_id;
        $content=M("GoodsContent")->where($map)->field('content,seodescription')->find();
        $description = $data['goods_info']['goods_name'];
        if($content['seodescription']){
            $description=strip_tags(h($content['seodescription']));
        }elseif($content['content']){
            $description=strip_tags(h($content['content']));
        }
        $goods_img = $data['goods_imgs'][0]['goods_img'];
        $share_url=U('Mobile/Goods/goods_cont',array('id'=>$goods_id,'eid'=>MID),true,true);
        //jxr start 2019.1.19
        intval(idtoname(MID,'Member','user_shop','id',false));
        $lmap['shop_id']=$lshop_id;
        $lmap['goods_id']=$goods_id;
        $lg_info=M('LittleShopGoods')->where($lmap)->find();
        $this->assign('lg_info',$lg_info);
        //jxr end 2019.1.19
        $url=U('Article/article_cont',array('id'=>$goods_id,'type'=>'goods','eid'=>MID));
        $this->assign($data);
        $this->assign('shop_id',$shop_id);
        $this->assign('title',$title);
        $this->assign('description',$description);
        $this->assign('goods_img',$goods_img);
        $this->assign('share_url',$share_url);
        $this->assign('url',$url);
        $this->assign('goods_id',$goods_id);
        $this->assign('content',$content['content']);	//jxr
        $this->assign('before_title',$data['goods_info']['goods_name']);
        $seodata=D('Common/Goods')->format_contseotitle($data['goods_info']);
        $this->assign($seodata);
        $this->display();
    }
    /**
     * 服务列表页
     */
	public function service_list($type=0){
		$shop_id = get_wxsmall_shop_id();
		$package = I('package');
		$p=I('page')?I('page'):1;
		if(!$shop_id)$shop_id = 1;
		$map = array();$map['id'] = $shop_id;
		$status = M('Shops')->where($map)->getField('status');
		if($status != 1)$this->error('该门店已关闭');
		if($package == 1){
			$list = D('Common/Goods')->service_list($shop_id,20,$p,6);
		}else{
			$list = D('Common/Goods')->service_list($shop_id,20,$p,4);
		}
		if($type == 1)return $list;
		$this->assign('list',$list);
		if($package == 1){
			$list_html=$this->fetch('package_list_index');
		}else{
			$list_html=$this->fetch('service_list_index');
		}
		$this->assign('list_html',$list_html);
		$this->assign('shop_id',$shop_id);
		$this->assign('page',$p);
        $title = "服务";
        $description = '服务' . '_' . C('WEB_SITE_TITLE');
        $share_url=U('Mobile/Goods/service_list',array('eid'=>MID));
        $this->assign('title',$title);
        $this->assign('description',$description);
        $this->assign('share_url',$share_url);
		if($package == 1){
			$this->assign('package',1);
			$this->display('package_list');
		}else{
			$this->display();
		}
	}
    public function get_service_list() {
        $return['status']=0;
		$package = I('package');
        $data=$this->service_list(1);
        if(empty($data['list']))$this->ajaxReturn($return);
        $return['status']=1;
        $this->assign('list',$data);
		if($package == 1){
			$list_html=$this->fetch('package_list_index');
		}else{
			$list_html=$this->fetch('service_list_index');
		}
        $return['data']=$list_html;
        $this->ajaxReturn($return);
    }
	/**
     * 服务详情页
     */
    public function service_cont(){
        $goods_id=I('id');
		goods_footprint(MID,$goods_id);
		$goodsdata=D('Common/Goods')->service_cont($goods_id,4);
		$this->assign($goodsdata['shop_info']);
		$this->assign('url',$goodsdata['url']);
		
		$title = $goodsdata['data']['goods_name'];
		$description = '服务分享';
		$goods_img = $goodsdata['data']['img'];
        $share_url=U('Mobile/Goods/service_cont',array('id'=>$goods_id,'eid'=>MID));
		$this->assign($data);
		$this->assign('title',$title);
		$this->assign('description',$description);
		$this->assign('goods_img',$goods_img);
		$this->assign('share_url',$share_url);
		
		if($goodsdata['data']['service_spec']){
			$goodsdata['data']['service_spec_info'] = json_decode($goodsdata['data']['service_spec'],true);
			unset($goodsdata['data']['service_spec']);
		}
		$goodsdata['data']['speac_count'] = count($goodsdata['data']['service_spec_info']);
		
		$this->assign('before_title',$goodsdata['data']['goods_name']);
        $seodata=D('Common/Goods')->format_contseotitle($goodsdata['data']);
		
		// echo "<pre>";print_r($goodsdata['data']);exit;
		
		//服务标签和评论
		$return=D('Dp')->get_dp_service($goods_id);
		if(!empty($return['status'])){$this->assign($return);}
		$this->assign('goods_info',$goodsdata['data']);
        $this->assign('hot_service',$goodsdata['hot_service']);
        $this->assign($seodata);
		$this->assign('goods_id',$goods_id);
        $this->display();
    }
	/**
     * 套餐详情页
     */
    public function package_cont(){
        $goods_id=I('id');
		goods_footprint(MID,$goods_id);
		$goodsdata=D('Common/Goods')->service_cont($goods_id,6);
		$this->assign($goodsdata['shop_info']);
		$this->assign('service_infos',$goodsdata['service_infos']);
		$this->assign('goods_info',$goodsdata['data']);
		$this->assign('url',$goodsdata['url']);
		$this->assign('before_title',$goodsdata['data']['goods_name']);
        $seodata=D('Common/Goods')->format_contseotitle($goodsdata['data']);
        $this->assign('hot_service',$goodsdata['hot_service']);
		$this->assign('goods_id',$goods_id);
        $this->assign($seodata);
        $this->display();
    }
	public function package_shops(){
		$id = I('id');
		$map['id'] = $id;
		$shop_ids = M('Goods')->where($map)->getField('shop_ids');

		if($shop_ids){
			$shopids = implode(',',array_filter(explode(',',$shop_ids)));
			$count = count(array_filter(explode(',',$shop_ids)));
			$shop_list= getShopid($shopids,1,$count);
		}else{
			$shop_list= getShopid('',1,5);
		}

		$this->assign('shop_list',$shop_list);
		$this->display();
	}

    /**
     * 加入购物车
     */
    public function addcart(){
        $goods_id=I('goods_id');
        $goods_attr=I('goods_attr');
        $number=I('number');
        $name=I('name');
        $price=I('money');
        $act=I('act');
        $type=I('type');
		
        /*if(cookie('dingwei_address')){
            $address_info = cookie('dingwei_address');//获取定位信息
        }elseif(session('dingwei_address')){
            $address_info = session('dingwei_address');
        }
        if (empty($address_info)) {
            $return['status'] = 3;
            $return['msg'] = '请选择配送地区';
            $this->ajaxReturn($return);
        }*/
        $return = array();
        $model=D("Common/Cart");
        $return=$model->add_carts($goods_id,$goods_attr,$number,$name,$act,$type);
		// $param=array();
		// $param['goods_id']=$goods_id;
		// $param['spec']=$goods_attr;
		// $param['name']=$name;
		// $param['num']=$number;
		// $param['is_add']=I("is_add");
		// $return=D("Common/Takeout")->add_cart_item($param);
        $return['num'] = cart_show();
        $this->ajaxReturn($return);
    }
    /**
   *关注收藏
   */
    public function favorite(){
        $goods_id=I('id');
        $type=I('type');
        $is_on=I('is_on');
        $data=D('Common/Goods')->favorite($goods_id,$type,$is_on);
        $this->ajaxReturn($data);
    }
    //判断是否收藏
    public function ajax_is_collect(){
        $goods_id=I('goods_id');
        $type=I('type');
        $is_collect = D('Common/Goods')->is_collect($goods_id,$type);
        $data['is_collect'] = $is_collect;
        $this->ajaxReturn($data);
    }
    //会员领取优惠券
    public function get_ecv(){
        $bouns_id=I('id');
        $data=D("Common/Promot")->member_get_bonus($bouns_id);
        $this->ajaxReturn($data);
    }

    /**
     * 立即购买
     */
    public function buy_now(){
        $param=$postdata=array();
        $param=$postdata=I("param.");
		$shop_id = get_wxsmall_shop_id();
        $goods_id=$param['goods_id'];
        $param['goods_attr']=$param['goods_attr']?$param['goods_attr']:0;
        if($param['goods_attr']){
            $goods_attr = serialize($goodsattr_info);
            $map = array();
            $map['attr_key'] = $val['spec_format']['key'];
            $map['goods_id'] = $val['id'];
            $price_info['goods_price'] = M('GoodsAttrStock')->where($map)->getField('attr_price');
            $price_info['price_type'] = 6;
            // $price_info=D('Common/Takeout')->get_min_price($shop_id,$val['id'],'',$param['goods_attr']);//获取商品最终价格
        }else{
            $price_info=D('Common/Takeout')->get_min_price($shop_id,$val['id']);//获取商品最终价格
        }
        if(empty($param['uid'])){$memberinfo=session('member_info');$param['uid']=$memberinfo['id'];}
        $uid=$param['uid'];


        $map = array();
        $map['id']=$goods_id;
        $goods_info=M('Goods')->where($map)->field('goods_name,goods_number,img,market_price,goods_sn,cat_id,promote_id,promote_price,promote_start_time,promote_end_time,sale_type,goods_number,sell_count,goods_max_number,goods_min_number,pt_id')->find();
        $return['status']=2;
        if($param['number']<=0){
            $return['msg'] = '请加入商品【'.$goods_info['goods_name'].'】数量';
            $this->ajaxReturn($return);
        }
        if($goods_info['sale_type']==1){//组合商品库存
            $goods_number = $this->get_group_goods_stock($goods_id,$shop_id);
            if($param['number']>$goods_number){
                $return['msg'] = $goods_info['goods_name'].'【库存不足，库存量'.$goods_number.'】';
                $this->ajaxReturn($return);
            }
        }else{
           /* if($goods_info['goods_number']>=0){
                if($param['number']>$goods_info['goods_number']){
                    $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                    $this->ajaxReturn($return);
                }
            }*/
        }
        if($goods_info['promote_id']){
            $map=array();
            $map['id']=$goods_info['promote_id'];
            $map['start_time'] = array('elt',NOW_TIME);
            $map['end_time'] = array('egt',NOW_TIME);
            $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time')->find();
            // 查询该会员在此活动下已购数量
            $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$goods_id);
            $p_num=$param['number']+$p_num;
            if($goods_info['goods_min_number']>0 && $p_num > $goods_info['goods_min_number']){
                $return['msg'] = "本活动单人限量".$goods_info['goods_min_number']."您已超过单人限量";
                $this->ajaxReturn($return);
            }
            //总限量
            $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$goods_id,1);
            $p_num=$param['number']+$p_num;
            if($goods_info['goods_max_number']>=0 && $p_num>$goods_info['goods_max_number']){
                $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                $this->ajaxReturn($return);
            }
        }else if($goods_info['pt_id']){
            $map=array();
            $map['id']=$goods_info['pt_id'];
            $map['start_time'] = array('elt',NOW_TIME);
            $map['end_time'] = array('egt',NOW_TIME);
            $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time,user_rank')->find();
                 // 拼团限制等级
            if($user_info['rank_id']<$promote_info['user_rank']){
                 $return['msg'] = "数据错误";
                $this->ajaxReturn($return);
            }

            // 查询该会员在此活动下已购数量
            $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$goods_id);
            $p_num=$param['number']+$p_num;
            if($promote_info['buy_limit']>0 && $p_num > $promote_info['buy_limit']){
                $return['msg'] = "本拼团单人限量".$promote_info['buy_limit']."您已超过单人限量";
                $this->ajaxReturn($return);
            }
            //总限量
            $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$goods_id,1);
            $p_num=$param['number']+$p_num;
            if($goods_info['goods_max_number']>=0 && $p_num>$goods_info['goods_max_number']){
                $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                $this->ajaxReturn($return);
            }
        }
		if($postdata['type'] == 6 || $postdata['type'] == 14){
			$postdata['status'] = 1;
			$is_num = D("Common/Cart")->shopgoodsstock($postdata['goods_id'],$shop_id,$postdata['goods_attr']);
			if($is_num['goods_number'] <= 0){
                $postdata['status'] = 2;
				$postdata['msg'] = '库存不足！';
			}
            //验证是否选择属性
            $goods_attr_map = array();
            $goods_attr_map['g.goods_id'] = $postdata['goods_id'];
            $goods_attr_map['ga.type'] = array('neq', 'text');
            $map_attr['goods_id']=$postdata['goods_id'];
            $stockcount = M('GoodsAttrStock')->where($map_attr)->count();
            if($stockcount>0) {
                $goods_attrs = M("GoodsAttr")->alias('g')->distinct("g.attr_id")->where($goods_attr_map)->JOIN('LEFT JOIN __GOODS_ATTRIBUTE__ ga ON g.attr_id=ga.id')->field('attr_id')->select();
                if (!empty($goods_attrs)) {
                    $attrs=array();
                    if($postdata['goods_attr'])$attrs = explode("_", $postdata['goods_attr']);
                    if (count($attrs) != count($goods_attrs)) {
                        $postdata['msg'] = '请选择商品规格';
                        $postdata['app_data'] = 'open_attr';  //app返回直接加载属性页面
                        $postdata['status'] = 2;
                    }
                }
            }
		}
		if($postdata['type'] == 11){
			$return = D("Common/OrderInfo")->check_service($postdata['goods_id'],$shop_id);
			if($return['status'] == 0){
				$postdata['status'] = 0;
				$postdata['msg'] = $return['msg'];
			}else{
				$postdata['status'] = 1;
			}
		}
        if($postdata['type'] == 3){//积分商品
            $postdata['status'] = 1;
            $is_num = D("Common/Cart")->shopgoodsstock($postdata['goods_id'],$shop_id);
            if($is_num['goods_number'] <= 0){
                $postdata['status'] = 0;
                $postdata['msg'] = '库存不足！';
            }
            if(empty($postdata['integra'])){
                $postdata['status'] = 0;
                $postdata['app_data'] = 'open_attr';
                $postdata['msg'] = '请选择付款方式';
            }
        }
        $this->ajaxReturn($postdata);
    }

    /**
     * 评论
     */
	public function service_comment(){
        $goods_id=I('id');
		//服务标签和评论
		if($goods_id){
			$return=D('Dp')->get_dp_service($goods_id);
			if(!empty($return['status'])){
				$this->assign($return);
			}
		}
        $this->assign('tplseo_title', '评论' . '_' . C('WEB_SITE_TITLE'));
        $this->assign('page_title', '评论');
        $this->display('goods_comment');
    }
    /*public function goods_comment(){
        $goods_id=I('id');
		$commlist = D('Dp')->get_goods($goods_id);
		$dp_count=count($commlist['dp_id']);
        $this->assign($commlist);
        $this->assign('tplseo_title', '评论' . '_' . C('WEB_SITE_TITLE'));
        $this->assign('page_title', '评论');
        $this->display();
    }*/
	
	// new评论
	public function goods_comment($is_ajax = 0){
		$postdata=I('param.');
        $goods_id=$postdata['id'];
		$commlist = D('Dp')->get_goods($postdata,$goods_id);
		// echo "<pre>";print_r($commlist);exit;
		if ($is_ajax == 1) return $commlist;
        $this->assign($commlist);
        $this->assign('goods_id',$goods_id);
        $this->assign('tplseo_title', '评论' . '_' . C('WEB_SITE_TITLE'));
        $this->assign('page_title', '评论');
        $this->display();
    }
	public function get_comment_list(){
        $return['status'] = 0;
        $data = $this->goods_comment(1);
        if (empty($data['dp_list'])) $this->ajaxReturn($return);
        $return['status'] = 1;
        $this->assign($data);
        $list_html = $this->fetch('comment_list');
        $return['data'] = $list_html;
        $return['show'] = $data['show'];
        $this->ajaxReturn($return);
    }
	public function get_tag_list(){
		$return['status'] = 0;
		$postdata=I('param.');
		$tag_name = $postdata['tag_name'];
		$goods_id = $postdata['goods_id'];
		$is_sp = empty($postdata['is_sp'])?1:$postdata['is_sp'];
		$data = D('Dp')->get_tag_link_list($postdata,$tag_name,$goods_id,$is_sp);
		if (empty($data['dp_list'])) $this->ajaxReturn($return);
        $return['status'] = 1;
		$this->assign($data);
        $list_html = $this->fetch('comment_list');
		$return['data'] = $list_html;
        $return['show'] = $data['show'];
        $this->ajaxReturn($return);
	}
	
	/**
     * 服务列表页
     */
	public function services_list($type=0){
		$postdata = I('post.');
		$package = I('package');
		$p=I('page')?I('page'):1;
		if($postdata['sell_count'] && $postdata['price']){
			$order='sell_count desc,shop_price desc';
		}else if($postdata['sell_count'] && !$postdata['price']){
			$order='sell_count desc';
		}else if(!$postdata['sell_count'] && $postdata['price']){
			$order='shop_price desc';
		}
		if($postdata['catid'])$map['cat_id'] = $postdata['catid'];
		
		if($package == 1){
			$map['goods_type'] = 6;
		}else{
			$map['goods_type'] = 4;
		}
		$map['status'] = 1;
		$map['is_delete'] = 0;
		$map['publish_wait'] = 1;
		if($postdata['shopid']){
			$shop_ids = ','.$postdata['shopid'].',';
			$map['_string'] = "shop_ids like '%".$shop_ids."%' OR shop_ids='0'";
		}
		$list = D('Common/Goods')->services_list($map,$order,20,$p);
		if($type == 1){$list['package']=$package;return $list;}
		$this->assign('list',$list);
		if($package == 1){
			$list_html=$this->fetch('packages_list_index');
		}else{
			$list_html=$this->fetch('service_list_index');
		}
		$this->assign('list_html',$list_html);
		$this->assign('page',$p);
		$this->assign($postdata);
		//所有门店
		$shopdata = M('Shops')->where('status=1')->field('id,name')->select();
		$this->assign('shopdata',$shopdata);
		//服务分类
		$serviceCat = M('ServiceCategory')->where('status=1')->field('id,name')->select();
		$this->assign('serviceCat',$serviceCat);
		if($package == 1){
			$this->assign('package',1);
			$this->display('packages_list');
		}else{
			$this->display();
		}
	}
	public function get_services_list() {
		$package = I('package');
        $return['status']=0;
        $data=$this->services_list(1);
        if(empty($data['list']))$this->ajaxReturn($return);
        $return['status']=1;
        $this->assign('list',$data);
		if($package==1){
			$list_html=$this->fetch('packages_list_index');
		}else{
			$list_html=$this->fetch('service_list_index');
		}
        $return['data']=$list_html;
        $this->ajaxReturn($return);
    }
}