<?php
/**商品
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <570035208@qq.cn>
 */
namespace Uapp\Controller;
class GoodsController extends BaseController {
    public function _initialize(){
        parent::_initialize ();
    }
	public function index() {
        GLOBAL $GoodsCategory;
        if (empty($GoodsCategory)) $GoodsCategory = getcache('GoodsCategory');
        $param=I('param.');
        $returns['status'] = 2;
        $return['goods_category']=$return['cate_order']=$return['filter_item']['attr_list']=$return['filter_item']['labels']=$return['filter_item']['brand_list']=array();
        foreach($GoodsCategory as $k=>$v){
            $return['goods_category'][$v['pid']][$k]['id']=$v['id'];
            $return['goods_category'][$v['pid']][$k]['name']=$v['name'];
            $return['goods_category'][$v['pid']][$k]['pid']=$v['pid'];
            $return['goods_category_item'][$k]['name']=$v['name'];
            $return['goods_category_item'][$k]['pid']=$v['pid'];
            $type_id=get_cate_type($k);//类型ID
            $type_attr=get_type_attr($type_id,$k);
            if($type_attr) {
                foreach($type_attr as $kk=>$vv){
                    $return['filter_item']['attr_list'][$k][$kk]['id'] = $vv['id'];
                    $return['filter_item']['attr_list'][$k][$kk]['name'] = $vv['name'];
                    $return['filter_item']['attr_list'][$k][$kk]['options'] = $vv['options'];
                }
            }
        }
        $cate_order=D('Common/Goods')->cate_order();
        $i = 0;
        foreach($cate_order as $ke=>$va){
            if($va){
                $return['cate_order'][$i]['name']=$va['name'];
                $return['cate_order'][$i]['type']=$ke;
            }
            $i++;
        }
       
        $labels=get_goodslabel_list($param);
        foreach($labels as $key=>$val){
            if($val) {
                $return['filter_item']['labels'][$key]['id'] = $val['id'];
                $return['filter_item']['labels'][$key]['label_name'] = $val['label_name'];
            }
        }
        $brand_list=brand_list();
        foreach($brand_list as $keyy=>$vall){
            if($vall) {
                $return['filter_item']['brand_list'][$keyy]['id'] = $vall['id'];
                $return['filter_item']['brand_list'][$keyy]['brand_name'] = $vall['brand_name'];
            }
        }
        $price_list = get_price_map($param['cat_id'],$param['price']);
        $pricelist=empty($price_list['pricelist'])?array():$price_list['pricelist'];
        $return['filter_item']['pricelist']=$pricelist;
        if($return['filter_item']){
            $returns['status'] = 1;
            $returns['data'] = $return;
        }else{
            $returns['msg'] = '未获取到数据';
        }
        $this->ajaxReturn($returns);
	}

    //911新加获取会员收货地址
    public function get_memberadds(){
        $return['status'] = 1;
        $uid = I('uid');

        //911新加
        $madd=array();
        $madd['status']=1;
        $madd['uid']=$uid;
        $madds = M('MemberAddress')->where($madd)->field(true)->find();
        if(empty($madds)){
            unset($madd['status']);
            $madds = M('MemberAddress')->where($madd)->field(true)->order('id desc')->find();

        }

       
        if($madds){

            $madds['province'] = $madds['province'];
            $madds['city'] = $madds['city'];
            $madds['district'] = $madds['district'];
            $madds['p_name'] = idtoname($madds['province'],'Area','name','id',false);
            $madds['c_name'] = idtoname($madds['city'],'Area','name','id',false);
            $madds['d_name'] = idtoname($madds['district'],'Area','name','id',false);
            $madds['address'] = $madds['address'];
            $return['madds'] = $madds;
        }else{
            $madds['province'] = 6;
            $madds['city'] = 130;
            $madds['district'] = 542;
            $madds['p_name'] = '河北省';
            $madds['c_name'] = '石家庄';
            $madds['d_name'] = '桥西区';
            $return['madds'] = $madds;
        }

        $this->ajaxReturn($return);
        //end
    }
    //end

    /**
     * $param=array(
            ['page']        页数（int）
            ['keyword']     关键字（str）
            ['cat_id']      分类id（int）
            ['brand_id']    品牌id（int）
            ['price']       价格分级（float）
            ['order_name']  排序名称（str）
            ['label_标签id']=标签id     标签（int）
            ['label_标签id+1']=标签id+1     标签（int）
            ['p属性id']=属性id     属性（int）
            ['p属性id+1']=属性id+1     属性（int）
            ['is_self']     是否自营（int）1是0否
            ['is_shipping'] 是否商家包邮（int）1是0否
            ['is_have']     是否有货（int）1是0否
       )
     */
    public function lists(){
        $param=I('param.');
        $root=array();
        $map=array();
        $join='';
        $return['status'] = 2;
        if(empty($param['page']))$param['page']=1;
        $p=$param['page'];
        if(!empty($param['keyword']))$map['goods_name']=array('like','%'.$param['keyword'].'%');
        if(!empty($param['cat_id']))$map['cat_id']=$param['cat_id'];
        if(!empty($param['brand_id']))$map['brand_id']=$param['brand_id'];
        //是否为自营
        if(!empty($param['is_self'])&& $param['is_self'] == 1)$map['shop_id']=0;
        //是否是商家包邮
        if(!empty($param['is_shipping'])&& $param['is_shipping'] == 1)$map['is_shipping']=1;
        //仅显示有货
        if(!empty($param['is_have'])&& $param['is_have'] == 1)$map['goods_number']=array('gt',0);
        /*价格分级开始*/
        $price_list = get_price_map($map['cat_id'],$param['price']);
        if(!empty($price_list['shop_price']))$map['shop_price']=$price_list['shop_price'];
        /*价格分级结束*/
        /*属性筛选开始*/
        $type_id=get_cate_type($param['cat_id']);//类型ID
        $attr_list=D('Common/GoodsAttr')->get_attr($param,$type_id);
        if(!empty($attr_list)){
            $map['_string']=$attr_list['_string'];
        }
        /*属性筛选结束*/
        /*标签筛选开始*/
        $labels_map=D('Common/Goods')->get_label_map($param);
        //if(!empty($labels_map['map']))$map['id']=$labels_map['map']['id'];
        /*标签筛选结束*/

        /* 排序 */
        if($param[$param['order_name']]==1){$order_type='desc';}
        elseif($param[$param['order_name']]==2){$order_type='asc';}
        if(!empty($param['order_name'])&& $param['order_name']!='default' && $order_type)$order=$param['order_name'].' '.$order_type;
        $goods_list=D('Common/Goods')->get_goods_list(0,$map,$join,$order,$p);
        foreach($goods_list['list'] as $k=>$v){
            $goods_format[$k]['id'] = $v['id'];
            $goods_format[$k]['name'] = $v['goods_name'];
            $goods_format[$k]['img'] = thumb($v['img'],500,500);
            $goods_format[$k]['shop_price'] = $v['shop_price'];
            $goods_format[$k]['market_price'] = $v['market_price'];
            $goods_format[$k]['pre_id'] = $v['pre_id'];
            $goods_format[$k]['style'] = $v['type'];
            $goods_format[$k]['pt_id'] = $v['pt_id'];
            $goods_format[$k]['endtime'] = $v['endtime'];
            $goods_format[$k]['end_time'] = $v['end_time'];
        }
        if($goods_format){
            $return['data']=$goods_format;
            $return['status'] = 1;
        }else{
            $return['msg'] = '未获取到数据';
        }
        $this->ajaxReturn($return);
    }
    /**
     * 商品详情页
     */
    public function get_cont(){
        $goods_id=I('id');
        $return['status'] = 3;
		//分销商
		$uid = I('uid');
		$return['data']['is_fx'] = $uid>0?intval(is_fx($uid)):0;
        $goods_info = D("Common/Goods")->get_goods_item($goods_id);
       // print_r($goods_info);
        if($goods_info['status']==1){
            //商品相册
            $where['goods_id']=$goods_id;
            $goods_imgs = M("GoodsGallery")->where($where)->select();
            foreach($goods_imgs as $key=>$val){
                $goods_imgs[$key]['goods_img']=thumb($val['goods_img'],500,500);
            }
            if (empty($goods_imgs)) $goods_imgs[0]['goods_img'] =thumb($goods_info['data']['img'],500,500);
            $goods_info['data']['goods_imgs']=$goods_imgs;
            //店铺信息
            $shop_id=$goods_info['data']['shop_id'];
            if($shop_id){
                $shop_map['id']=$shop_id;
                $shop_info=M('Shops')->where($shop_map)->field('name,total_revenues,dp_count,contacts_phone,qq')->find();
                $g_map['shop_id']=$shop_id;
                $g_map['status']=1;
                $shop_info['goods_num']=M('Goods')->where($g_map)->count();
            }
            //获取商品最小价格
            $price_info=D("Common/Cart")->getminprice($goods_id);
           $goods_info['data']['price_info']=$price_info;
            $goods_info['data']['min_price']=$price_info['price'];
            if($price_info['type']==3){
                $goods_info['data']['price_type']='促销价';
            }elseif($price_info['type']==2){
                $goods_info['data']['price_type']='会员价';
            }
            //会员领取该商品的红包
            $ecv_list=D("Common/Promot")->goods_to_ticket($goods_id,$shop_id);
            $ticket=array();
            foreach($ecv_list['list'] as $key=>$val){
                if($val['is_get']==1){
                    if($key<=1){
                        $ticket[$key]=$val;
                    }
                }
            }
            //优惠活动
            $activelist=D("Common/Promot")->goods_to_promot($goods_id,1);
            $active_id=array();
            if($activelist['list']) {
                foreach ($activelist['list'] as $key => $v) {
                    $active_id[] = $v['id'];
                }
            }
            if($goods_info['promote_end_time']<NOW_TIME){
                $goods_info['promote_end_time']=0;
            }
            //评论列表
            $commlist = D("Common/GoodsAttr")->comment_list($goods_id);
            $m_map['id']=$commlist['info']['list'][0]['uid'];
            $commlist['info']['list'][0]['user_name']=M("Member")->where($m_map)->getField('username');
            //总评论个数
            $c_map['id']=$goods_id;
            $dp_count=M("goods")->where($c_map)->getField('dp_count');
            $return['data']['goods_info']=$goods_info['data'];
            $return['data']['shop_info']=$shop_info;
            $return['data']['ticket_info']=$ticket;
            $return['data']['activelist']=$activelist['count'];
            $return['data']['active_id']=$active_id[0]?$active_id[0]:0;
            if($active_id[0]>0){
                $return['data']['active_name']=idtoname($active_id[0],'PromotAct','act_name');
            }

            $return['data']['common_list']=$commlist['info']['list'][0];
            $return['data']['dp_count']=$dp_count;
            $userid = I('uid')?I('uid'):0;
            $return['data']['share_url']=geturl('Mobile/Goods/goods_cont',array('id'=>$goods_id,'eid'=>$userid),true,true);

            //判断是否收藏
            $is_collect=D("Common/Goods")->is_collect($goods_id,0);
            $return['data']['is_collect']=$is_collect;
            //判断是否有属性
            $attr = D("Common/GoodsAttr")->getattr($goods_id);
            $return['data']['attr']=$attr['newarr'];
             //猜你喜欢
            $param=array();$param['id']=$goods_id;
            $recommend=D('Wxsmall/Takeout')->recommend($param);
            $return['data']['recommend']=$recommend;
            // 3-18 zjn 服务
            $reds = array();
            if($goods_info['service_ids']){
                $reds['id'] = array('IN',$goods_info['service_ids']);
                $goods_info['goods_service']=M('GoodsService')->where($reds)->field(true)->select();
            }
            $return['status']=1;
        }else{
            $return['msg'] = $goods_info['msg'];
        }
        
        $this->ajaxReturn($return);
    }
    public function ticket(){
        $goods_id=I('id');
        $return['status'] = 2;
        $map['id']=$goods_id;
        $shop_id=M("Goods")->where($map)->getField('shop_id');
        $ecv_list=D("Common/Promot")->goods_to_ticket($goods_id,$shop_id);
        if($ecv_list){
            $return['status'] = 1;
            foreach($ecv_list['list'] as $key=>$val){
                if($val['use_end_date_format']){
                    if($val['use_start_date_format']){
                        $ecv_list['list'][$key]['ticket_time']=$val['use_start_date_format'].'-'.$val['use_end_date_format'];
                    }else{
                        $ecv_list['list'][$key]['ticket_time']='有效期至'.$val['use_end_date_format'];
                    }
                }else{
                    $ecv_list['list'][$key]['ticket_time']='无限';
                }
            }
            $return['data']=$ecv_list;
        }else{
            $return['msg']='未获取到数据';
        }
        $this->ajaxReturn($return);
    }
    /**
     * 会员领取优惠券
     */
    public function get_ecv(){
        $return['status']=3;
        $bouns_id=I('id');
        $data=D("Common/Promot")->member_get_bonus($bouns_id);
        if($data['status']==0){
            $return['msg']=$data['info'];
        }else{
            $return['status']=1;
            $return['msg']=$data['info'];
        }
        $this->ajaxReturn($return);
    }

    /**
     * 活动弹窗
     */
    public function activity(){
        $return['status']=2;
        $goods_id=I('id');
        $activelist=D("Common/Promot")->goods_to_promot($goods_id,1);
        if($activelist['list']){
            foreach($activelist['list'] as $key=>$val){
                if($val['act_type']==1){
                    $activelist['list'][$key]['activity_type']='满减';
                }else{
                    $activelist['list'][$key]['activity_type']='折扣';
                }
            }
            $return['data']=$activelist['list'];
            $return['status']=1;
        }else{
            $return['msg']='未获取到数据';
        }
        $this->ajaxReturn($return);
    }
    public function goods_attr(){
        $getdata = I('get.');
        $return['status']=2;
        $user_info=$this->checkuserauth();
        $shop_id=$user_info['HCshop']['bind_shop_id'];//追加当前会员匹配的门店
        $goods_id=I('id');
        if($goods_id){
            $data = D('Common/Takeout')->get_goods_info($goods_id,$shop_id);
            if(!$data['status']){
                $return['msg'] = $data['info'];
                $this->ajaxReturn($return);
            }
            
                  // echo "<pre>";print_r(json_decode($data['goods_info']['format_spec']['combinationprice']));exit;
            $return['goods_id'] = $goods_id;
            $return['format_market_price'] = $data['goods_info']['format_end_price'];
            $return['combination'] = json_decode($data['goods_info']['format_spec']['combination']);
            $return['combinationnum'] = $data['goods_info']['format_spec']['combinationnum'];
            $return['combinationprice'] = json_decode($data['goods_info']['format_spec']['combinationprice']);
            $return['combinationpricenum'] = $data['goods_info']['format_spec']['combinationpricenum'];
            if($data['goods_info']['format_spec']['newarr']){
                $return['status'] = 1;
                $html = "";
                foreach ($data['goods_info']['format_spec']['newarr'] as $key => $value) {
                    $html.= "<dl rel='".$key."'><dt>".$value['name']."</dt><dd>";
                    foreach ($value['options'] as $k => $v) {
                        $html.= "<span attr='".$v['id']."' ";
                        $html.= "onClick=\"init_choose(this)\" id=\"attr".$v['id']."\">".$v['optionsval']."</span>";
                    }
                    $html.="</dd></dl>";
                }
                $return['html'] = $html; 
                
                $sg_map = array();
                $sg_map['goods_id']=$goods_id;
                $sg_map['shop_id']=$shop_id;
                $sg_info=M('ShopsGoods')->where($sg_map)->getField('id');
                if(empty($sg_info)){$return['is_add'] = 0;}
                else{$return['is_add'] = 1;}
            }else{
                $return['status'] = 2;
                $return['msg'] = '无属性';
            }
        }else{
            $return['msg'] = '数据获取错误';
        }
        $this->ajaxReturn($return);
    }

    /**
     * 商品图文详情
     */
    public function goods_article(){
        $id=I('id');
        $type=I('type');
        $return=array('status'=>1);
       $info= D('Mobile/Article')->article_con($id,$type);
        if($info['status']==0){
            $return['data']=$this->format_content($info['content']['content']);
        }else{
            $return['status']=3;
            $return['msg']=$info['msg'];
        }
        $this->ajaxReturn($return);
    }


    /**
     * 加入购物车
     */
    public function addcart(){
        $return=array('status'=>1);
        $goods_id=I('id');
        $goods_attr=I('checkarrkey_str');
        $number=I('goodsnum');
        $name=I('checkarrkey_strname');
        $act=I('act');
        $type=0;
        $return['data']=I('get.');
        $anchor_room=I('anchor_room');
        if($anchor_room){
            $map['roomnumber']=$anchor_room;
            $anchor_id=M("LiveAnchor")->where($map)->getField('user_id');
        }
        $address_info = checkuseraddress();//获取定位信息
        if (empty($address_info)) {
            $return['status'] = 3;
            $return['msg'] = '请选择配送地区';
            $this->ajaxReturn($return);
        }
        $model=D("Common/Cart");
        $res=$model->add_carts($goods_id,$goods_attr,$number,$name,$act,$type,$anchor_id);
        // zjn 购物车商品
        $cart_num = D("Wxsmall/Takeout")->get_cart_total_info(I('uid'));
        $return['cart_num']=$cart_num['cart_num'];
        if($res['status']==0 || $res['status']==1){
            if($res['app_data']=='open_attr'){
                $return['data']='open_attr';
                $return['msg']=$res['msg'];
            }else{
                $return['msg']=$res['msg'];
            }
            $return['status']=3;

        }else{
            $return['status']=1;
            $return['msg']=$res['msg'];
        }
        $this->ajaxReturn($return);
    }

    /**
     * 收藏
     */
    public function get_collect(){
        $return=array('status'=>1,'msg'=>'');
        $goods_id=I('id');
        $type=I('type')?I('type'):0;
        $is_on=1;
        $data=D('Common/Goods')->favorite($goods_id,$type,$is_on);
        $return['msg']=$data['msg'];
        if($data['status']==0 || $data['status']==3){
            $return['status']=3;
        }else{
            if($data['is_on']==1){
                $return['is_collect']=1;
            }
            $return['status']=1;
        }
        $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 buy_now(){
        $return=array('status'=>2,'info'=>'数据错误');
        $postdata=$param=I('param.');
        $user_info=$this->checkuserauth();
        $param['uid']=$user_info['id'];
        // $param['shop_id']=$shop_id=$user_info['HCshop']['bind_shop_id'];//追加当前会员匹配的门店
        $return['data']=$param;
        $shop_id=$param['shop_id'];
        $goods_id=$param['goods_id'];
        
        $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();

        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']){

                $this->ajaxReturn($return);
            }

            // 查询该会员在此活动下已购数量
            $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['info'] = "本活动单人限量".$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['info'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                $this->ajaxReturn($return);
            }
        }
        //验证是否选择属性
        $goods_attr_map = array();
        $goods_attr_map['g.goods_id'] = $goods_id;
        $goods_attr_map['ga.type'] = array('neq', 'text');
        $map_attr['goods_id']=$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)) {
                    $return['info'] = '请选择商品规格';
                    $return['app_data'] = 'open_attr';  //app返回直接加载属性页面
                    $return['status'] = 3;
                    $this->ajaxReturn($return);
                }
            }
        }
        if($param['goods_attr']){
            $goods_attr= json_decode(htmlspecialchars_decode($param['goods_attr']),true);
        }
        $goods_attr=array();
        if($param['checkarrkey_str'] !=0)$goods_attr['key']=$param['checkarrkey_str'];
        if($param['checkarrkey_strname'] !=0)$goods_attr['name']=$param['checkarrkey_strname'];
        if($goods_attr){
            $param['spec']=$goods_attr['key'];
            $param['name']=$goods_attr['name'];
        }
        $uid=$user_info['id'];
        if(!empty($goods_id)){
            $is_num = D("Common/Cart")->shopgoodsstock($goods_id,$shop_id,$goods_attr['key']);
            
            if($is_num['goods_number'] <= 0){
                $return['info']="库存不足！";
                $this->ajaxReturn($return);
            }
        }$map = array();$map['e.style_ext_id'] = $goods_id;$map['e.style'] = 4;
        $buy_limit = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where($map)->order('e.id desc')->getField('buy_limit');
        if($param['number'] > $buy_limit && $buy_limit != 0){
            $return['info']='按拼团价格买每人限购'.$buy_limit.'件，不得超过数量限制';
            $this->ajaxReturn($return);
        }
        $now_time = NOW_TIME;
        //是否成团
        $pid_order = I('get.pid');
        if(!empty($pid_order)){
            $map_tea['id']=$pid_order;
            $tid = M('OrderInfo')->where($map_tea)->getField('uid');
            if($tid==$uid){
                $return['info']='你是该团的团长，不可参团购买';
                $this->ajaxReturn($return);
            }
            $map_son = array();$map_son['pid'] = $pid_order;$map_son['pay_status'] = 3;
            $son_uid = M('OrderInfo')->where($map_son)->field('uid')->select();
            if(!empty($son_uid)){
                foreach($son_uid as $k=>$v){
                    $arr[] = $v['uid'];
                }
                if(in_array($uid, $arr)){
                    $return['info']='你已参加该团，不可再次购买';
                    $this->ajaxReturn($return);
                }
            }
            $p_order_status = M('OrderInfo')->where('id='.$pid_order)->getField('shipping_status');
            if($p_order_status == 1){
                $return['info']='该团已成团，不可参团';
                $this->ajaxReturn($return);
            }
            $map = array();$map['e.style_ext_id'] = $goods_id;$map['e.style'] = 4;
            $group_time_limit = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where($map)->order('e.id desc')->getField('group_time_limit');
            $p_time = M('OrderInfo')->where('id='.$pid_order)->getField('confirm_time');
            $p_end = $p_time + ($group_time_limit * 3600);
            if($p_end<$now_time){
                //已过期未成团的，返还余额
                $status = M('OrderInfo')->where('id='.$pid_order)->getField('status');
                if($status != 10 && $status != 4){
                    $postdata['order_id']=$pid_order;
                    $postdata['admin_id']=$uid;//操作日志用
                    $postdata['type']='Member';//操作日志用
                    $return=D('Common/OrderInfo')->cancel_order($postdata);
                    if($return['status'] == 1){
                        $save['status'] = 10;
                        $map = array();
                        $map['id'] = $pid_order;
                        $update = M('OrderInfo')->where($map)->save($save);
                    }
                    $map = array();
                    $map['pid'] = $pid_order;
                    $son_orders = M('OrderInfo')->where($map)->field('id')->select();
                    if(!empty($son_orders)){
                        $map_order['admin_id']=$uid;//操作日志用
                        $map_order['type']='Member';//操作日志用
                        foreach ($son_orders as $key => $value) {
                            $map_order['order_id']=$value['id'];
                            $updates = D('Common/OrderInfo')->cancel_order($map_order);
                            if($updates['status'] == 1){
                                $maps = array();
                                $maps['id'] = $value['id'];
                                $saves['status'] = 10;
                                $updates = M('OrderInfo')->where($maps)->save($saves);
                            }
                        }
                    }
                }
                $return['info']='该团已过期，不可参团';
                $this->ajaxReturn($return);
            }
        }
        //是否过期
        $map = array();$map['e.style_ext_id'] = $goods_id;$map['e.style'] = 4;
        $end_time = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where($map)->order('e.id desc')->getField('end_time');
        if($end_time<$now_time){
            $return['info']='该团已过期，不可参团';
           $this->ajaxReturn($return);
        }
        $return['status']=1;
        $return['data']=$param;
        $this->ajaxReturn($return);
    }
    /**
     * 商品立即购买
     */
    public function buy_nows(){
        $param=$postdata=I("param.");
        $postdata['status'] = 1;
        $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']);//获取商品最终价格
        }
        $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['info'] = '请加入商品【'.$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['info'] = $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'] && $postdata['type'] == 14){
            $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['info'] = "本活动单人限量".$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['info'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                $this->ajaxReturn($return);
            }
        }      
        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')->find();
            // 查询该会员在此活动下已购数量
            $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['info'] = "本活动单人限量".$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['info'] = $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['info'] = $is_num['info'];
                $this->ajaxReturn($postdata);
            }
            //验证是否选择属性
            $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();
            $postdata['stockcount']=$stockcount;
            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();
                $postdata['goods_attrs']=$goods_attrs;
                if (!empty($goods_attrs)) {
                    $attrs=array();
                    if($postdata['goods_attr'])$attrs = explode("_", $postdata['goods_attr']);
                    $postdata['attrs']=$attrs;
                    $postdata['count_attrs']=count($attrs);
                    $postdata['count_goods_attrs']=count($goods_attrs);
                    if (count($attrs) != count($goods_attrs)) {
                        $postdata['info'] = '请选择商品规格';
                        $postdata['app_data'] = 'open_attr';  //app返回直接加载属性页面
                        $postdata['status'] = 3;
                        $this->ajaxReturn($postdata);
                    }
                }
            }
        }
        if($postdata['type'] == 11){
            $return = D("Common/OrderInfo")->check_service($postdata['goods_id'],$shop_id);
            if($return['status'] == 0){
                $postdata['status'] = 3;
                $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'] = 3;
                $postdata['msg'] = '库存不足！';
            }
            if(empty($postdata['integra'])){
                $postdata['status'] = 3;
                $postdata['app_data'] = 'open_attr';
                $postdata['msg'] = '请选择付款方式';
            }
        }
        $this->ajaxReturn($postdata);
    }
    /*
    *活动是否过期
    */
    public function check_act($goods_id,$number,$pid_order,$uid){
        $return['status']=1;
        $buy_limit = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where('e.style_ext_id='.$goods_id)->order('e.id desc')->getField('buy_limit');
        if($number > $buy_limit && $buy_limit != 0){
            if($type == 6){
                $return['status']=2;
                $return['msg']='按拼团价格买每人限购'.$buy_limit.'件，不得超过数量限制';
            }else{
                $return['status']=2;
                $return['msg']='每人限购'.$buy_limit.'件，不得超过数量限制';
            }
            return $return;
        }
        $now_time = NOW_TIME;
        //是否成团
        // $pid_order = I('get.pid');
        if(!empty($pid_order)){
            $map_tea['id']=$pid_order;
            $tid = M('OrderInfo')->where($map_tea)->getField('uid');
            if($uid==$tid){
                $return['status']=2;
                $return['msg']='你是该团的团长，不可参团购买';
                return $return;
            }
            $map_son['pid'] = $pid_order;
            $map_son['pay_status'] = 3;
            $son_uid = M('OrderInfo')->where($map_son)->field('uid')->select();
            if(!empty($son_uid)){
                foreach($son_uid as $k=>$v){
                    $arr[] = $v['uid'];
                }
                if(in_array($uid, $arr)){
                    $return['status']=2;
                    $return['msg']='你已参加该团，不可再次购买';
                    return $return;
                }
            }
            $p_order_status = M('OrderInfo')->where('id='.$pid_order)->getField('shipping_status');
            if($p_order_status == 1){
                $return['status']=2;
                $return['msg']='该团已成团，不可参团';
                return $return;
            }
            $group_time_limit = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where('e.style_ext_id='.$goods_id)->order('e.id desc')->getField('group_time_limit');
            $p_time = M('OrderInfo')->where('id='.$pid_order)->getField('confirm_time');
            $p_end = $p_time + ($group_time_limit * 3600);
            if($p_end<$now_time){
                //已过期未成团的，返还余额
                $status = M('OrderInfo')->where('id='.$pid_order)->getField('status');
                if($status != 10 && $status != 4){
                    $postdata['order_id']=$pid_order;
                    $postdata['admin_id']=$uid;//操作日志用
                    $postdata['type']='Member';//操作日志用
                    $return=D('Common/OrderInfo')->cancel_order($postdata);
                    if($return['status'] == 1){
                        $save['status'] = 10;
                        $map['id'] = $pid_order;
                        $update = M('OrderInfo')->where($map)->save($save);
                    }
                    $son_orders = M('OrderInfo')->where('pid='.$pid_order)->field('id')->select();
                    if(!empty($son_orders)){
                        $map_order['admin_id']=$uid;//操作日志用
                        $map_order['type']='Member';//操作日志用
                        foreach ($son_orders as $key => $value) {
                            $map_order['order_id']=$value['id'];
                            $updates = D('Common/OrderInfo')->cancel_order($map_order);
                            if($updates['status'] == 1){
                                $maps['id'] = $value['id'];
                                $saves['status'] = 10;
                                $updates = M('OrderInfo')->where($maps)->save($saves);
                            }
                        }
                    }
                }
                $return['status']=2;
                $return['msg']='该团已过期，不可参团';
                return $return;
            }
        }
        //是否过期
        $end_time = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where('e.style_ext_id='.$goods_id)->order('e.id desc')->getField('end_time');
        if($end_time<$now_time){
            if($type == 6){
                $return['status']=2;
                $return['msg']='该团已过期，不能购买此商品';
                return $return;
            }else{
                $return['status']=2;
                $return['msg']='活动已过期，不能购买此商品';
                return $return;
            }
        }
    }

    /**
     * 评论
     */
    public function goods_comment(){
        $return=array('status'=>3,'msg'=>'无更多评论了');
        $param=I('param.');
        $goods_id=I('goods_id');
        $return['common_list']=D('Mobile/Dp')->get_goods($param,$goods_id);
        if($return['common_list']['status']==2){
            foreach ($return['common_list']['dp_list'] as $key => $value) {
                $return['common_list']['dp_list'][$key]['username']=show_user_name($value['uid']);
                $header_img=idtoname($value['uid'],'Member','header_img');
                $img=format_url($header_img);
                $img=str_replace('https','http',$img);
                $return['common_list']['dp_list'][$key]['header_img']=$img;
                $return['common_list']['dp_list'][$key]['xing']=$value['dp_point']/5*100;
                $return['common_list']['dp_list'][$key]['add_time']=time_format($value['addtime']);
                if($value['pl_img']){
                    foreach ($value['pl_img'] as $k => $value) {
                        $img=format_url($value);
                        $img=str_replace('https','http',$img);
                        $return['common_list']['dp_list'][$key]['imgjson'][$k]=$img;
                    }
                }
            }
            $return['status']=1;
            $return['dp_count']=$return['common_list']['count_dp'];
        }
        
        $this->ajaxReturn($return);
    }
	/**
     * 分销详情页面
     */
    public function fx_cont(){
        $return=array('status'=>1);
        $goods_id=I('goods_id');
		$newdata['list']='';
		$uid=I('uid');
		$newdata['username'] =idtoname($uid,'Member','username');	
		$newdata['goods_info'] =M('Goods')->field('goods_name,supply_price,is_promote,promote_price,shop_price,img')->where('id='.$goods_id)->find();
		$newdata['goods_info']['img'] = thumb($newdata['goods_info']['img'],500,500);
		//佣金显示
		$newval = (C('COMMISSION'));
		if($newval>0){
			$pro = unserialize((C('AFFILIATE')));
			$proone = $pro['item'][1]['level_money'];
			$protwo = $pro['item'][2]['level_money'];
			$prothree = $pro['item'][3]['level_money'];
			$supply_price = substr($newdata['goods_info']['supply_price'],3);
			if($newdata['goods_info']['is_promote']==1 && $newdata['goods_info']['promote_price']>0){
				$promote_price = $newdata['goods_info']['promote_price'];
			}else{
				$promote_price = substr($newdata['goods_info']['shop_price'],3);
			}
			$newdata['list']['brokerone'] = intval($promote_price-$supply_price)*intval($proone)*0.01;
			$newdata['list']['brokertwo']  = intval($promote_price-$supply_price)*intval($protwo)*0.01;
			$newdata['list']['brokerthree']  = intval($promote_price-$supply_price)*intval($prothree)*0.01;
		}
        if($newdata) {
            $return['data']=$newdata;
        }else{
            $return['status']=3;
            $return['msg']='未获取到数据';
        }
        $this->ajaxReturn($return);
    }
}