<?php
/**
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Common\Model;
use Think\Model;
class CartModel extends Model
{
    /**加入购物车检测
     * @param $goods_id 商品id
     * @param $attr 商品属性
     * @param $number 购买的商品数量
     * @param $cart_type 1直营商品，2订货商品3,外卖商品
     * @param $pack_id 包装id
     * @return array
     */
    public function check_cart($goods_id, $attr, $number = 1, $name='',$address_id=0,$cart_type=1,$pack_id=0)
    {
        $return = array('status' => 2, 'msg' => '', 'data' => '', 'url' => '');
        if($cart_type==1){
            $memberinfo = checkuserauthtype();
            $re_shopping = C('NOT_ADD_CART');//是否允许未登录购买
            //判断用户是否登录
            if (empty($memberinfo) && $re_shopping == 0) {
                $return['msg'] = '请登录';
                $return['status'] = 0;
                $return['url'] = getjumpurl('JUMP_1');
                return $return;
            }
        }elseif($cart_type==2){
            // 判断店铺是否登录
            $shops_info = checkuserauthtype(2);
            if(empty($shops_info)){
                $return['msg'] = '请登录';
                $return['status'] = 0;
                $return['url'] = getjumpurl('JUMP_8');
                return $return;
            }
        }elseif($cart_type==3 && !empty($goods_id)){
            $shop_id = get_wxsmall_shop_id();
            $num = $this->shopgoodsstock($goods_id,$shop_id,$attr);
            if($num['goods_number'] <= 0){
                $return['msg'] = $num['info'];//'库存不足！';
                $return['status'] = 0;
                $return['shop_id']=$shop_id;
                return $return;
            }
        }

        if (empty($goods_id)) {
            $return['msg'] = '没有可以购买的产品';
            $return['status'] = 1;
            return $return;
        }
        //判断商品是否有效
        $g_map=array();
        $g_map['id']=$goods_id;
        $status=M('Goods')->where($g_map)->Field('is_delete,status')->find();
        if($status['is_delete']>0 || $status['status']==0){
            $return['msg'] = '商品已下架';
            $return['status'] = 1;
            return $return;
        }
        if (intval($number) <= 0) {
            $return['msg'] = '商品数量必须大于等于1';
            $return['status'] = 1;
            return $return;
        }
        if(intval($number) > 0 && $cart_type==2 && $pack_id > 0){
            $number = $number*idtoname($pack_id,'GoodsPackage','ratio','',false);
        }
        $map['id']=$goods_id;
        $is_service=M("Goods")->where($map)->getField('goods_type');
        if($is_service != 4 && $is_service!=6){
            //验证是否选择属性
            $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 = explode("_", $attr);
                    if (count($attrs) != count($goods_attrs)) {
                        $return['msg'] = '请选择商品规格';
                        $return['app_data'] = 'open_attr';  //app返回直接加载属性页面
                        $return['status'] = 1;
                        return $return;
                    }
                }
            }

            //判断属性库存
            $attrstock = D("Common/GoodsAttr")->check_attr_stock($attr, $goods_id, $number, $name,$cart_type);
            if ($attrstock['status'] == 0) {
                $return['attr_kucun'] = 2;
                $return['msg'] = $attrstock['msg'];
                $return['status'] = 1;
                return $return;
            }
            //判断商品库存以及最大购买量和最少购买量
            $check_goods_count = $this->check_cart_number($goods_id, $number,$cart_type);
            if ($check_goods_count['status'] == 1) {
                $return['msg'] = $check_goods_count['msg'];
                $return['status'] = 1;
                return $return;
            }
            //验证会员不能购买该会员所注册的店铺的商品

            $shop_id=M("Goods")->where($map)->getField('shop_id');
            if($shop_id && $cart_type==1){
                $shop_map=array();
                $shop_map['id']=$shop_id;
                $shop_uid=M("Shops")->where($shop_map)->getField('uid,name');
                if(!empty($memberinfo) && $shop_uid['uid']==$memberinfo['id'] && $shop_uid['uid']>0){
                    $return['msg'] ="该商品是本店铺下的商品,不能购买";
                    $return['status'] = 1;
                    return $return;
                }

            }
            // 判断该地区是否有货
            if(empty($address_id)) {
                $address_info = checkuseraddress();
            }else{
                $addmap['id']=intval($address_id);
                $address_info=M('MemberAddress')->where($addmap)->field('province,city,district')->find();
            }
            if ($address_info['district']) {
                $area_id = $address_info['district'];
            } elseif($address_info['city']) {
                $area_id = $address_info['city'];
            }else {
                $area_id = $address_info['province'];
            }
            if($cart_type == 2){
                $suppliers_id = M("Goods")->where($map)->getField('suppliers_id');
                $root=D("Common/Cart")->get_area_fees($suppliers_id,$area_id);
            }elseif($cart_type == 1){
                $root=D("Common/Cart")->get_area_fee($shop_id,$area_id);
            }elseif($cart_type == 3){
                $root['is_stock']=1;
            }

            if($root['is_stock']==0){
                if($shop_id>0){
                    $sho_map['id']=$shop_id;
                    $shop_name=M("Shops")->where($sho_map)->getField('name');
                }
                $shop_name=empty($shop_name)?'官方自营旗舰店':("店铺".$shop_name);
                $return['msg'] =$shop_name."下的商品在该地区无货,不能购买";
                $return['status'] = 1;
                return $return;
            }
        }

        return $return;
    }
    /**购买仓库商品加入购物车检测
     * @param $goods_id 商品id
     * @param $attr 商品属性
     * @param $number 购买的商品数量
     * @param $pack_id 包装id
     * @return array
     */
    public function check_carts($goods_id, $attr, $number = 1, $name='',$address_id=0,$pack_id=0)
    {
        $return = array('status' => 2, 'msg' => '', 'data' => '', 'url' => '');
        // 判断店铺是否登录
        $shops_info = checkuserauthtype(2);
        if(empty($shops_info)){
            $return['msg'] = '请登录';
            $return['status'] = 0;
            $return['url'] = getjumpurl('JUMP_8');
            return $return;
        }


        if (empty($goods_id)) {
            $return['msg'] = '没有可以购买的产品';
            $return['status'] = 1;
            return $return;
        }
        //判断商品是否有效
        $g_map=array();
        $g_map['id']=$goods_id;
        $status=M('Goods')->where($g_map)->Field('is_delete,status')->find();
        if($status['is_delete']>0 || $status['status']==0){
            $return['msg'] = '商品已下架';
            $return['status'] = 1;
            return $return;
        }
        if (intval($number) <= 0) {
            $return['msg'] = '商品数量必须大于等于1';
            $return['status'] = 1;
            return $return;
        }
        if(intval($number) > 0 && $pack_id > 0){
            $number = $number*idtoname($pack_id,'GoodsPackage','ratio','',false);
        }
        $map['id']=$goods_id;
        //验证是否选择属性
        $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 = explode("_", $attr);
                if (count($attrs) != count($goods_attrs)) {
                    $return['msg'] = '请选择商品规格';
                    $return['app_data'] = 'open_attr';  //app返回直接加载属性页面
                    $return['status'] = 1;
                    return $return;
                }
            }
        }

        //判断属性库存及配送范围
        $where=array();
        $area = idtoname($shops_info['shop_id'],'Shops','province,city_id,district');
        $area_id='';
        if($area['district']){
            $area_id = $area['district'];
        }
        if(!$area_id){
            $area_id = $area['city_id'];
        }
        if(!$area_id){
            $area_id = $area['province'];
        }
        $store_id=get_area_stid($area_id);
        $storageid=intval($store_id['0']);
        $return['storage_id']=$storageid;
        if($storageid>0){
            $where['store_id']=$store_id['0'];
            $where['goods_id']=$goods_id;
            if($attr==0){
                $attr='';
            }
            $where['goods_attr_sn'] = $goods_id.'-' .$attr;
            $stock=M("StorageStock")->where($where)->getField('stock');
            if(!$stock){
                $return['attr_kucun'] = 2;
                $return['msg'] = '商品库存不足';
                $return['status'] = 1;
                return $return;
            }
        }else{
            $return['msg'] = '该商品在该地区无货,不能购买';
            $return['status'] = 1;
            return $return;
        }



        //判断商品库存以及起订量
        if($pack_id>0){
            $pakageinfo = M('GoodsPackage')->where('id='.$pack_id)->field('ratio,moq')->find();
            if($number<$pakageinfo['moq']){
                $return['msg'] = '起订量为'.$pakageinfo['moq'];
                $return['status'] = 1;
                return $return;
            }
            $number = $number*$pakageinfo['ratio'];
        }else{
            $moq=idtoname($goods_id,'Goods','moq','id',false);
            if($number<$moq){
                $return['msg'] = '起订量为'.$moq;
                $return['status'] = 1;
                return $return;
            }
        }
        if($stock<$number){
            $return['msg'] = '库存不足';
            $return['status'] = 1;
            return $return;
        }

        return $return;
    }
    /**检测商品的数量状态
     * @param $id 商品id
     * @param $number 商品数量
     * @param $cart_type 购物车类型 1直营2订货
     */
    public function check_cart_number($id, $number,$cart_type=1)
    {
        if($cart_type==2){
            $memberinfo = checkuserauthtype(2);
        }else{
            $memberinfo = checkuserauthtype();
        }

        $return = $cart_map = $goods_map = $map = $unpaid_map = array();
        $re_shopping = C('NOT_ADD_CART');//是否允许未登录购买
        if ($re_shopping > 0 && empty($memberinfo) && $cart_type == 1) {
            $cart_map['cookie_id'] = cookie('u_cookieid');
            $cart_list = M("Cart")->field(true)->where($cart_map)->select();
        } else {
            if($cart_type == 2){
                $cart_map['user_id'] = $memberinfo['shop_id'];
            }else{
                $cart_map['user_id'] = $memberinfo['id'];
            }
            $cart_list = M("Cart")->field(true)->where($cart_map)->select();
        }
        $goods_map['id'] = $id;
        $goods_info = M("Goods")->where($goods_map)->field(true)->find();
        //商品已售数量（销量）
        $goods_buy_count = $goods_info['sell_count'];
        // 本商品当前会员的购物车中数量
        $goods_user_cart_count = 0;
        if ($cart_list) {
            foreach ($cart_list as $k => $v) {
                if ($v['goods_id'] == $id) {
                    $goods_user_cart_count += intval($v['goods_num']);
                }
            }
        }
        $goods_user_paid_count = 0;
        $goods_user_unpaid_count = 0;
        if ($memberinfo) {
            //本商品当前会员已付款的数量
            $map['g.goods_id'] = $id;
            if($cart_type==2){
                $map['o.uid'] = $memberinfo['shop_id'];
            }else{
                $map['o.uid'] = $memberinfo['id'];
            }

            $map['o.pay_status'] = 3;
            $map['o.is_delete'] = 0;
            $goods_user_paid_count = M('OrderGoods')->alias('g')->where($map)->JOIN('LEFT JOIN __ORDER_INFO__ o ON o.id=g.order_id')->sum('g.goods_number');
            //4. 本商品当前会员未付款的数量
            $unpaid_map['g.goods_id'] = $id;
            $unpaid_map['o.pay_status'] = array('neq', 3);
            $unpaid_map['o.status'] = array('elt', 3);
            if($cart_type==2){
                $map['o.uid'] = $memberinfo['shop_id'];
            }else{
                $map['o.uid'] = $memberinfo['id'];
            }
            $unpaid_map['o.is_delete'] = 0;
            $goods_user_unpaid_count = intval(M('OrderGoods')->alias('g')->where($unpaid_map)->JOIN('LEFT JOIN __ORDER_INFO__ o ON o.id=g.order_id')->sum('g.goods_number'));
        }
        if ($goods_user_cart_count + $goods_user_unpaid_count + $number < $goods_info['user_min_bought'] && $goods_info['user_min_bought'] > 0) {
            $return['status'] = 1;
            //用户最小购买数不足
            $return['msg'] = "购买数量小于商品最少购买量，不能再购买";
            return $return;
        }
        if ($goods_user_unpaid_count + $number < $goods_info['moq'] && $goods_info['moq'] > 0) {//订货商品
            $return['status'] = 1;
            //店铺最小购买数不足
            $return['msg'] = $goods_info['goods_name']."购买数量不能小于商品起订量";
            return $return;
        }
        if ($goods_user_cart_count + $goods_user_paid_count + $goods_user_unpaid_count + $number > $goods_info['user_max_bought'] && $goods_info['user_max_bought'] > 0) {
            $return['status'] = 1;
            //用户最大购买数超出
            $return['msg'] = "已超出商品最大购买量，不能再购买";
            return $return;
        }
        return $return;
    }
    /**计算商品价格
     * @param $goods_id 商品id
     * @param string $attr 商品属性
     * @return array（'price'=>价格,'price_type'=>价格类型（1原价，2会员价，3促销价））
     */
    public function get_goods_price($goods_id,$attr=''){
        $result=$this->getminprice($goods_id,$attr);
        $return['price']=$result['price'];
        $return['price_type']=$result['type'];//原价
        return $return;
    }
    public function getminprice($goods_id,$attr='',$name='Goods'){
        $memberinfo = checkuserauthtype();
        $map['id']=$goods_id;
        $goods_info = M($name)->where($map)->field('shop_price,promote_id,promote_end_time,promote_start_time,promote_price,goods_type')->find();
        //平台价
        $all_price[1]=$goods_info['shop_price'];
        if (!empty($memberinfo) && $goods_info['goods_type'] != 6) {
            $member_map = $memberrank_map = array();
            $member_map['id'] = $memberinfo['id'];
            $rank_id = M("Member")->where($member_map)->getField('rank_id');
            $memberrank_map['id'] = $rank_id;
            $rank = M("MemberRank")->where($memberrank_map)->getField("goods_price");
            if($rank==100){
                $all_price[1]=$goods_info['shop_price'];
            }else {
                $all_price[2] = $all_price[1] * $rank / 100;
            }
        }
        //促销价
        if($goods_info['promote_id']>0 && $goods_info['promote_end_time']>NOW_TIME && NOW_TIME>=$goods_info['promote_start_time'] && $goods_info['promote_price']>0){
            $all_price[3]=$goods_info['promote_price'];
        }
        //获取最低价
        $minprice = min(array_filter($all_price));
        //print_r($minprice);exit;
        $type = array_search($minprice,$all_price);
        $attr_price =D("Common/GoodsAttr")->get_goods_attrprice($attr,$minprice);
        if(empty($attr_price)){
            $newprice =$minprice;
        }else{
            $newprice =$attr_price;
        }
        return array('type'=>$type,'price'=>$newprice);
    }
    /** 加入购物车
     * @param $goods_id 商品id
     * @param $number 购买商品的数量
     * @param $integral
     * @param $attr 属性
     * @param $name 属性名称
     * @param $price 价格
     * @param $act 活动
     * @param $type 以哪种方式加入购物车 0加入购物车1立即购买2立即兑换
     * @return array
     */
    public function add_carts($goods_id, $attr = '', $number = 1, $name = '', $act, $type = 0)
    {
        $shop_id = get_wxsmall_shop_id();
        // ---zjn ---
        if(!$shop_id){
            $shop_infos = D('Wxsmall/Login')->setshopid();
            $shop_id = $shop_infos['bind_shop_id'];
        }
        // -----end-----
        $re_shopping = C('NOT_ADD_CART');//是否允许未登录购买
        $return = array('status' => 0, 'msg' => '', 'data' => '', 'url' => '');
        $check = $this->check_cart($goods_id, $attr, $number, $name, 0, 3);
        $goods_info = idtoname($goods_id, 'Goods', 'goods_number,promote_id,shop_price,goods_name,goods_sn,img,brand_id,cat_id,goods_number,sell_count,goods_max_number,goods_min_number,pt_id', 'id', false);
        //判断商品是否有属性
        $goods_attr_data = D('Common/GoodsAttr')->getattr($goods_id);
        if($goods_attr_data['newarr']){
            if(empty($attr) || empty($name)){
                $return['msg'] = '请选择商品规格';
                $return['status'] = 0;
                $return['app_data'] ='open_attr';
                return $return;
            }
        }

        //将属性和属性名称组合
        if ($attr) {
            $goodsattr_info = array(
                'key' => $attr,
                'name' => $name
            );
            $attr_info = serialize($goodsattr_info);
        }
        //计算商品价格
        // $price_info=$this->getminprice($goods_id,$attr);

        $price_info = array();
        $memberinfo = checkuserauthtype();
        if (!empty($attr)) {
            $cart_map['goods_attr'] = $attr_info;

            $map = array();
            $map['attr_key'] = $attr;
            $map['goods_id'] = $goods_id;
            $price_info['price'] = M('GoodsAttrStock')->where($map)->getField('attr_price');
            $price_info['type'] = 6;
            $price_info=D('Pad/Cashier')->get_min_price($shop_id,$goods_id,$memberinfo,$attr);
        }else{
            $attr_info='';
            $price_info=D('Common/Takeout')->get_min_price($shop_id,$goods_id);//获取商品最终价格
            $price_info['price'] = $price_info['goods_price'];
            $price_info['type'] = $price_info['price_type'];
        }
        $ret = D('Common/Promot')->goods_to_promot($goods_id,0,3,$shop_id);
        if($ret['count'] > 0){
            $act_info = current($ret['list']);
            $act = $act_info['id'];
        }
        if ($check['status'] == 2 && $re_shopping == 0) {//不允许未登录加入购物车
            //判断购物车中是否有完全相同的商品
            $cart_map['user_id'] = $memberinfo['id'];
            $cart_map['goods_id'] = $goods_id;
            $cart_map['shop_id'] = $shop_id;
            $cart_map['goods_attr'] = $attr_info;
            $member_cart = M('Cart')->where($cart_map)->field('id,goods_id,goods_attr,all_price,goods_num')->find();
            //如果有只改变改商品的数量和价格
            if (!empty($member_cart)) {
                $new_number = $member_cart['goods_num'] + $number;
                $new_check = $this->check_cart($goods_id, $attr, $new_number, $name, 0, 3);
                if($new_check['status']==1){
                    $return['msg'] = $new_check['msg'];
                    $return['status'] = 0;
                    $return['url'] = $new_check['url'];
                    $return['app_data'] = $new_check['app_data'];
                    return $return;
                }
                if($price_info['price_type']==3 || $price_info['price_type']==6){
                    $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,$memberinfo['id'],$goods_id);
                    $p_num=$new_number+$p_num;
                    if($goods_info['goods_min_number']>0 && intval($p_num) > $goods_info['goods_min_number']){
                        //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                        $return['msg'] = "本活动单人限量".$goods_info['goods_min_number']."您已超过单人限量";
                        $return['status'] = 0;
                        return $return;
                    }
                    //总限量
                    $p_num=D('Common/Takeout')->pro_num($promote_info,$memberinfo['id'],$goods_id,1);
                    $p_num=$new_number+$p_num;
                    if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                        $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                        $return['status'] = 0;
                        return $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,$memberinfo['id'],$goods_id);
                    $p_num=$new_number+$p_num;
                    if($promote_info['buy_limit']>0 && intval($p_num) > $promote_info['buy_limit']){
                        //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                        $return['msg'] = "本拼团单人限量".$promote_info['buy_limit']."您已超过单人限量";
                        $return['status'] = 0;
                        return $return;
                    }
                    //总限量
                    $p_num=D('Common/Takeout')->pro_num($promote_info,$memberinfo['id'],$goods_id,1);
                    $p_num=$new_number+$p_num;
                    if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                        $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                        $return['status'] = 0;
                        return $return;
                    }
                }
                $map_c = array();
                $map_c['goods_id'] = $goods_id;
                $map_c['user_id'] = $memberinfo['id'];
                $map_c['shop_id'] = $shop_id;
                $arr_num['goods_num'] = $new_number;
                $arr_num['cart_id'] = $act;
                $arr_num['shop_price'] = $price_info['goods_price'];
                $arr_num['price_type'] = $price_info['price_type'];
                $arr_num['all_price'] = $price_info['goods_price']*$arr_num['goods_num'];
                $add_cart = M('Cart')->where($map_c)->save($arr_num);
                $return['data'] = $member_cart['id'];
            } else {
                //将选中的商品加入购物车
                $cart_data['user_id'] = $memberinfo['id'];
                $cart_data['goods_id'] = $goods_id;
                $cart_data['goods_name'] = $goods_info['goods_name'];
                if($attr_info){
                    $cart_data['goods_sn'] = idtoname($attr,'GoodsAttrStock','goods_attr_sn','attr_key',false);
                }else{
                    $cart_data['goods_sn'] = $goods_info['goods_sn'];
                }
                if($price_info['price_type']==3){
                    $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,$memberinfo['id'],$goods_id);
                    $p_num=$number+$p_num;
                    if($goods_info['goods_min_number']>0 && intval($p_num) > $goods_info['goods_min_number']){
                        //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                        $return['msg'] = "本活动单人限量".$goods_info['goods_min_number']."您已超过单人限量";
                        $return['status'] = 0;
                        return $return;
                    }
                    //总限量
                    $p_num=D('Common/Takeout')->pro_num($promote_info,$memberinfo['id'],$goods_id,1);
                    $p_num=$number+$p_num;
                    if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                        $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                        $return['status'] = 0;
                        return $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,$memberinfo['id'],$goods_id);
                    $p_num=$number+$p_num;
                    if($promote_info['buy_limit']>0 && intval($p_num) > $promote_info['buy_limit']){
                        //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                        $return['msg'] = "本活动单人限量".$promote_info['buy_limit']."您已超过单人限量";
                        $return['status'] = 0;
                        return $return;
                    }
                    //总限量
                    $p_num=D('Common/Takeout')->pro_num($promote_info,$memberinfo['id'],$goods_id,1);
                    $p_num=$number+$p_num;
                    if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                        $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                        $return['status'] = 0;
                        return $return;
                    }
                }
                $cart_data['catid'] = $goods_info['cat_id'];
                $cart_data['goods_attr'] = $attr_info;
                $cart_data['goods_num'] = $number;
                $cart_data['shop_price'] = $price_info['goods_price'];
                $cart_data['price_type'] = $price_info['price_type'];
                $cart_data['all_price'] = $price_info['goods_price']*$number;
                $cart_data['shop_id'] = $shop_id;
                $cart_data['cart_id'] = $act;
                $add_cart = M('Cart')->add($cart_data);
                $return['data'] = $add_cart;
            }
            if ($add_cart) {
                $return['msg'] = '加入购物车成功';
                $return['status'] = 2;
                if ($type > 0) {
                    $return['url'] = U('Home/Order/Index', array("ids" => $add_cart));
                } else {
                    $return['url'] = U('Home/Goods/success_tpl');
                }
                return $return;
            } else {
                $return['msg'] = '加入购物车失败';
                $return['status'] = 1;
                return $return;
            }
        } elseif ($check['status'] == 2 && $re_shopping == 1) { //允许未登录加入购物车

            if ($memberinfo) {
                $cart_map = array();
                $cart_map['user_id'] = $memberinfo['id'];
                $cart_map['goods_id'] = $goods_id;
                $cart_map['cart_type'] = 3;//外卖购物车类型
                $cart_map['shop_id'] = $shop_id;
                $cart_map['goods_attr'] = $attr_info;
                $member_cart = M('Cart')->where($cart_map)->field('id,goods_id,goods_attr,all_price,goods_num')->find();
            } else {
                $cart_map['cookie_id'] = cookie('u_cookieid');
                $cart_map['goods_id'] = $goods_id;
                $cart_map['cart_type'] = 3;//外卖购物车类型
                $cart_map['shop_id'] = $shop_id;
                $cart_map['goods_attr'] = $attr_info;
                $member_cart = M('Cart')->where($cart_map)->field('id,goods_id,goods_attr,all_price,goods_num')->find();
            }
            if ($member_cart) {
                $map_c = array();
                $map_c['id'] = $member_cart['id'];
                $map_c['goods_id'] = $goods_id;
                $map_c['goods_attr'] = $attr_info;
                if ($memberinfo) {
                    $map_c['user_id'] = $memberinfo['id'];
                } else {
                    $map_c['user_id'] = 0;
                    $map_c['cookie_id'] = cookie('u_cookieid');
                }
                $new_number = $member_cart['goods_num'] + $number;

                if($price_info['price_type']==3 || $price_info['price_type']==6){
                    $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,$memberinfo['id'],$goods_id);
                    $p_num=$new_number+$p_num;
                    if($goods_info['goods_min_number']>0 && intval($p_num) > $goods_info['goods_min_number']){
                        //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                        $return['msg'] = "本活动单人限量".$goods_info['goods_min_number']."您已超过单人限量";
                        $return['status'] = 0;
                        return $return;
                    }
                    //总限量
                    $p_num=D('Common/Takeout')->pro_num($promote_info,$memberinfo['id'],$goods_id,1);
                    $p_num=$new_number+$p_num;
                    if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                        $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                        $return['status'] = 0;
                        return $return;
                    }
                }
                if($goods_info['pt_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,$memberinfo['id'],$goods_id);
                    $p_num=$new_number+$p_num;
                    if($promote_info['buy_limit']>0 && intval($p_num) > $promote_info['buy_limit']){
                        //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                        $return['msg'] = "本活动单人限量".$promote_info['buy_limit']."您已超过单人限量";
                        $return['status'] = 0;
                        return $return;
                    }
                    //总限量
                    $p_num=D('Common/Takeout')->pro_num($promote_info,$memberinfo['id'],$goods_id,1);
                    $p_num=$new_number+$p_num;
                    if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                        $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                        $return['status'] = 0;
                        return $return;
                    }
                }
                $new_check = $this->check_cart($goods_id, $attr, $new_number, $name, 0, 3);
                if($new_check['status']==1){
                    $return['msg'] = $new_check['msg'];
                    $return['status'] = 0;
                    $return['url'] = $new_check['url'];
                    $return['app_data'] = $new_check['app_data'];
                    return $return;
                }
                $arr_num['goods_num'] = $new_number;
                $arr_num['cart_id'] = $act;
                $arr_num['shop_price'] = $price_info['goods_price'];
                $arr_num['price_type'] = $price_info['price_type'];
                $arr_num['all_price'] = $price_info['goods_price']*$arr_num['goods_num'];
                $add_cart = M('Cart')->where($map_c)->save($arr_num);
                $return['data'] = $member_cart['id'];
            } else {
                //将选中的商品加入购物车
                if ($memberinfo) {
                    $cart_data['user_id'] = $memberinfo['id'];
                } else {
                    $cart_data['user_id'] = 0;
                    $cart_data['cookie_id'] = $this->getcookieid();
                }
                if($price_info['price_type']==3 || $price_info['price_type']==6){
                    $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,$memberinfo['id'],$goods_id);
                    $p_num=$number+$p_num;
                    if($goods_info['goods_min_number']>0 && intval($p_num) > $goods_info['goods_min_number']){
                        //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                        $return['msg'] = "本活动单人限量".$goods_info['goods_min_number']."您已超过单人限量";
                        $return['status'] = 0;
                        return $return;
                    }
                    //总限量
                    $p_num=D('Common/Takeout')->pro_num($promote_info,$memberinfo['id'],$goods_id,1);
                    $p_num=$number+$p_num;
                    if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                        $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                        $return['status'] = 0;
                        return $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,$memberinfo['id'],$goods_id);
                    $p_num=$number+$p_num;
                    if($promote_info['buy_limit']>0 && intval($p_num) > $promote_info['buy_limit']){
                        //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                        $return['msg'] = "本活动单人限量".$promote_info['buy_limit']."您已超过单人限量";
                        $return['status'] = 0;
                        return $return;
                    }
                    //总限量
                    $p_num=D('Common/Takeout')->pro_num($promote_info,$memberinfo['id'],$goods_id,1);
                    $p_num=$number+$p_num;
                    if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                        $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                        $return['status'] = 0;
                        return $return;
                    }
                }
                $cart_data['goods_id'] = $goods_id;
                $cart_data['goods_name'] = $goods_info['goods_name'];
                $cart_data['goods_sn'] = $goods_info['goods_sn'];
                $cart_data['catid'] = $goods_info['cat_id'];
                $cart_data['goods_attr'] = $attr_info;
                $cart_data['goods_num'] = $number;
                $cart_data['shop_price'] = $price_info['goods_price'];
                $cart_data['all_price'] = $price_info['goods_price']*$number;
                $cart_data['price_type'] = $price_info['price_type'];
                $cart_data['shop_id'] = $shop_id;
                $cart_data['cart_type'] = 3;
                $cart_data['cart_id'] = $act;
                $add_cart = M('Cart')->add($cart_data);
                $return['data'] = $add_cart;
            }
            if ($add_cart) {
                $return['msg'] = '加入购物车成功';
                $return['status'] = 2;
                if ($type > 0) {
                    $return['url'] = U('Home/Order/Index', array("ids" => $return['data']));
                } else {
                    $return['url'] = U('Home/Goods/success_tpl');
                }
                return $return;
            } else {
                $return['msg'] = '加入购物车失败';
                $return['status'] = 1;
                return $return;
            }
        } else {
            $return['msg'] = $check['msg'];
            $return['status'] = $check['status'];
            $return['url'] = $check['url'];
            $return['app_data'] = $check['app_data'];
            return $return;
        }
        return $return;
    }
    /** 订货加入购物车手机版、APP
     * @param $goods_id 商品id
     * @param $number 购买商品的数量
     * @param $integral
     * @param $attr 属性
     * @param $name 属性名称
     * @param $price 价格
     * @param $act 活动
     * @param $pack_id 包装id
     * @param $type 以哪种方式加入购物车 0加入购物车1立即购买
     * @return array
     */
    public function pur_addcart($goods_id, $attr = '', $number = 1, $name = '', $act='',$pack_id,$type=0)
    {

        $return = array('status' => 0, 'msg' => '', 'data' => '', 'url' => '');
        if(C('IS_WAREHOUSE')==1){// 判断该商品是否在配送范围
            $check = $this->check_carts($goods_id, $attr, $number, $name,0,$pack_id);
        }else{
            $check = $this->check_cart($goods_id, $attr, $number, $name,0,2,$pack_id);
        }
        $goods_info = idtoname($goods_id, 'Goods', 'goods_number,shop_price,goods_name,goods_sn,suppliers_id,img,brand_id,cat_id,supply_price', 'id', false);
        if($pack_id > 0){
            $goods_info['shop_price'] = idtoname($pack_id,'GoodsPackage','shop_price','id',false);
        }
        //将属性和属性名称组合
        if ($attr) {
            $goodsattr_info = array(
                'key' => $attr,
                'name' => $name
            );
            $attr_info = serialize($goodsattr_info);
        }

        if (!empty($attr)) {
            $cart_map['goods_attr'] = $attr_info;
        }else{
            $attr_info='';
        }
        $shops_info = checkuserauthtype(2);
        if ($check['status'] == 2) {
            //判断购物车中是否有完全相同的商品
            $cart_map['user_id'] = $shops_info['shop_id'];
            $cart_map['goods_id'] = $goods_id;
            $member_cart = M('Cart')->where($cart_map)->field('id,goods_id,goods_attr,all_price,goods_num')->find();
            //如果有只改变改商品的数量和价格
            if (!empty($member_cart)) {
                $arr_num['goods_num'] = $number;

                $arr_num['cart_id'] = $act;
                $arr_num['shop_price'] = $goods_info['shop_price'];
                $add_cart = M('Cart')->where($cart_map)->save($arr_num);
                $return['data'] = $member_cart['id'];
            } else {
                //将选中的商品加入购物车
                $cart_data['user_id'] = $shops_info['shop_id'];
                $cart_data['goods_id'] = $goods_id;
                $cart_data['goods_attr'] = $attr_info;
                $cart_data['goods_num'] = $number;
                $cart_data['shop_price'] = $goods_info['shop_price'];
                $cart_data['cart_id'] = $act;
                $cart_data['cart_type'] = 2;
                $cart_data['pack_id'] = $pack_id;
                $cart_data['supplier_price'] = $goods_info['supply_price'];
                $add_cart = M('Cart')->add($cart_data);
                $return['data'] = $add_cart;
            }
            if ($add_cart) {
                $return['msg'] = '加入购物车成功';
                $return['status'] = 2;
                if ($type > 0) {
                    $return['url'] = U('Home/PurOrder/Index', array("ids" => $add_cart));
                } else {
                    $return['url'] = U('Home/PurGoods/success_tpl');
                }
                return $return;
            } else {
                $return['msg'] = '加入购物车失败';
                $return['status'] = 1;
                return $return;
            }
        }  else {
            $return['msg'] = $check['msg'];
            $return['status'] = $check['status'];
            $return['url'] = $check['url'];
            $return['app_data'] = $check['app_data'];
            return $return;
        }
        return $return;
    }
    /** 订货加入购物车PC端
     * @param $goods_id 商品id
     * @param $number 购买商品的数量
     * @param $integral
     * @param $attr 属性
     * @param $name 属性名称
     * @param $price 价格
     * @param $act 活动
     * @param $pack_id 包装id
     * @param $type 以哪种方式加入购物车 0加入购物车1立即购买
     * @return array
     */
    public function puraddcart($goods_id, $attr = '', $number = 1, $name = '', $act='',$pack_id,$type=0)
    {

        $return = array('status' => 0, 'msg' => '', 'data' => '', 'url' => '');
        if(C('IS_WAREHOUSE')==1){// 判断该商品是否在配送范围
            $check = $this->check_carts($goods_id, $attr, $number, $name,0,$pack_id);
        }else{
            $check = $this->check_cart($goods_id, $attr, $number, $name,0,2,$pack_id);
        }

        $goods_info = idtoname($goods_id, 'Goods', 'goods_number,shop_price,goods_name,goods_sn,suppliers_id,img,brand_id,cat_id,supply_price', 'id', false);
        if($pack_id > 0){
            $goods_info['shop_price'] = idtoname($pack_id,'GoodsPackage','shop_price','id',false);
        }
        //将属性和属性名称组合
        if ($attr) {
            $goodsattr_info = array(
                'key' => $attr,
                'name' => $name
            );
            $attr_info = serialize($goodsattr_info);
        }

        if (!empty($attr)) {
            $cart_map['goods_attr'] = $attr_info;
        }else{
            $attr_info='';
        }
        $shops_info = checkuserauthtype(2);
        if ($check['status'] == 2) {
            //判断购物车中是否有完全相同的商品
            $cart_map['user_id'] = $shops_info['shop_id'];
            $cart_map['goods_id'] = $goods_id;
            $member_cart = M('Cart')->where($cart_map)->field('id,goods_id,goods_attr,all_price,goods_num')->find();
            //如果有只改变改商品的数量和价格
            if (!empty($member_cart)) {
                $arr_num['goods_num'] = $member_cart['goods_num'] + $number;
                $arr_num['cart_id'] = $act;
                $arr_num['shop_price'] = $goods_info['shop_price'];
                $add_cart = M('Cart')->where($cart_map)->save($arr_num);
                $return['data'] = $member_cart['id'];
            } else {
                //将选中的商品加入购物车
                $cart_data['user_id'] = $shops_info['shop_id'];
                $cart_data['goods_id'] = $goods_id;
                $cart_data['goods_attr'] = $attr_info;
                $cart_data['goods_num'] = $number;
                $cart_data['shop_price'] = $goods_info['shop_price'];
                $cart_data['cart_id'] = $act;
                $cart_data['cart_type'] = 2;
                $cart_data['pack_id'] = $pack_id;
                $cart_data['supplier_price'] = $goods_info['supply_price'];
                $add_cart = M('Cart')->add($cart_data);
                $return['data'] = $add_cart;
            }
            if ($add_cart) {
                $return['msg'] = '加入购物车成功';
                $return['status'] = 2;
                if ($type > 0) {
                    $return['url'] = U('Home/PurOrder/Index', array("ids" => $add_cart));
                } else {
                    $return['url'] = U('Home/PurGoods/success_tpl');
                }
                return $return;
            } else {
                $return['msg'] = '加入购物车失败';
                $return['status'] = 1;
                return $return;
            }
        }  else {
            $return['msg'] = $check['msg'];
            $return['status'] = $check['status'];
            $return['url'] = $check['url'];
            $return['app_data'] = $check['app_data'];
            return $return;
        }
        return $return;
    }
    //获取cookieid
    private function getcookieid()
    {
        $cookie_id = cookie('u_cookieid');
        if (empty($cookie_id)) {
            $cookie_id = md5(NOW_TIME . C("HANCHAO_KEY"));
            cookie('u_cookieid', $cookie_id, time() + 3600);
        }
        return $cookie_id;
    }
    public function add_cartlist($goods_id, $number, $act)
    {
        $memberinfo = checkuserauthtype();
        $re_shopping = C('NOT_ADD_CART');//是否允许未登录购买
        //判断用户是否登录
        if (empty($memberinfo) && $re_shopping == 0) {
            $return['msg'] = '请登录';
            $return['status'] = 0;
            $return['url'] = getjumpurl('JUMP_1');
            return $return;
        }
        if ($goods_id == '') {
            $return['msg'] = '没有可以购买的产品';
            $return['status'] = 1;
            return $return;
        }
        if ($number <= 0) {
            $return['msg'] = '商品数量必须大于等于1';
            $return['status'] = 1;
            return $return;
        }
        //验证是否选择属性
        $goodsattr_map = array();
        $goodsattr_map['g.goods_id'] = $goods_id;
        $goodsattr_map['ga.type'] = array('neq', 'text');
        $goods_attrs = M("GoodsAttr")->alias('g')->distinct("g.attr_id")->where($goodsattr_map)->JOIN('LEFT JOIN __GOODS_ATTRIBUTE__ ga ON g.attr_id=ga.id')->field('attr_id')->select();
        if (!empty($goods_attrs)) {
            $return['status'] = 3;
            $return['url'] = U("Home/Goods/goods_attrs", array("goods_id" => $goods_id, "number" => $number));
            return $return;
        } else {
            $goods_map = array();
            $goods_map['id'] = $goods_id;
            $price = M("Goods")->where($goods_map)->getField("shop_price");
            $return = $this->add_carts($goods_id, '', $number, '', $act, 0);
            return $return;
        }
    }
    /** 订货PC端列表加入购物车
     * @param $goods_id 商品id
     * @param $number 购买商品的数量
     * @param $integral
     * @param $attr 属性
     * @param $name 属性名称
     * @param $price 价格
     * @param $pack_id 包装id
     * @return array
     */
    public function padd_cartlist($goods_id, $number, $pack_id)
    {
        $memberinfo = checkuserauthtype(2);
        //判断用户是否登录
        if (empty($memberinfo)) {
            $return['msg'] = '请登录';
            $return['status'] = 0;
            $return['url'] = getjumpurl('JUMP_8');
            return $return;
        }
        if ($goods_id == '') {
            $return['msg'] = '没有可以购买的产品';
            $return['status'] = 1;
            return $return;
        }
        if ($number <= 0) {
            $return['msg'] = '商品数量必须大于等于1';
            $return['status'] = 1;
            return $return;
        }
        //验证是否选择属性
        $goodsattr_map = array();
        $goodsattr_map['g.goods_id'] = $goods_id;
        $goodsattr_map['ga.type'] = array('neq', 'text');
        $goods_attrs = M("GoodsAttr")->alias('g')->distinct("g.attr_id")->where($goodsattr_map)->JOIN('LEFT JOIN __GOODS_ATTRIBUTE__ ga ON g.attr_id=ga.id')->field('attr_id')->select();
        if (!empty($goods_attrs)) {
            $return['status'] = 3;
            $return['url'] = U("Home/PurGoods/goods_attrs", array("goods_id" => $goods_id, "number" => $number));
            return $return;
        } else {
            $goods_map = array();
            $goods_map['id'] = $goods_id;
            $price = M("Goods")->where($goods_map)->getField("shop_price");
            $return = $this->puraddcart($goods_id, '', $number, '', '', $pack_id);
            return $return;
        }
    }
    public function cart_index($type)
    {
        $return = array();
        $return['status'] = 0;//0没数据，1有数据
        $memberinfo = checkuserauthtype();
        $data = $carts_map = array();
        if (empty($memberinfo)) {
            $ucookieid = cookie('u_cookieid');
            if (empty($ucookieid)) return $return;
            $carts_map['cookie_id'] = $ucookieid;
        } else {
            $carts_map['user_id'] = $memberinfo['id'];
        };
        $carts_map['cart_type'] = $type;
        $cart_ids = M('Cart')->where($carts_map)->getField('id', true);
        $data = $this->cartlist('', $cart_ids,0,0,$type);
        $return['status'] = 1;
        $return['data'] = $data;
        return $return;
    }
    /**订货购物车
     */
    public function cart_indexp()
    {
        $return = array();
        $return['status'] = 0;//0没数据，1有数据
        $shops_info = checkuserauthtype(2);
        $data = $carts_map = array();
        if (!empty($shops_info)) {
            $carts_map['user_id'] = $shops_info['shop_id'];
            $carts_map['cart_type'] = 2;
        }
        $cart_ids = M('Cart')->where($carts_map)->getField('id', true);
        $data = $this->cartlistp('', $cart_ids);
        $return['status'] = 1;
        $return['data'] = $data;
        return $return;
    }
    /**订货购物车列表
     * @param string $goodsids 商品id
     * @param $is_order 是否是订单 0购物车，1订单
     * @return mixed
     */
    public function cartlistp($goods_id='', $cart_ids = '', $is_order = 0,$addre_id=0)
    {
        $return = $carts_map = array();
        $return['status'] = $return['all_price'] = $return['all_save_price'] = 0;
        $shops_info = checkuserauthtype(2);
        //判断用户是否登录
        if (empty($shops_info)) {
            $return['status'] = 2;
            $return['msg'] = '请登录';
            $return['url'] = getjumpurl('JUMP_8');
            return $return;
        } else {
            $carts_map['c.user_id'] = $shops_info['shop_id'];
        }
        if (!empty($cart_ids)) $carts_map['c.id'] = array('in', $cart_ids);
        $carts_map['cart_type'] = 2;
        if($cart_ids) {
            $carts = M('Cart')->alias('c')->JOIN('LEFT JOIN __GOODS__ g ON g.id=c.goods_id')->where($carts_map)->field('g.*,g.id as goods_id,c.id as id,c.user_id,c.cookie_id,c.goods_attr,c.goods_num,c.cart_id,c.shop_price as shop_price,c.price_type,c.pack_id,g.moq,c.pack_id,c.supplier_price')->order('g.suppliers_id asc')->select();
        }elseif(!empty($goods_id)){
            $info=D("Common/OrderInfo")->buy_now($goods_id,10);
            if($info['status']<=0){$return['status']=0;$return['msg']=$info['msg'];return $return;}
            $carts=$info['data'];
        }
        $cartlist = $shoptickets = $promot_lists = array();
        $orig_total_prices = 0;
        $list = array();
        foreach ($carts as $k => $v) {
            if(C('IS_WAREHOUSE')==1){
                $v['suppliers_id']=0;
            }
            if (empty($cartlist[$v['suppliers_id']]['shop_info'])) $cartlist[$v['suppliers_id']]['shop_info'] = $this->format_goods_supplier($v['suppliers_id'],$shops_info['shop_id']);
            //如果供货商信息还是空的，将不显示该供货商下的商品
            if (!empty($cartlist[$v['suppliers_id']]['shop_info'])) {
                if (empty($cartlist[$v['suppliers_id']]['promot_list'][$v['cart_id']]['promot_info'])) $cartlist[$v['suppliers_id']]['promot_list'][$v['cart_id']]['promot_info'] = $this->format_goods_promot('');
                if($v['cart_id']>0 && $cartlist[$v['suppliers_id']]['promot_list'][$v['cart_id']]['promot_info']['is_valid']==0){
                    $v['status']=0;
                }
                $goods_list = $this->format_purgoods($v, $cartlist[$v['suppliers_id']]['promot_list'][$v['cart_id']]['promot_info']['is_limit_time']);



                $cartlist[$v['suppliers_id']]['promot_list'][$v['cart_id']]['goods_list'][] = $goods_list;
                $cartlist[$v['suppliers_id']]['promot_list'][$v['cart_id']]['promot_info']['goods_count'] = intval($cartlist[$v['suppliers_id']]['promot_list'][$v['cart_id']]['promot_info']['goods_count']) + 1;
                if (!empty($goods_list['promot_list']['list'])) $promot_lists = array_merge($promot_lists, $goods_list['promot_list']['list']);
                $suppliergoods[$v['suppliers_id']]['goods_ids'][] = $v['goods_id'];
                $suppliergoods[$v['suppliers_id']]['goods_total_price'] += $v['shop_price'] * $v['goods_num'];
            }
        }
        //在上面的循环中没有办法传供货商下所有商品的id，因此将优惠券写到这里
        foreach ($suppliergoods as $ke => $va) {
//            $cartlist[$ke]['shop_info']['goods_num']=array_sum($va['goods_ids']);
            $cartlist[$ke]['shop_info']['allgoods_price'] = $cartlist[$ke]['shop_info']['allgoods_weight'] = 0;
            foreach ($cartlist[$ke]['promot_list'] as $ck => $cv) {
                $prices = $demo_prices = 0;
                foreach ($cv['goods_list'] as $cgk => $cgv) {
                    $prices += $cgv['shop_price'] * $cgv['goods_num'];
                    $cartlist[$ke]['shop_info']['allgoods_weight'] += $cgv['goods_weight'] * $cgv['goods_num'];
                }
                $cartlist[$ke]['promot_list'][$ck]['promot_info']['orig_prices'] = $orig_prices = $prices;
                $promot_info = $cv['promot_info'];
//                if(!empty($promot_info['id']))$promot_lists=array_merge($promot_lists,array($promot_info['id']=>$promot_info));
                if ($prices >= $promot_info['min_amount']) {
                    if ($promot_info['act_type'] == 1) {
                        if ($promot_info['is_addup'] == 1) {
                            if (!empty($promot_info['max_amount']) && $prices >= $promot_info['max_amount']) {
                                $demo_prices = $promot_info['max_amount'];
                            }
                            if($promot_info['max_amount']==0){
                                $demo_prices=$prices;
                            }
                            if ($promot_info['min_amount'] > 0) $prices = $prices - (floor($demo_prices / $promot_info['min_amount']) * $promot_info['act_type_ext']);
                        } else {
                            $prices = $prices - $promot_info['act_type_ext'];
                        }
                    } else if ($promot_info['act_type'] == 2) {
                        $prices = $prices * ($promot_info['act_type_ext'] / 100);
                    }
                }
                $cartlist[$ke]['promot_list'][$ck]['promot_info']['orig_prices'] = format_decimal($orig_prices);
                $cartlist[$ke]['promot_list'][$ck]['promot_info']['current_prices'] = format_decimal($prices);
                $cartlist[$ke]['shop_info']['allgoods_price'] += $prices;
                $cartlist[$ke]['shop_info']['shop_total_price'] += $prices;
                $save_prices = $orig_prices - $prices;
                $return['all_save_price'] += $save_prices;
                $cartlist[$ke]['promot_list'][$ck]['promot_info']['save_prices'] = format_decimal($save_prices);
            }
            $return['all_price'] += $cartlist[$ke]['shop_info']['allgoods_price'];
            $allgoods_price = $cartlist[$ke]['shop_info']['allgoods_price'];//供货商下的总金额
            $cartlist[$ke]['shop_info']['shipping_fee_key'] = $cartlist[$ke]['shop_info']['shipping_fee'] = '';
            $cartlist[$ke]['shop_info']['allgoods_price'] = format_decimal($cartlist[$ke]['shop_info']['allgoods_price']);
        }
        foreach ($promot_lists as $key => $val) {
            $promot[$val['id']] = $this->format_promot_carts($val);
        }
        if (!empty($cartlist)) $return['status'] = 1;
        $return['list'] = $cartlist;//店铺所有产品
        $return['shopgoods'] = $suppliergoods;
        $return['all_price'] = format_decimal($return['all_price']);
        $return['all_save_price'] = format_decimal($return['all_save_price']);
        $return['promot_lists_json'] = json_encode($promot);
        return $return;
    }

    /**得到购物车带属性商品的真实信息
     * @param $data购物车数组
     */
    public function get_cart_goods_attr_info($data){
        if(empty($data))return false;
        $goods_ids=array();
        foreach($data as $key=>$val){
            if($val['goods_attr']){
                $goods_ids[]=$val['goods_id'];
            }
        }
        if($goods_ids){
            foreach($goods_ids as $key=>$val){
                $map=array();
                $map['goods_id']=$val;
                $goods_attr_info[$val]=M("GoodsAttrStock")->where($map)->select();
            }
        }
        return $goods_attr_info;
    }
    /**购物车列表
     * @param string $goodsids 商品id
     * @param $is_order 是否是订单 0购物车，1订单
     * @return mixed
     */
    public function cartlist($goods_id='', $cart_ids = '', $is_order = 0,$addre_id=0,$type=3)
    {
        $return = $carts_map = array();
        $return['status'] = $return['all_price'] = $return['all_save_price'] = 0;
        $memberinfo = checkuserauthtype();
        //判断用户是否登录
        if (empty($memberinfo)) {
            if ($is_order == 1) {
                $return['status'] = 2;
                $return['msg'] = '请登录';
                $return['url'] = getjumpurl('JUMP_1');
                return $return;
            } else {
                $ucookieid = cookie('u_cookieid');
                if (empty($ucookieid)) {
                    $return['data'] = '';
                    return $return;
                }
                $carts_map['c.cookie_id'] = $ucookieid;
            }
        } else {
            $carts_map['c.user_id'] = $memberinfo['id'];
        }
        if (!empty($cart_ids)) $carts_map['c.id'] = array('in', $cart_ids);
        $carts_map['cart_type'] = $type;
        if($cart_ids) {
            $carts = M('Cart')->alias('c')->JOIN('LEFT JOIN __GOODS__ g ON g.id=c.goods_id')->where($carts_map)->field('g.*,c.shop_id,c.cart_type,g.id as goods_id,c.id as id,c.user_id,c.cookie_id,c.goods_attr,c.goods_num,c.cart_id,c.shop_price as shop_price,c.price_type,c.actgoodsid,c.is_valid,g.shop_price as goods_shop_price,c.live_anchor_id as live_anchor_id,c.live_history_id as live_history_id')->order('c.shop_id asc')->select();
        }elseif(!empty($goods_id)){
            $info=D("Common/OrderInfo")->buy_now($goods_id,$type);

            if($info['status']<=0){$return['status']=0;$return['msg']=$info['msg'];return $return;}
            $carts=$info['data'];
        }
        $cartlist = $promot_lists = array();
        $orig_total_prices = 0;
        $list = array();
        $goods_attr_info=$this->get_cart_goods_attr_info($carts);
        foreach ($carts as $k => $v) {
            //$v['shop_id'] = session('main_shop_id');
            if (empty($cartlist[$v['shop_id']]['shop_info'])) $cartlist[$v['shop_id']]['shop_info'] = $this->format_goods_shop($v['shop_id'],$addre_id);
            //如果店铺信息还是空的，将不显示店铺下的商品
            if (!empty($cartlist[$v['shop_id']]['shop_info'])) {
                if (empty($cartlist[$v['shop_id']]['promot_list'][$v['cart_id']]['promot_info'])) $cartlist[$v['shop_id']]['promot_list'][$v['cart_id']]['promot_info'] = $this->format_goods_promot($v['cart_id']);
                if (empty($cartlist[$v['shop_id']]['promot_list'][$v['cart_id']]['gift_list'])){
                    $gift_param=array();
                    $gift_param['cart_id']=$v['id'];
                    $gift_param['pro_id']=$v['cart_id'];
                    $cartlist[$v['shop_id']]['promot_list'][$v['cart_id']]['gift_list'] = $this->show_cart_gift($gift_param);
                }
                if($v['cart_id']>0 && $cartlist[$v['shop_id']]['promot_list'][$v['cart_id']]['promot_info']['is_valid']==0){
                    $this->save_cart_isvalid($v['id']);
                    $v['status']=0;
                }
                $goods_list = $this->format_goods($v, $cartlist[$v['shop_id']]['promot_list'][$v['cart_id']]['promot_info']['is_limit_time'],$goods_attr_info);
                $cartlist[$v['shop_id']]['promot_list'][$v['cart_id']]['goods_list'][] = $goods_list;
                $cartlist[$v['shop_id']]['promot_list'][$v['cart_id']]['promot_info']['goods_count'] = intval($cartlist[$v['shop_id']]['promot_list'][$v['cart_id']]['promot_info']['goods_count']) + 1;
                if (!empty($goods_list['promot_list']['list'])) $promot_lists = array_merge($promot_lists, $goods_list['promot_list']['list']);
                $shopgoods[$v['shop_id']]['goods_ids'][] = $v['goods_id'];
                $shopgoods[$v['shop_id']]['goods_total_price'] += $v['shop_price'] * $v['goods_num'];
                $shopgoods[$v['shop_id']]['cart_type'][] = $v['cart_type'];
            }
        }
        //在上面的循环中没有办法传店铺下所有商品的id，因此将活动写到这里
        foreach ($shopgoods as $ke => $va) {
//            $cartlist[$ke]['shop_info']['goods_num']=array_sum($va['goods_ids']);
            $cartlist[$ke]['shop_info']['org_allprice']=$cartlist[$ke]['shop_info']['allgoods_price'] = $cartlist[$ke]['shop_info']['allgoods_weight'] = 0;
            foreach ($cartlist[$ke]['promot_list'] as $ck => $cv) {
                $attr_price=$giftprice = $newprices = $prices = $demo_prices = 0;
                foreach ($cv['goods_list'] as $cgk => $cgv) {
                    $prices += $cgv['shop_price'] * $cgv['goods_num'];//商品总金额
                    $cartlist[$ke]['shop_info']['allgoods_weight'] += $cgv['goods_weight'] * $cgv['goods_num'];
                    $showpro_map=array();
                    $showpro_map['c.id']=$cgv['id'];
                    $attr_price +=$cgv['attr_price'] * $cgv['goods_num'];//原始价格
                }
                $cartlist[$ke]['promot_list'][$ck]['promot_info']['orig_prices'] = $orig_prices = $prices;
                $promot_info = $cv['promot_info'];
//                if(!empty($promot_info['id']))$promot_lists=array_merge($promot_lists,array($promot_info['id']=>$promot_info));
                if ($prices >= $promot_info['min_amount']) {
                    if ($promot_info['act_type'] == 1) {//满减
                        if ($promot_info['is_addup'] == 1) {//叠加
                            if (!empty($promot_info['max_amount']) && $prices >= $promot_info['max_amount']) {
                                $demo_prices = $promot_info['max_amount'];
                            }
                            if($promot_info['max_amount']==0 || $prices < $promot_info['max_amount']){
                                $demo_prices=$prices;
                            }

                            if ($promot_info['min_amount'] > 0) $prices = $prices - (intval($demo_prices / $promot_info['min_amount']) * $promot_info['act_type_ext']);
                        } else {
                            $prices = $prices - $promot_info['act_type_ext'];
                        }
                    } else if ($promot_info['act_type'] == 2) {//满折
                        $prices = $prices * ($promot_info['act_type_ext'] / 100);
                    }elseif($promot_info['act_type']==4 || $promot_info['act_type']==3){//满赠 //加价购
                        $is_showpro=1;
                        if($promot_info['act_type']==3 && $cv['gift_list']){
                            $newprices = $cv['gift_list']['shop_price'];
                        }elseif($promot_info['act_type']==4 && $cv['gift_list']){
                            $newprices = floatval($cv['gift_list']['shop_price']-$cv['gift_list']['all_price']);
                            $giftprice = $cv['gift_list']['all_price'];
                        }
//                        $cartlist[$ke]['promot_list'][$ck]['goods_list'][]=M('Cart')->alias('c')->JOIN('LEFT JOIN __GOODS__ g ON g.id=c.	actgoodsid')->where($showpro_map)->field('g.img,g.goods_name,c.shop_id,c.cart_type,g.id as goods_id,c.id as id,c.user_id,c.cookie_id,c.cart_id')->find();

                    }
                }
                $cartlist[$ke]['promot_list'][$ck]['promot_info']['orig_prices'] = format_decimal($orig_prices);
                $cartlist[$ke]['promot_list'][$ck]['promot_info']['current_prices'] = format_decimal($prices);
                $cartlist[$ke]['promot_list'][$ck]['promot_info']['is_showpro'] = $is_showpro?$is_showpro:0;
                $cartlist[$ke]['shop_info']['allgoods_price'] += $prices;
                $cartlist[$ke]['shop_info']['allgoods_price'] += $giftprice;
                $cartlist[$ke]['shop_info']['giftprice'] += $giftprice;
                $save_prices = $orig_prices - $prices;
                $return['new_save_price']+=$newprices;//满赠 加价购商品优惠金额
                $return['all_save_price'] += $save_prices;//满减满折优惠的金额
                $return['org_allprice'] += $attr_price;//没有任何优惠之前的商品总金额
                $return['org_allprice'] += $cv['gift_list']['shop_price'];//没有任何优惠之前的商品总金额
                $cartlist[$ke]['promot_list'][$ck]['promot_info']['save_prices'] = format_decimal($save_prices);
                $cartlist[$ke]['promot_list'][$ck]['promot_info']['new_save_price'] = format_decimal($newprices);
            }
            $return['all_price'] += $cartlist[$ke]['shop_info']['allgoods_price'];
            $allgoods_price = $cartlist[$ke]['shop_info']['allgoods_price'];//店铺下的总金额

            $cartlist[$ke]['shop_info']['allgoods_price'] = format_decimal($cartlist[$ke]['shop_info']['allgoods_price']);
            $cartlist[$ke]['shop_info']['shop_total_price'] = format_decimal($cartlist[$ke]['shop_info']['allgoods_price']);
            $cartlist[$ke]['shop_info']['giftprice'] = format_decimal($cartlist[$ke]['shop_info']['giftprice']);
        }
        foreach ($promot_lists as $key => $val) {
            $promot[$val['id']] = $this->format_promot_carts($val);
        }
        if (!empty($cartlist)) $return['status'] = 1;
        // echo "<pre>";
        // print_r($cartlist);exit;
        $return['list'] = $cartlist;//店铺所有产品
        $return['shopgoods'] = $shopgoods;
        $return['all_price'] = format_decimal($return['all_price']);
        $return['all_save_price'] = format_decimal($return['all_save_price']);//活动优惠的金额
        $return['promot_lists_json'] = json_encode($promot);
        // echo "<pre>";
        // print_r($return);exit;
        return $return;
    }
    // 购物车失效
    public function save_cart_isvalid($cart_id){
        if(empty($cart_id))return false;
        $map = array();$map['id'] = $cart_id;$map['is_valid'] = 1;
        $save_data = array();$save_data['is_valid'] = 0;
        M('Cart')->where($map)->save($save_data);
    }

    /**
     * 格式化购物车活动用(怕有其他另加的字段或是需要格式化的字段)
     * @param array $val
     * @return array
     */
    public function format_promot_carts($val = array())
    {
        $return = $val;
        return $return;
    }
    /**
     * 格式化购物车供货商
     * @param int $suppliers_id
     * @param int $shop_id
     * @return array
     */
    public function format_goods_supplier($suppliers_id = 0,$shop_id=0)
    {
        $return = $shippingfeewhere = $where = array();
        //判断该地区是否有货
//        if(!$addre_id){
        $address_info=getshopaddress($shop_id);
        if($address_info['district']){
            $area_id=$address_info['district'];
        }elseif($address_info['city']){
            $area_id=$address_info['city'];
        }else{
            $area_id=$address_info['province'];
        }
        $root=D("Common/Cart")->get_area_fees($suppliers_id,$area_id);
        $area_ids=getallparent($root['area_id'],'','Area');
        $area_ids=explode(',',$area_ids);
        $area_ids[]=$root['area_id'];
        $address=rsort($area_ids);
//        }
        $map['id']=$suppliers_id;
        $suppliers = M('Suppliers')->where($map)->field(true)->find();
        if($suppliers_id == 0){
            $return['id'] = $suppliers_id;
            $return['name'] = '官方自营旗舰店';
        }elseif(!empty($suppliers)){
            $return['id'] = $suppliers['id'];
            $return['name'] = $suppliers['name'];
            $return['thumb'] = $suppliers['thumb'];
            $return['status'] = $suppliers['status'];
        }

        return $return;
    }
    /**
     * 格式化购物车店铺
     * @param int $shop_id
     * @return array
     */
    public function format_goods_shop($shop_id = 0,$addre_id=0)
    {
        $return = $shippingfeewhere = $where = array();
        //判断该地区是否有货
        if($addre_id){
            $address_map['id']=$addre_id;
            $memberaddress=M("MemberAddress")->where($address_map)->field('province,city,district')->find();
            $address=array($memberaddress['province'],$memberaddress['city'],$memberaddress['district']);
            rsort($address);
        }else{
            $address_info=checkuseraddress();
            if($address_info['district']){
                $area_id=$address_info['district'];
            }elseif($address_info['city']){
                $area_id=$address_info['city'];
            }else{
                $area_id=$address_info['province'];
            }
            $root=D("Common/Cart")->get_area_fee($shop_id,$area_id);
            $area_ids=getallparent($root['area_id'],'','Area');
            $address=explode(',',$area_ids);
            rsort($address);
        }
        $map=array();
        $map['id']=$shop_id;
        $shop = M('Shops')->where($map)->field(true)->find();
        if ($shop_id == 0) {
            $return['id'] = $shop_id;
            $return['name'] = '官方自营旗舰店';
            $shippingfeewhere['shop_id'] = 0;
            $order = 'id desc';
            $return['shipping_info'] = M('ShippingFee')->where($shippingfeewhere)->order($order)->field(true)->select();
        }elseif (!empty($shop)) {
            $return['id'] = $shop['id'];
            $return['name'] = $shop['name'];
            $return['thumb'] = $shop['thumb'];
            $return['thumb_img'] = $shop['thumb_img'];
            $return['address'] = $shop['address'];
            $return['status'] = $shop['status'];
            $shippingfeewhere['shop_id'] = $shop['id'];
            $order = 'id desc';
            $return['shipping_info'] = M('ShippingFee')->where($shippingfeewhere)->order($order)->field(true)->select();
        }
        if(!empty($return['shipping_info'])) {
            foreach ($address as $val) {
                foreach ($return['shipping_info'] as $k => $v) {
                    if (empty($v)) continue;
                    if (in_array($val, explode(',', $v['area_region']))) {
                        $return['shipping_info']['configure'] = unserialize($v['configure']);return $return;
                    }
                }
            }
        }
        return $return;
    }
    /**
     * 格式化购物车商品
     * @param array $data
     * @param int $is_limit_time 是否是限时促销
     * @return array
     */
    public function format_goods($data = array(), $is_limit_time = 0,$goods_attr_info=array())
    {
        $return = $data;
        $return['goods_attr_format'] = unserialize($data['goods_attr']);
        if($data['status'] == 1 && $data['is_delete'] == 0){
            $return['is_valid'] = 1;
        }else{
            if($data['is_valid'] != 0){
                $this->save_cart_isvalid($data['id']);
            }
            $return['is_valid'] = 0;
        }
        // $return['is_valid'] = ($data['status'] == 1 && $data['is_delete'] == 0) ? 1 : 0;
        if($data['cart_type']!=3){
            if($data['goods_attr']){
                $shops_goods_attr = unserialize($data['goods_attr']);
                $goods_attr=$shops_goods_attr['key'];
                if($goods_attr_info[$data['goods_id']]){
                    foreach($goods_attr_info[$data['goods_id']] as $key=>$val){
                        if($val['attr_key']==$goods_attr){
                            $price_info=D("Common/Takeout")->get_min_price($data['shop_id'],$data['goods_id'],'',$val['attr_key']);
                            $return['attr_price']=$data['attr_price']=$price_info['attr_price'];
                        }
                    }
                }
            }else{
                $price_info=D("Common/Takeout")->get_min_price($data['shop_id'],$data['goods_id']);
                $return['attr_price']=$data['attr_price']=$price_info['goods_price'];
                $goods_attr=0;
            }
            if($data['goods_attr']){
                $attr=$return['goods_attr_format']['key'];
                $map['attr_key']=$attr;
                $stock=M("GoodsAttrStock")->where($map)->getField('stock_cfg');
                $return['goods_number'] =$stock;
            }else{
                $return['goods_number'] = $data['goods_number'];
            }
        }else{
            if($data['goods_attr'] && $data['is_valid'] != 0){
                $shops_goods_attr = unserialize($data['goods_attr']);
                $goods_attr=$shops_goods_attr['key'];
                if($goods_attr_info[$data['goods_id']]){
                    foreach($goods_attr_info[$data['goods_id']] as $key=>$val){
                        if($val['attr_key']==$goods_attr){
                            $price_info=D("Common/Takeout")->get_min_price($data['shop_id'],$data['goods_id'],'',$val['attr_key']);
                            $return['attr_price']=$data['attr_price']=$price_info['attr_price'];
                            if($data['shop_price']!=$price_info['goods_price']){
                                $this->save_cart_isvalid($data['id']);
                                $return['is_valid']=0;
                            }
                        }
                    }
                }
            }else{
                $return['attr_price']=$data['attr_price']=$data['goods_shop_price'];
                $goods_attr=0;
            }
            $goods_number=$this->shopgoodsstock($data['goods_id'],$data['shop_id'],$goods_attr);
            $return['goods_number'] = $goods_number['goods_number'];
        }
        $return['org_allprice']=format_decimal($data['attr_price'] * $data['goods_num']);//没有任何优惠前的商品总价
        $return['all_price'] = format_decimal($data['shop_price'] * $data['goods_num']);
        $return['all_weight'] = $data['goods_weight'] * $data['goods_num'];
        $return['is_limit_time'] = $is_limit_time;
        if((($data['promote_id']>0 && $data['price_type']==3 ))&& $data['is_valid'] != 0){
            $time=NOW_TIME;
            if($data['promote_start_time']>$time || $data['promote_end_time']<$time){
                $this->save_cart_isvalid($data['id']);
                $return['is_valid']=0;
            }
            if($data['promote_id']){
                $map=array();
                $map['id']=$data['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,$data['user_id'],$data['goods_id']);
                $p_num=$data['goods_num']+$p_num;
                if($data['goods_min_number']>0 && $p_num > $data['goods_min_number']){
                    $this->save_cart_isvalid($data['id']);
                    $return['is_valid']=0;
                }
            }
                
            //总限量
            $p_num=D('Common/Takeout')->pro_num($promote_info,$data['id'],$data['goods_id'],1);
            $p_num=$data['goods_num']+$p_num;
            if($data['goods_max_number']>=0 && $p_num>$data['goods_max_number']){
                //$return['info'] = $data['goods_name'].'【已超过总限量，总限量'.$data['goods_max_number'].'】';
                $this->save_cart_isvalid($data['id']);
                $return['is_valid']=0;
            }
        }else{
            if(empty($data['goods_attr']) && $data['is_valid'] != 0){
                $price_info=D("Common/Takeout")->get_min_price($data['shop_id'],$data['goods_id']);
                if(format_decimal($price_info['goods_price'],2,2)!=format_decimal($data['shop_price'],2,2)){
                    $this->save_cart_isvalid($data['id']);
                    $return['is_valid']=0;
                }
            }
        }
        //暂时注释库存
        // if($return['goods_number']<=0 && $data['is_valid'] != 0){
        //     $this->save_cart_isvalid($data['id']);
        //     $return['is_valid']=0;
        // }
        $return['promot_list'] = empty($is_limit_time) ? D('Common/Promot')->goods_to_promot($data['goods_id'],0,$data['cart_type'],$data['shop_id']) : array();
        $return['collect_count'] = 0;
        $return['imgF'] = thumb($data['img'],289,289,'noimg_289x289.png');
        // $return['contract_list']=D('Common/Goods')->get_goods_contract($data['shop_id']);
        $member=checkuserauthtype();
        if($member){
            $map['uid'] = $member['id'];
            $map['goods_id'] = $data['goods_id'];
            $return['collect_count'] = M('GoodsCollect')->where($map)->count();
        }
        $map=array();
        $map['id']=$data['id'];
        $cart_info=M("Cart")->where($map)->field('is_valid,cart_id')->find();
        if($cart_info){
            $return['is_valid']=$cart_info['is_valid'];
        }
        return $return;
    }
    /**
     * 格式化订货购物车商品
     * @param array $data
     * @param int $is_limit_time 是否是限时促销
     * @return array
     */
    public function format_purgoods($data = array(), $is_limit_time = 0)
    {
        $return = $data;
        $return['goods_attr_format'] = unserialize($data['goods_attr']);
        if($data['goods_attr']){

            $attr=$return['goods_attr_format']['key'];
            $map['attr_key']=$attr;
            $stock=M("GoodsAttrStock")->where($map)->getField('stock_cfg');
            $return['goods_number'] =$stock;
        }else{
            $return['goods_number'] = $data['goods_number'];
        }
        if($data['pack_id']){
            $return['moq'] = M('GoodsPackage')->where('id='.$data['pack_id'])->getField('moq');
        }else{
            $return['moq'] = $data['moq'];
        }
        $return['all_price'] = format_decimal($data['shop_price'] * $data['goods_num']);
        $return['all_weight'] = $data['goods_weight'] * $data['goods_num'];
        $return['is_limit_time'] = $is_limit_time;
        $return['is_valid'] = ($data['status'] == 1 && $data['is_delete'] == 0) ? 1 : 0;
        $return['promot_list'] = empty($is_limit_time) ? D('Common/Promot')->purgoods_to_promot($data['goods_id']) : array();
        $return['collect_count'] = 0;
        $return['contract_list']=D('Common/Goods')->get_goods_contract($data['shop_id']);
        $shop_info=session('shops_info');
        if($shop_info){
            $map['uid'] = $shop_info['id'];
            $map['goods_id'] = $data['goods_id'];
            $return['collect_count'] = M('GoodsCollect')->where($map)->count();
        }
        return $return;
    }
    /**
     * 根据活动id找活动信息，并格式化
     * @param int $pro_id
     * @return array
     */
    public function format_goods_promot($pro_id = 0)
    {
        $return = array();
        if (empty($pro_id)) return $return;
        $map=array();
        $map['is_check']=array('elt',1);
        $data = M('PromotAct')->field(true)->where($map)->find($pro_id);
        $return = $data;
        $return['start_time_format'] = time_format($data['start_time'], 'Y.m.d');
        $return['end_time_format'] = time_format($data['end_time'], 'Y.m.d');
        $now_time = NOW_TIME;
        $return['is_valid'] = (($data['start_time'] == 0 || $data['start_time'] <= $now_time) && ($data['end_time'] == 0 || $data['end_time'] >= $now_time) && $data['is_online']==1) ? 1 : 0;//是否有效
        if($return['is_valid']==0){
            $memberinfo = checkuserauthtype();
            $map=$is_data=array();
            //$map['id']=$cart_id;
            $map['cart_id']=$pro_id;
            $map['user_id']=$memberinfo['id'];
            $is_data['is_valid']=2;
            M("Cart")->where($map)->save($is_data);
        }
        return $return;
    }
    /**
     * 更换活动
     * @param $cart_id 购物车id
     * @param $pro_id 活动id
     * @return array
     */
    public function change_act($cart_id, $pro_id)
    {
        $return = $map_c = array();
        $return['status'] = 1;
        $memberinfo = checkuserauthtype();
        $map_c = array();
        if (empty($memberinfo)) {
            $ucookieid = cookie('u_cookieid');
            if (empty($ucookieid)) return $return;
            $map_c['cookie_id'] = $ucookieid;
        } else {
            $map_c['user_id'] = $memberinfo['id'];
        }
        $map_c['id'] = $cart_id;
        $arr_num['cart_id'] = $pro_id;
        $add_cart = M('Cart')->where($map_c)->save($arr_num);
        if (empty($add_cart)) $return['status'] = 0;
        return $return;
    }
    /**
     * 删除购物车
     * @param $id 购物车id
     * @return array
     */
    public function del_cart($id)
    {
        $return = $map_c = array();
        $return['status'] = 1;
        $memberinfo = checkuserauthtype();
        $map_c = array();
        if (empty($memberinfo)) {
            $ucookieid = cookie('u_cookieid');
            if (empty($ucookieid)) return $return;
            $map_c['cookie_id'] = $ucookieid;
        } else {
            $map_c['user_id'] = $memberinfo['id'];
        }
        $map_c['id'] = array('in',$id);
        $add_cart = M('Cart')->where($map_c)->delete();
        if (empty($add_cart)) $return['status'] = 0;
        return $return;
    }
    /**
     * 删除订货购物车
     * @param $id 购物车id
     * @return array
     */
    public function del_purcart($id)
    {
        $return = $map_c = array();
        $return['status'] = 1;
        $shops_info = session('shops_info');
        $map_c = array();
        $map_c['user_id'] = $shops_info['shop_id'];
        $map_c['id'] = array('in',$id);
        $add_cart = M('Cart')->where($map_c)->delete();
        if (empty($add_cart)) $return['status'] = 0;
        return $return;
    }
    /**提交购物车
     * @param array $cart_id 购物车id 数组
     * @param $number 数量  （格式为：['cart_id']=>$number）
     */
    public function sub_cart($cart_id = array(), $number)
    {
        $memberinfo = checkuserauthtype();
        $root = $map = $cart_map = array();
        if (empty($memberinfo)) {
            $root['status'] = 2;
            $root['msg'] = '您没登录，请登录';
            $root['url'] = getjumpurl('JUMP_1');
            return $root;
        } else {
            if (!empty($cart_id)) {
                asort($cart_id);
                $cart_ids = implode(",", $cart_id);
                $map['id'] = array("in", $cart_id);
                $cart_info = M("Cart")->field(true)->where($map)->select();
                foreach ($cart_info as $key => $val) {
                    $id = intval($val['id']);
                    $num = intval($number[$id]);
                    $gooda_attrs = unserialize($val['goods_attr']);
                    $gooda_attrs_values = array_values($gooda_attrs);
                    $data = $this->check_cart($val['goods_id'], $gooda_attrs_values[0], $num, $gooda_attrs_values[1],0,$val['cart_type']);
                    if($val['cart_type']==3){
                        $type=14;
                    }else{
                        $type=0;
                    }
                    if ($data['status'] == 0 || $data['status'] == 1) {
                        $root['status'] = 0;
                        $root['msg'] = $data['msg'];
                        $root['url'] = $data['url'];
                        return $root;
                    } else {
                        //修改商品数量
                        $cart_data['goods_num'] = $num;
                        $cart_map['id'] = $id;
                        M("Cart")->where($cart_map)->save($cart_data);
                    }

                }
                $root['status'] = 1;
                if($type==14){
                    $root['url'] = U("Order/index", array('ids' => $cart_ids,'type'=>$type));
                }else{
                    $root['url'] = U("Order/index", array('ids' => $cart_ids));
                }
            } else {
                $root['status'] = 0;
                $root['msg'] = '没有要结算的商品';
            }
        }
        return $root;
    }
    /**提交订货购物车
    * @param array $cart_id 购物车id 数组
    * @param $number 数量  （格式为：['cart_id']=>$number）
    */
    public function sub_pcart($cart_id = array(), $number)
    {
        $shop_info = checkuserauthtype(2);
        $root = $map = $cart_map = array();
        if (empty($shop_info)) {
            $root['status'] = 2;
            $root['msg'] = '您没登录，请登录';
            $root['url'] = getjumpurl('JUMP_8');
            return $root;
        } else {
            if (!empty($cart_id)) {
                asort($cart_id);
                $cart_ids = implode(",", $cart_id);
                $map['id'] = array("in", $cart_id);
                $cart_info = M("Cart")->field(true)->where($map)->select();
                foreach ($cart_info as $key => $val) {
                    $id = intval($val['id']);
                    $num = intval($number[$id]);
                    $gooda_attrs = unserialize($val['goods_attr']);
                    $gooda_attrs_values = array_values($gooda_attrs);
                    if(C('IS_WAREHOUSE')==1){// 判断该商品是否在配送范围
                        $data = $this->check_carts($val['goods_id'], $gooda_attrs_values[0], $num, $gooda_attrs_values[1],'',$val['pack_id']);
                    }else{
                        $data = $this->check_cart($val['goods_id'], $gooda_attrs_values[0], $num, $gooda_attrs_values[1],'',2,$val['pack_id']);
                    }

                    if ($data['status'] == 0 || $data['status'] == 1) {
                        $root['status'] = 0;
                        if($data['attr_kucun'] == 2){
                            $goods_name = idtoname($val['goods_id'],'Goods','goods_name','id',false);
                            $root['msg'] = $goods_name.$gooda_attrs_values[1].$data['msg'];
                        }else{
                            $root['msg'] = $data['msg'];
                        }
                        $root['url'] = $data['url'];
                        return $root;
                    } else {
                        //修改商品数量
                        $cart_data['goods_num'] = $num;
                        $cart_map['id'] = $id;
                        M("Cart")->where($cart_map)->save($cart_data);
                    }
                }
                $root['status'] = 1;
                $root['url'] = U("PurOrder/index", array('ids' => $cart_ids));
            } else {
                $root['status'] = 0;
                $root['msg'] = '没有要结算的商品';
            }
        }
        return $root;
    }
    /**计算运费
    * @param $allgoods_price 店铺商品总金额
    * @param $cartlist店铺商品列表
    * @param $config 店铺运费配置
    */
    public function shipping_fee($allgoods_price, $cartlist, $config)
    {
        if (empty($allgoods_price) || empty($cartlist)) return false;
        if ($allgoods_price >= $config['money']) return 0.00;
        $num = $weight = array();
        foreach ($cartlist as $k => $val) {
            foreach ($val['goods_list'] as $key => $gv) {
                if ($gv['is_shipping'] > 0) continue;
                $num[] = $gv['goods_num'];
                $weight[] = $gv['goods_weight'];
            }
            if($val['gift_list']){
                $num[] = 1;
                $weight[] = $val['gift_list']['goods_weight'];
            }
        }
        $totalnum = array_sum($num);
        $totalweight = array_sum($weight);
        if ($config['type'] == 2) {
            if($totalnum <= $config['first_weight']){
                return $config['first_weight_money'];
            }else{
                return $config['first_weight_money']+ceil(($totalnum-$config['first_weight'])/$config['x_weight'])*$config['x_weight_money'];
            }
        } else {
            $first_weight = $totalweight - $config['first_weight'];
            if ($first_weight <= 0) {
                return $config['first_weight_money'];
            } else {
                return $config['first_weight_money'] + ceil(($totalweight - $config['first_weight']) / $config['x_weight']) * $config['x_weight_money'];
            }
        }
    }
    /**
     * 判断该地区是否配送
     * @param int $shop_id 商户id
     * @param int $area_id 地区id
     * @return array('area_id'=>0,'is_stock'=>0否1是)
     */
    public function get_area_fee($shop_id=0,$area_id=0){
        $root=array('area_id'=>0,'is_stock'=>0);
        $shop_shipping_area=S("shop_shipping_fee_catch".$shop_id);
        if($shop_shipping_area){
            if (in_array($area_id, $shop_shipping_area)) {
                $root['is_stock'] = 1;
                $root['area_id'] = $area_id;
            } else {$root['is_stock'] = 0;}
        }else {
            $map['shop_id'] = $shop_id;
            $shop_shipinfo = M("ShippingFee")->where($map)->getField('area_region', true);
            $area_ids =array_unique(array_filter(explode(',',implode(',',$shop_shipinfo))));
            $alldata = array();
            if ($shop_shipinfo) {
                $map=array();
                $map['status']=1;
                $map['id']=array('in',$area_ids);
                $area_info=M('Area')->where($map)->field('id,pid,name')->cache(true)->select();
                foreach ($area_info as $k => $va) {
                    $areadata = getallson($va['id'],'Area');
                    foreach($areadata as $key=>$val){
                        array_push($alldata,$val);
                    }
                }
                if(in_array($area_id, $alldata)){
                    $root['is_stock'] = 1;
                    $root['area_id'] = $area_id;
                } else {
                    $root['is_stock'] = 0;
                }
                $shop_area = $alldata;
                S("shop_shipping_fee_catch".$shop_id, $shop_area,3600);
            }
        }
        return $root;
    }
    /**
     * 判断该供货商是否配送该地区
     * @param int $suppliers_id 供货商id
     * @param int $area_id 地区id
     * @return array('area_id'=>0,'is_stock'=>0否1是)
     */
    public function get_area_fees($suppliers_id=0,$area_id=0){
        $root=array('area_id'=>0,'is_stock'=>0);
        $sup_shipping_area=S("sup_shipping_fee_catch".$suppliers_id);
        if($sup_shipping_area){
            if (in_array($area_id, $sup_shipping_area)) {
                $root['is_stock'] = 1;
                $root['area_id'] = $area_id;
            } else {$root['is_stock'] = 0;}
        }else {
            $map['id'] = $suppliers_id;
            $sup_shipinfo = M("Suppliers")->where($map)->getField('areas', true);
            $area_ids =array_unique(array_filter(explode(',',implode(',',$sup_shipinfo))));
            $alldata = array();
            if ($sup_shipinfo) {
                if($area_ids){
                     $map=array();
                    $map['status']=1;
                    $map['id']=array('like',$area_ids);
                    $area_info=M('Area')->where($map)->field('id,pid,name')->cache(true)->select();
                    foreach ($area_info as $k => $va) {
                        $areadata = getallson($va['id'],'Area');
                        foreach($areadata as $key=>$val){
                            array_push($alldata,$val);
                        }
                    }
                    if(in_array($area_id, $alldata)){
                        $root['is_stock'] = 1;
                        $root['area_id'] = $area_id;
                    } else {
                        $root['is_stock'] = 0;
                    }
                }else{
                    $root['is_stock'] = 1;
                    $root['area_id'] = $area_id;
                }

                $shop_area = $alldata;
                S("sup_shipping_area".$suppliers_id, $shop_area,3600);
            }
        }
        return $root;
    }
//    获取外卖商品的库存
    public function shopgoodsstock($goodsid,$shop_id,$attr_key=0){
        $sale_type=idtoname($goodsid,'Goods','sale_type','id',false);
        $attr_key=$attr_key?$attr_key:0;
        $return=array();
        // zjn -----3-29----
        if(!$shop_id){//无门店 根据ip获取门店
            $shop_infos = D('Wxsmall/Login')->setshopid();
            $shop_id = $shop_infos['bind_shop_id'];
        }
        $return['info']='库存不足';
        // $info=unserialize(getconfig('PRO_GOODS'));
        // $goods_ids=implode(',',unserialize($info['temp']));
        // if(strpos($goodsid,$goods_ids) == false){//是否是晋升商品
        $offline=idtoname($goodsid,'Goods','is_offline','id',false);//是否是线上商品
        if($offline==1){
            $param=I('param.');
            // if(!$param['lshop_id'] && !cookie('lshop_id') && getconfig('REGISTERBUY_OPEN')==0){//不开放购物 并且不是等级会员
                // $return['info']='请先晋升等级在购买';
                // $return['url']=U('Mobile/pro_level/index');
                // return $return;
            // }
        }
        // ---end----
        if($sale_type==1){
            $map=array();
            $map['goodsid']=$goodsid;
            $list = M('GroupGoods')->where($map)->field('linkid,attr_key,ratio')->select();
            foreach($list as $k=>$v){
                $map=array();
                $map['goods_id'] = $v['linkid'];
                $map['shop_id'] = $shop_id;
                $attr_key=explode('-',$v['attr_key']);
                if($attr_key[1]){
                    $map['goods_stock'] = $attr_key[1];
                }
                $map['status'] = 1;
                $goods_number=floatval(M('ShopsGoodsStock')->where($map)->sum('goods_number'));
                $biggoods_number=$this->big_unit($v['linkid'],$shop_id,$attr_key[1]);
                $goods_number=$goods_number+$biggoods_number;
                $goods_number=floatval($goods_number);
                $goodsnum[]=floatval(format_decimal($goods_number/$v['ratio'],3));
            }
            $return['goods_number'] = min($goodsnum);
        }else{
            $map=array();
            $map['goods_id']=$goodsid;
            if($attr_key){
                $map['goods_stock']=$attr_key;
            }
            $map['shop_id']=$shop_id;
            $map['status']=1;
            $goodsnum = floatval(M('ShopsGoodsStock')->where($map)->sum('goods_number'));
            $biggoods_number = $this->big_unit($goodsid,$shop_id,$attr_key);
            $return['goods_number']=$goodsnum+$biggoods_number;
        }
        return $return;
    }
//    获取组合商品的结算价
    public function groupprice($goodsid,$shop_id){
        $map=array();
        $map['goodsid']=$goodsid;
        $list = M('GroupGoods')->where($map)->field('linkid,ratio')->select();
        $price=0;
        foreach($list as $k=>$v){
            $map_sg=array();
            $map_sg['goods_id']=$v['linkid'];
            $map_sg['shop_id']=$shop_id;
            $supply_price=M('ShopsGoods')->where($map_sg)->getField('avg_price');
            if(!$supply_price){
                $supply_price=idtoname($v['linkid'],'Goods','supply_price','id','false');
            }
            $price+=floatval($supply_price)*$v['ratio'];
        }
        $return['supply_price']=$price;
        return $return;
    }

    /**获取加价购的商品
     * @param $data=array('cart_ids','pro_id');
     * @return array
     */
    public function change_pro_goods($data){
        $return=array();
        if(empty($data)){
            $return['stauts']=3;
            $return['msg']='参数错误';
            return $return;
        }
        if($data['cart_ids']){
            $cart_ids=explode('_',$data['cart_ids']);
        }
        $map=array();
        $map['id']=array('in',$cart_ids);
        $cart_info=M("Cart")->where($map)->field('sum(shop_price*goods_num) as total_price,actgoodsid')->find();
        if($cart_info['actgoodsid']){
            if(stripos($cart_info['actgoodsid'],'-')){
                $act_id=explode('-',$cart_info['actgoodsid']);
                $return['data']['gift_id']=$act_id[0];
            }else{
                $return['data']['gift_id']=$cart_info['actgoodsid'];
            }
        }
        $map=array();
        $map['id']=$data['pro_id'];
        $pro_info=M("PromotAct")->where($map)->field('act_good_ids,min_amount,act_type_ext')->find();
        if($cart_info['total_price']>=$pro_info['min_amount']){
            $goods_ids=$pro_info['act_good_ids'];
            if($goods_ids){
                $shop_id=get_wxsmall_shop_id();
                if(stripos($goods_ids,'-')){
                    $goods_ids=array_filter(explode(',',$goods_ids));
                    foreach($goods_ids as $key=>$val){
                        if(stripos($val,'-')){
                            $ids[$key]=explode('-',$val);
                        }else{
                            $ids[$key]=array(0=>$val);
                        }
                    }
                    foreach($ids as $key=>$val){
                        $map=array();
                        $map['shop_id']=$shop_id;
                        $map['status']=1;
                        $map['goods_id']=$val[0];
                        $map['goods_stock']=$val[1];
                        $goods_info[]=M("ShopsGoodsStock")->where($map)->field(true)->find();
                    }
                }else{
                    $goods_ids=array_filter(explode(',',$goods_ids));
                    $map=array();
                    $map['goods_id']=array('in',$goods_ids);
                    $map['shop_id']=$shop_id;
                    $map['status']=1;
                    $goods_info=M("ShopsGoodsStock")->where($map)->field(true)->select();
                }
                foreach($goods_info as $key=>$val){
                    $goods_param=array();
                    $goods_param['goods_id']=$val['goods_id'];
                    $goods_param['goods_stock']=$val['goods_stock'];
                    $is_stock=$this->check_pro_goods($goods_param);
                    $map=array();
                    $map['id']=$val['goods_id'];
                    $goods_data=M("Goods")->where($map)->field(true)->find();
                    $goods_info[$key]['img']=thumb($goods_data['img']);
                    $goods_info[$key]['goods_name']=$goods_data['goods_name'];
                    $goods_info[$key]['all_price']=$pro_info['act_type_ext'];
                    $goods_info[$key]['goods_attr']=$val['goods_stock'];
                    $goods_info[$key]['goods_attr_format']=D("Common/GoodsAttr")->goods_to_attrname($val['goods_stock']);
                    if($is_stock['status']==3){
                        unset($val);
                    }
                }
                $return['status']=1;
                $return['data']['goods_info']=$goods_info;
                return $return;
            }
        }else{
            $return['status']=3;
            $return['msg']='不满足活动';
            return $return;
        }
        return $return;
    }

    /**验证加价购商品库存
     * @param $data=array('goods_id'=>goods_id,'shop_id'=>shop_id)
     */
    public function check_pro_goods($data){
        $return=array('status'=>1);
        $shop_id=get_wxsmall_shop_id();
        if(empty($data) || empty($data['goods_id']) ||empty($shop_id)){
            $return['status']=3;
            $return['msg']='参数错误2';
            return $return;
        }
        $map=array();
        $map['goods_id']=$data['goods_id'];
        if($data['goods_stock']){
            $map['goods_stock']=$data['goods_stock'];
        }
        $map['shop_id']=$shop_id;
        $map['status']=1;
        $goods_count=M("ShopsGoodsStock")->where($map)->getField('goods_number');
        if($goods_count<=0){
            $return['status']=3;
            $return['msg']='库存不足';
            return $return;
        }
        return $return;
    }

    /**更新赠品
     * @param $data=array('cart_ids'=>购物车id，
     *                      'id'=>赠品id,
     *                       'goods_attr'=>属性，
     *                      ‘pro_id’=>活动id
     * )
     * @return array
     */
    public function add_pro_goods($data){
        $return=array();
        $shop_id=get_wxsmall_shop_id();
        if(empty($data)){
            $return['status']=3;
            $return['msg']='参数错误';
            return $return;
        }
        if(empty($data['user_id'])){
            $return['status']=3;
            $return['msg']='您没登录，请先登录';
            return $return;
        }
        if(empty($data['cart_ids'])){
            $map=array();
            $map['cart_id']=$data['pro_id'];
            $map['user_id']=$data['user_id'];
            $map['shop_id']=$shop_id;
            $data['cart_ids']=M("Cart")->where($map)->getField('id');
        }
        if(empty($data['cart_ids'])){
            $return['status']=3;
            $return['msg']='请先加入购物车';
            return $return;
        }
        //验证活动是否过期，以及是否满足活动
        $map=array();
        $map['id']=$data['pro_id'];
        $map['start_time'] = array('lt',NOW_TIME);
        $map['end_time'] = array('gt',NOW_TIME);
        $promat_info=M("PromotAct")->where($map)->field(true)->find();
        if(empty($promat_info)){
            $return['status']=3;
            $return['msg']='活动失效';
            return $return;
        }
        if(stripos($data['cart_ids'],'_')) {
            $cart_ids = array_filter(explode('_', $data['cart_ids']));
        }else{
            $cart_ids=$data['cart_ids'];
        }
        if(empty($data['id'])){
            $data['id']='';
        }else{//验证赠品库存
            $goods_array=array();
            $goods_array['goods_id']=$data['id'];
            $goods_array['goods_stock']=$data['goods_attr'];
            $rs=$this->check_pro_goods($goods_array);
            if($rs['status']!=1){
                $return['status']=3;
                $return['msg']=$rs['msg'];
                return $return;
            }
        }
        $map=array();

        $map['cart_id']=$data['pro_id'];
        $map['user_id']=$data['user_id'];
        $map['shop_id']=$shop_id;
        $cart_total_price=M("Cart")->where($map)->getField("sum(shop_price*goods_num)");

        if($cart_total_price<$promat_info['min_amount']){
            $data['id']='';
            $return['status']=3;
            $return['msg']='不满足活动条件';
            return $return;
        }
        $map=array();
        $map['cart_id']=$data['pro_id'];
        $map['user_id']=$data['user_id'];
        $map['shop_id']=$shop_id;
        if($data['goods_attr']){
            $gift_id=$data['id'].'-'.$data['goods_attr'];
        }else{
            $gift_id=$data['id'];
        }
        $map['actgoodsid']=$gift_id;
        $cart_count=M("Cart")->where($map)->count();
        if($cart_count>0){
            $return['status']=3;
            $return['msg']='您已经选了此赠品';
            return $return;
        }
        $map=$param=array();
        if($data['goods_attr']){
            $param['actgoodsid']=$data['id'].'-'.$data['goods_attr'];
        }else{
            $param['actgoodsid']=$data['id'];
        }
        if(is_array($cart_ids)){
            $map['id']=array('in',$cart_ids);
        }else{
            $map['id']=$cart_ids;
        }
        $res=M("Cart")->where($map)->save($param);
        if($res){
            $return['status']=1;
            $return['msg']='更新成功';
            if($data['id']) {
                $map = array();
                $map['id'] = $data['id'];
                $gift_goods = M("Goods")->where($map)->field('goods_name,img')->find();
                $gift_goods['img'] = thumb($gift_goods['img']);
                $gift_goods['all_price'] = idtoname($data['pro_id'], 'PromotAct', 'act_type_ext', 'id', false);
                if ($data['goods_attr']) {
                    $gift_goods['goods_attr'] = $data['goods_attr'];
                    $gift_goods['goods_attr_format'] = D("Common/GoodsAttr")->goods_to_attrname($data['goods_attr']);
                }
                $gift_goods['id'] = $data['id'];
            }else{
                $gift_goods='';
            }
            $return['data']['goods_info']=$gift_goods;
            $return['data']['pro_id']=$data['pro_id'];
            return $return;
        }else{
            $return['status']=3;
            $return['msg']='更新失败';
            return $return;
        }
        return $return;
    }

    /**显示购物车里的赠品
     * @param $data=array('cart_id'=>cart_id,'pro_id'=>pro_id)
     */
    public function show_cart_gift($data)
    {
        if (empty($data) || empty($data['cart_id']) || empty($data['pro_id'])) {
            return false;
        }
        $cart_id = $data['cart_id'];
        $pro_id = $data['pro_id'];
        //验证活动
        $map=array();
        $map['id']=$cart_id;
        $cart_info=M("Cart")->where($map)->field('user_id,cookie_id')->find();
        $paramdata=array();
        $paramdata['pro_id']=$data['pro_id'];
        if($cart_info['user_id']){
            $paramdata['user_id']=$cart_info['user_id'];
        }else{
            $paramdata['user_id']=$cart_info['cookie_id'];
        }
        $ischeck=$this->check_manage_cart_activity($paramdata);
        if($ischeck['status']==3)return false;
        $map = array();
        $map['id'] = $cart_id;
        $map['cart_id'] = $pro_id;
        $gift_id = M("Cart")->where($map)->getField('actgoodsid');
        if ($gift_id) {
            if (stripos($gift_id, '-')) {
                $gift_ids = explode('-', $gift_id);
                $map = array();
                $map['id'] = $gift_ids[0];
                $gift_goods = M("Goods")->where($map)->field('goods_name,img,goods_weight,shop_price,unit_id')->find();
                $gift_goods['img'] = thumb($gift_goods['img']);
                $gift_goods['id'] = $gift_ids[0];
                $gift_goods['all_price'] = idtoname($pro_id, 'PromotAct', 'act_type_ext', 'id', false);
                if ($gift_ids[1]) {
                    $gift_goods['goods_attr'] = $gift_ids[1];
                    $gift_goods['goods_attr_format'] = D("Common/GoodsAttr")->goods_to_attrname($gift_ids[1]);
                    $gift_goods['shop_price']=idtoname($gift_ids[1],'GoodsAttrStock','attr_price','attr_key',false);
                }
            } else {
                $map = array();
                $map['id'] = $gift_id;
                $gift_goods = M("Goods")->where($map)->field('goods_name,img,goods_weight,shop_price,unit_id')->find();
                $gift_goods['id'] = $gift_id;
                $gift_goods['all_price'] = idtoname($pro_id, 'PromotAct', 'act_type_ext', 'id', false);
            }
            $gift_goods['unit_name']=idtoname($gift_goods['unit_id'], 'GoodsUnit', 'name', 'id', false);
            $gift_goods['act_id']=$pro_id;
            $gift_goods['act_type'] = idtoname($pro_id, 'PromotAct', 'act_type', 'id', false);
        }
        return $gift_goods;
    }

    /**验证并修改购物车的活动（只针对满赠加价购活动）
     * @param $data=array(
    'pro_id'=>活动id,
     *  'user_id'=>会员ID
     * )
     */
    public function check_manage_cart_activity($data){
        $return=array('status'=>1);
        if(empty($data) || empty($data['pro_id']) || empty($data['user_id'])){
            $return['status']=3;
            $return['msg']='参数错误';
            return $return;
        }
        //验证活动是否过期
        $map=array();
        $map['id']=$data['pro_id'];
        $map['start_time'] = array('lt',NOW_TIME);
        $map['end_time'] = array('gt',NOW_TIME);
        $map['is_online'] = 1;
        $promat_info=M("PromotAct")->where($map)->field(true)->find();
        if(empty($promat_info)){
            $return['status']=3;
            $return['msg']='活动失效';
            return $return;
        }
        $map=array();
        $map['user_id']=$data['user_id'];
        $map['cart_id']=$data['pro_id'];
        $cart_total_price=M("Cart")->where($map)->getField("sum(shop_price*goods_num)");
        if($cart_total_price<$promat_info['min_amount']){
            $param_data=array();
            $param_data['actgoodsid']='';
            $res=M("Cart")->where($map)->save($param_data);
            if($res){
                $return['msg']='修改成功';
                return $return;
            }else{
                $return['status']=3;
                $return['msg']='修改失败';
                return $return;
            }
        }
        return $return;
    }

    /**清空购物车不在配送区域的商品
     * @param $uid会员ID
     */
    public function clear_out_cart($uid){
        $return=array("status"=>3);

        //获取当前定位的店铺
        $shop_id = get_wxsmall_shop_id();
        $map=array();
        $map['id']=$uid;
        $member_info=M("Member")->where($map)->count();
        $ucookieid = cookie('u_cookieid');
        if(empty($member_info) && $ucookieid){
            $return['msg']="登录信息错误";
            return $return;
        }
        $map=array();
        $map['shop_id']=array("neq",$shop_id);
        if($uid){
            $map['user_id']=$uid;
        }elseif($ucookieid){
            $map['cookie_id']=$ucookieid;
        }
        $res=M("Cart")->where($map)->delete();
        if($res){
            $return['status']=1;
            $return['msg']="删除成功";
        }else{
            $return['msg']="删除失败";
        }
        return $return;

    }

    /**判断是否有大单位库存
     * @param $uid会员ID
     */
    public function big_unit($sid,$shop_id,$attr_key){
        $g_map=array();
        $g_map['gp.sid']=$sid;
        $g_map['s.goods_stock']=$attr_key;
        $g_map['s.shop_id']=$shop_id;
        $p_info=M('GoodsPackage')->alias('gp')->where($g_map)->JOIN('LEFT JOIN __SHOPS_GOODS_STOCK__ s ON s.goods_id=gp.pid')->field('s.goods_number,gp.ratio')->find();
        $goods_number=$p_info?($p_info['goods_number']*$p_info['ratio']):0;
        return $goods_number;
    }

}
?>