<?php
/**
 * 购物车
 */

defined('InShopNC') or exit('Access Invalid!');

require_once(BASE_ROOT_PATH . '/helper/goods_helper.php');
require_once(BASE_ROOT_PATH . '/helper/activity_helper.php');
require_once(BASE_ROOT_PATH . '/helper/algorithm.php');
require_once(BASE_ROOT_PATH . '/helper/predeposit_helper.php');
require_once (BASE_ROOT_PATH . '/helper/user_session/fcode.php');
require_once (BASE_ROOT_PATH . '/helper/special_helper.php');


class cart_item
{
    private $cart_id;
    private $bl_id;
    private $goods_id;
    private $goods_num;

    public function __construct($cart_id,$bl_id,$goods_id,$goods_num)
    {
        $this->cart_id = intval($cart_id);
        $this->bl_id = intval($bl_id);
        $this->goods_id = intval($goods_id);
        $this->goods_num = intval($goods_num);
    }

    public function is_bl() {
        return $this->bl_id > 0;
    }
    public function format() {
        $cart_item['cart_id']   = $this->cart_id;
        $cart_item['goods_id']  = $this->goods_id;
        $cart_item['bl_id']     = $this->bl_id;
        $cart_item['goods_num'] = $this->goods_num;
        return $cart_item;
    }
    public function goods_ids()
    {
        if($this->is_bl()) {
            return activity_helper::bundling_goods($this->bl_id);
        }
        else {
            return array($this->goods_id);
        }
    }
}

class cartControl extends mobileControl
{
    const db_type = 'db';
    const session_type = 'Session';

    private $mUserFcode;
    private $mFcodeBannerID;

    public function __construct() {
        parent::__construct();
        $this->mUserFcode = null;

        global $config;
        $this->mFcodeBannerID = $config['autosend_fcodes']['cart_spid'];
    }

    public function rate_moneyOp()
    {
        if($_SESSION['is_login'] == 1)
        {
            $pred = new predeposit_helper($_SESSION['member_id']);
            $bonus_rate = $pred->bonus_rate();

            if($bonus_rate != null)
            {
                $rates = $bonus_rate->format();
                $rates_money = [];
                foreach ($rates as $rate => $money) {
                    $item['rate']  = $rate;
                    $item['total'] = $money;
                    $rates_money[] = $item;
                }
            } else {
                $rates_money = null;
            }

            if(empty($rates_money)) {
                $result['bonus_rate'] = null;
            } else {
                $result['bonus_rate'] = $rates_money;
            }
            return self::outsuccess($result);
        }
        else {
            return self::outsuccess(null);
        }
    }

    public function listOp()
    {
        $model_cart	= Model('cart');
        $minest_cartid = intval($_GET['minest_cartid']);
        if($minest_cartid < 0) $minest_cartid = 0;

        $save_type = $this->save_type();
        if($_SESSION['is_login'] == 1)
        {
            $page_size = $this->page_size();
            if($minest_cartid > 0) {
                $condition = array('buyer_id'=>$_SESSION['member_id'],'cart_id' => array('lt',$minest_cartid));
                $left = $model_cart->getCartListCount($condition);
                $has_more = $left > $page_size;

                $total = $model_cart->getCartListCount(array('buyer_id'=>$_SESSION['member_id']));
                $pages = $this->pages($total);
            } else {
                $condition = array('buyer_id'=>$_SESSION['member_id']);
                $total = $model_cart->getCartListCount(array('buyer_id'=>$_SESSION['member_id']));
                $pages = $this->pages($total);
                $has_more = $total > $page_size;
            }
            $cart_list	= $model_cart->listCart($save_type,$condition,$page_size);
        }
        else
        {
            $cart_list	= $model_cart->listCart($save_type);
            $total = count($cart_list);
            $has_more = false;
            $pages = 1;
        }

        $goods_ids = array();
        $cart_infos = array();
        foreach ($cart_list as $item) {
            $cart_item['cart_id'] = intval($item['cart_id']);
            $cart_item['goods_id'] = intval($item['goods_id']);
            $cart_item['bl_id'] = intval($item['bl_id']);
            $cart_item['goods_num'] = intval($item['goods_num']);

            $goods_ids[] = intval($item['goods_id']);
            $cart_infos[] = $cart_item;
        }

        $helper = new goods_helper(false);
        $summaries = $helper->cart_summary($goods_ids,$related_goods);
        $summary_list = $summaries['summary'];
        if(!empty($related_goods)) {
            $related_summary = $helper->cart_summary($related_goods,$x);
            $summary_list = array_merge($summary_list,$related_summary['summary']);
        }

        //有可能购物车中的商品被删除....
        $avables_goods = [];
        foreach ($summary_list as $summay) {
            $avables_goods[] = $summay['goods_id'];
        }

        $err_goods = algorithm::not_in($goods_ids,$avables_goods);
        $cart_infos = $this->remove_err($cart_infos,$err_goods);

        if($minest_cartid == 0) {
            $ret['free_info'] = $this->full_send();
        }

        $ret['cart_count'] = $total;
        $ret['cart_list']  = $cart_infos;
        $ret['summary']  = $summary_list;
        $ret['groupbuy'] = $summaries['groupbuy'];
        $ret['limitime'] = $summaries['limitime'];
        $ret['bundling'] = $summaries['bundling'];
        $ret['mobile_page'] = array('hasmore' => $has_more,'page_total' => $pages);

        return self::outsuccess($ret);
    }

    public function exgoodsOp()
    {
        $mod_fcode = Model('goods_fcode');
        $mobile = session_helper::cur_mobile();
        if(empty($mobile))
        {
            return self::outsuccess(array('special_list' => null,
                'fcodes' => null,
                'summary'  => null,
                'groupbuy' => null,
                'limitime' => null,
                'bundling' => null,
                'mobile_page' => mobile_page(0)));
        }

        $items = $mod_fcode->getFcodeList(['mobile' => session_helper::cur_mobile(), 'usable_time' => array('gt',time()),'fc_state' => 0],
                                          '*','fc_state asc,fc_id asc',$this->page_size());
        $page_count = $mod_fcode->gettotalpage();

        if($this->page_no() == 1)
        {
            if(isset($_SESSION['fcodes'])) {
                unset($_SESSION['fcodes']);
            }
        }

        $fcodes = [];
        $gids = [];

        foreach ($items as $item)
        {
            $fcoder = new fcode\mfcode($item);
            $fcode = $fcoder->format();
            if($fcode != false)
            {
                $gids[] = intval($fcode['goods_id']);
                $fcodes[] = $fcode;
            }
        }

        if(empty($fcodes))
        {
            return self::outsuccess(array('special_list' => null,
                'fcodes' => null,
                'summary'  => null,
                'groupbuy' => null,
                'limitime' => null,
                'bundling' => null,
                'mobile_page' => mobile_page($page_count)));
        }
        else
        {
            if($this->page_no() == 1 && $this->mFcodeBannerID > 0)
            {
                $blocks = special_manager::instance()->special($this->mFcodeBannerID,$unused_gids);
                $items = $this->format($fcodes);
                $blocks = array_merge($blocks,$items);
            }
            else {
                $blocks = $this->format($fcodes);
            }

            $helper = new goods_helper(false);
            $ret = $helper->cart_summary($gids,$related_goods);

            return self::outsuccess(array('special_list' => $blocks,
                'fcodes' => $fcodes,
                'summary'  => $ret['summary'],
                'groupbuy' => $ret['groupbuy'],
                'limitime' => $ret['limitime'],
                'bundling' => $ret['bundling'],
                'mobile_page' => mobile_page($page_count)));
        }
    }

    private function format($fcodes)
    {
        $blocks = [];
        if(!empty($fcodes)) {
            $blocks[] = special_formater::def_divider();
        }

        foreach ($fcodes as $fcode)
        {
            $block = [];
            $block['item_title'] = '';
            $block['item_type'] = 'home1';
            $block['scale'] = 3.224299;

            $item['image'] = '';
            $item['show_type'] = "fcode";
            $item['show_data'] = strval($fcode['fcode_id']);
            $item['type'] = "goods";
            $item['data'] = strval($fcode['goods_id']);;
            $item['title'] = '';

            $block['items'][] = $item;
            $blocks[] = $block;
            $blocks[] = special_formater::def_divider();
        }

        return $blocks;
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    private function remove_err($cart_infos,$err_goods)
    {
        if(empty($err_goods)) return $cart_infos;

        $result = [];
        foreach ($cart_infos as $cart)
        {
            if($cart['bl_id'] > 0) {
                $result[] = $cart;
            }
            else
            {
                if(algorithm::binary_search($err_goods,$cart['goods_id']) == false) {
                    $result[] = $cart;
                }
                else
                {
                    $cart_id = intval($cart['cart_id']);
                    if($cart_id <= 0) continue;

                    $model_cart	= Model('cart');
                    $model_cart->where(['cart_id' => $cart_id])->delete();
                }
            }
        }

        return $result;
    }

    private function full_send()
    {
        $result = [];

        $rules = activity_helper::fullsent_rules();
        foreach ($rules as $rule) {
            $item['title'] = '内买优惠';
            $item['value'] = $rule;
            $result[] = $item;
        }

        $free_ship = activity_helper::free_ship();
        if($free_ship != false) {
            $item['title'] = '全场包邮';
            $item['value'] = $free_ship;
            $result[] = $item;
        }

        $item['title'] = '红包抵扣';
        $item['value'] = "请参考红包抵扣规则，不与其它活动共享，不含运费";
        $result[] = $item;

        return $result;
    }

    public function addexOp()
    {
        $ret = $this->do_add($err,$ext_info);
        if($ret === false) {
            $msg = isset($err['msg']) ? $err['msg'] : '';
            return self::outerr($err['code'],$msg);
        }
        else
        {
            $bl_id    = intval($ext_info['bl_id']);
            $goods_id = intval($ext_info['goods_id']);
            $cart_id  = intval($ext_info['cart_id']);

            $model_cart = Model('cart');
            $save_type = $this->save_type();
            $cart_num  = $model_cart->getCartNum($save_type,array('buyer_id'=>$_SESSION['member_id']));
            $goods_num = $model_cart->getCartItemNum($save_type,$cart_id);
            $item = new cart_item($cart_id,$bl_id,$goods_id,$goods_num);

            $result['cart_count'] = $cart_num;
            $result['cart_list'][] = $item->format();

            $gids = $item->goods_ids();
            if(empty($gids)) {
                $result['summary']  = array();
                $result['groupbuy'] = array();
                $result['limitime'] = array();
                $result['bundling'] = array();
            }
            else
            {
                $helper = new goods_helper(false);
                $summaries = $helper->cart_summary($gids,$related_goods);
                $summary_list = $summaries['summary'];
                if(!empty($related_goods)) {
                    $related_summary = $helper->cart_summary($related_goods,$x);
                    $summary_list = array_merge($summary_list,$related_summary['summary']);
                }

                $result['summary']  = $summary_list;
                $result['groupbuy'] = $summaries['groupbuy'];
                $result['limitime'] = $summaries['limitime'];
                $result['bundling'] = $summaries['bundling'];
            }
            return self::outsuccess($result);
        }
    }

    public function cart_listOp()
    {
        if($_SESSION['is_login'] != 1) {
            return self::outerr(errcode::ErrUnLogin);
        }

        $page = trim($_GET['page']);
        $curpage = trim($_GET['curpage']);
        if (!isset($_GET['page'])) {
            $page = "100";
            $curpage = "1";
            $this->page_size = 100;
        }
        $this->initpage($page, $curpage);

        $model_cart = Model('cart');
        $model_goods = Model('goods');

        $condition  = array('buyer_id' => $_SESSION['member_id']);
        $cart_list  = $model_cart->getCartList($condition, $this->page_size);
        $page_count = $model_cart->gettotalpage();

        $model_cart->cls();
        foreach ($cart_list as $key => $value) {
            $goods_id = $value['goods_id'];
            $goods_promotion = $model_goods->getGoodsInfoAndPromotionById($goods_id);
            $goods_storage = $model_goods->getGoodsStorageById($goods_id);
            $promotion_type = '';
            $promotion_price = '0.00';
            if (!empty($goods_promotion['groupbuy_info'])) {
                $promotion_type = '抢购';
                $promotion_price = $goods_promotion['groupbuy_info']['groupbuy_price'];
            }
            if (!empty($goods_promotion['xianshi_info'])) {
                $promotion_type = '限时折扣';
                $promotion_price = $goods_promotion['xianshi_info']['xianshi_price'];
            }
            $goods_spec = unserialize($goods_promotion['goods_spec']);
            $goods_spec_array = array();

            if(!empty($goods_spec))
            {
                foreach ($goods_spec as $val) {
                    array_push($goods_spec_array, $val);
                }
            }

            $cart_list[$key]['goods_storage'] = $goods_storage;
            $cart_list[$key]['goods_spec'] = implode(',', $goods_spec_array);
            $cart_list[$key]['promotion_type'] = $promotion_type;
            $cart_list[$key]['promotion_price'] = $promotion_price;
            $cart_list[$key]['goods_image_url'] = cthumb($value['goods_image'], $value['store_id']);
            $cart_list[$key]['goods_sum'] = ncPriceFormat($value['goods_price'] * $value['goods_num']);
        }

        self::outsuccess(array('cart_list' => $cart_list, 'mobile_page' => mobile_page($page_count)));
    }

    public function addOp()
    {
        $ret = $this->do_add($err,$ext_info);
        if($ret === false) {
            $msg = isset($err['msg']) ? $err['msg'] : '';
            return self::outerr($err['code'],$msg);
        } else {
            return self::outsuccess($ret);
        }
    }

    public function do_add(&$err,&$ext_info)
    {
        if (is_numeric($_GET['goods_id']) && is_numeric($_POST['quantity']))
        {
            $goods_id = intval($_POST['goods_id']);
            $quantity = intval($_POST['quantity']);

            if ($goods_id <= 0 || $quantity <= 0) {
                $err = array('code' => errcode::ErrInputParam);
                return false;
            }
            $model_goods = Model('goods');
            $logic_buy_1 = Logic('buy_1');
            $goods_info = $model_goods->getGoodsOnlineInfoAndPromotionById($goods_id);
            $logic_buy_1->getGroupbuyInfo($goods_info);
            $logic_buy_1->getXianshiInfo($goods_info, $quantity);

            if(array_key_exists('ifgroupbuy',$goods_info) && $goods_info['ifgroupbuy'] == true)
            {
                if ($_SESSION['is_login'] != 1)
                {
                    $err = array('code' => errcode::ErrAddCart,'msg' => "只能登录后，才能向购物车添加抢购商品.");;
                    return false;
                }
            }

            if(array_key_exists('ifxianshi',$goods_info) && $goods_info['ifxianshi'] == true)
            {
                if ($_SESSION['is_login'] != 1)
                {
                    $err = array('code' => errcode::ErrAddCart,'msg' => "只能登录后，才能向购物车添加限时购商品.");;
                    return false;
                }
            }

            $ret = $this->check_goods($goods_info, $quantity);
            if(is_array($ret)) {
                $err = $ret;
                return false;
            }
            $bl_id = 0;
        }
        elseif (is_numeric($_GET['bl_id']))
        {
            if ($_SESSION['is_login'] != 1) {
                $err = array('code' => errcode::ErrUnLogin);
                return false;
            }
            $bl_id = intval($_GET['bl_id']);
            if ($bl_id <= 0) {
                $err = array('code' => errcode::ErrInputParam);
                return false;
            }

            $model_bl = Model('p_bundling');
            $bl_info = $model_bl->getBundlingInfo(array('bl_id'=>$bl_id));
            if (empty($bl_info) || $bl_info['bl_state'] == '0') {
                $err = array('code' => errcode::ErrBLUnExist);
                return false;
            }

            $bl_goods_list = $model_bl->getBundlingGoodsList(array('bl_id'=>$bl_id));
            $goods_id_array = array();
            $bl_amount = 0;
            foreach ($bl_goods_list as $goods) {
                $goods_id_array[] = $goods['goods_id'];
                $bl_amount += $goods['bl_goods_price'];
            }

            $model_goods = Model('goods');
            $goods_list = $model_goods->getGoodsOnlineListAndPromotionByIdArray($goods_id_array);
            foreach ($goods_list as $goods)
            {
                $err = $this->check_goods($goods,1);
                if($err === true) {
                    continue;
                } else {
                    return false;
                }
            }

            //优惠套装作为一条记录插入购物车，图片取套装内的第一个商品图
            $goods_info    = array();
            $goods_info['store_id']	= $bl_info['store_id'];
            $goods_info['goods_id']	= $goods_list[0]['goods_id'];
            $goods_info['goods_name'] = $bl_info['bl_name'];
            $goods_info['goods_price'] = $bl_amount;
            $goods_info['goods_num']   = 1;
            $goods_info['goods_image'] = $goods_list[0]['goods_image'];
            $goods_info['store_name'] = $bl_info['store_name'];
            $goods_info['bl_id'] = $bl_id;
            $quantity = 1;
            $goods_id = intval($goods_info['goods_id']);
        }
        else
        {
            $err = array('code' => errcode::ErrInputParam);
            return false;
        }
        $save_type = $this->save_type();
        if($_SESSION['member_id']) {
            $goods_info['buyer_id'] = $_SESSION['member_id'];
        }

        $model_cart = Model('cart');
        $insert = $model_cart->addCart($goods_info, $save_type , $quantity);

        if ($insert) {
            $data = array('result' => 1, 'num' => $model_cart->cart_goods_num, 'amount' => ncPriceFormat($model_cart->cart_all_price));
            $ext_info = array('bl_id' => $bl_id,'goods_id' => $goods_id,'cart_id' => $insert);
            return $data;
        } else {
            $err = array('code' => errcode::ErrAddCart);
            return false;
        }
    }

    private function check_goods($goods_info, $quantity)
    {
        if(empty($quantity)) {
            return array('code' => errcode::ErrInputParam, 'msg' => errcode::msg(errcode::ErrInputParam));
        }
        if(empty($goods_info)) {
            return array('code' => errcode::ErrGoodsOff, 'msg'=> '商品已下架或不存在');
        }
        if ($goods_info['store_id'] == $_SESSION['store_id']) {
            return array('code' => errcode::ErrCanNotBuyOwn, 'msg'=> errcode::msg(errcode::ErrCanNotBuyOwn));
        }
        if(intval($goods_info['goods_storage']) < 1) {
            return array('code' => errcode::ErrGoodsOutofStock, 'msg' => errcode::msg(errcode::ErrGoodsOutofStock));
        }
        if(intval($goods_info['goods_storage']) < $quantity) {
            return array('code' => errcode::ErrStorageShort, 'msg' => errcode::msg(errcode::ErrStorageShort));
        }
        if ($goods_info['is_virtual'] || $goods_info['is_presell']) {
            return array('code' => errcode::ErrGoodsSpecial, 'msg' => errcode::msg(errcode::ErrGoodsSpecial));
        }
        $is_fcode = intval($goods_info['is_fcode']) == 1 ? true : false;
        if($is_fcode)
        {
            if(!session_helper::logined()) {
                return array('code' => errcode::ErrLogin, 'msg' => 'F码商品，只有在登录后才能添加到购物车');
            }
            else
            {
                if($this->mUserFcode == null) {
                    $this->mUserFcode = new user_session\fcode();
                    $this->mUserFcode->onStatus();
                }
                $goods_id = intval($goods_info['goods_id']);
                $num = $this->mUserFcode->goods_has_code($goods_id,$lock_num);
                if($num == false)
                {
                    if($lock_num > 0) {
                        return array('code' => errcode::ErrLogin, 'msg' => '等确认收货后该商品的F码才可以使用.');
                    } else {
                        return array('code' => errcode::ErrLogin, 'msg' => '您没有该商品F码，请领取F码后再购买.');
                    }
                }
                elseif($num < $quantity) {
                    return array('code' => errcode::ErrLogin, 'msg' => "该商品F码，只够购买{$num}支.");
                }
            }
        }

        return true;
    }

    public function cart_editOp()
    {
        if($_SESSION['is_login'] != 1) {
            return self::outerr(errcode::ErrUnLogin);
        }

        $cart_list = explode(',', urldecode($_POST['cart_list']));
        $new_cart_list = array();
        if (is_array($cart_list))
        {
            foreach ($cart_list as $value) {
                if (preg_match_all('/^(\d{1,10})\|(\d{1,6})$/', $value, $match)) {
                    if (intval($match[2][0]) > 0) {
                        $new_cart_list[$match[1][0]] = $match[2][0];
                    }
                }
            }

            $model_cart = Model('cart');
            $condition = array('buyer_id' => $_SESSION['member_id']);
            $original_cart_list = $model_cart->listCart(self::db_type, $condition);
            $quantity_error = array();
            foreach ($original_cart_list as $key => $value)
            {
                if (array_key_exists($value['cart_id'], $new_cart_list))
                {
                    $quantity = intval($new_cart_list[$value['cart_id']]);
                    if (intval($value['goods_num']) !== $quantity)
                    {
                        if (!$this->check_goods_storage($value, $quantity)) {
                            array_push($quantity_error, array('cart_id' => $value['cart_id'], 'quantity' => $quantity, 'err_info' => '库存不足'));
                        } else {
                            $data = array();
                            $data['goods_num'] = $quantity;
                            $update = $model_cart->editCart($data, array('cart_id' => $value['cart_id']));
                            if (!$update) {
                                return self::outerr(errcode::ErrCart, '购物车修改失败');
                            }
                        }
                    }
                }
                else
                {
                    $delete = $model_cart->delCart(self::db_type, array('cart_id' => $value['cart_id']));
                    if (!$delete) {
                        return self::outerr(errcode::ErrCart, '购物车修改失败');
                    }
                }
            }

            if (count($quantity_error) > 0) {
                self::outsuccess(array('result' => '0', 'quantity_error' => $quantity_error));
            } else {
                self::outsuccess(array('result' => '1','quantity_error' => NULL));
            }
        }
        else {
            return self::outerr(errcode::ErrCart, '购物车列表格式错误');
        }
    }

    /**
     * 购物车更新商品数量
     */
    public function editOp()
    {
        $cart_id = intval($_POST['cart_id']);
        $quantity = intval($_POST['quantity']);

        if ($cart_id <= 0 || $quantity < 0) {
            return self::outerr(errcode::ErrInputParam);
        }

        if($quantity > 0) {
            $ret = $this->do_edit(intval(abs($cart_id)),intval($quantity));
        }
        else {
            $ret = $this->do_del($cart_id);
        }

        if ($ret === true) {
            $save_type = $this->save_type();
            $mod_cart = Model('cart');
            $cart_num  = $mod_cart->getCartNum($save_type,array('buyer_id'=>$_SESSION['member_id']));
            $goods_num = $mod_cart->getCartItemNum($save_type,$cart_id);

            $result['cart_count'] = $cart_num;
            $result['cart_id'] = $cart_id;
            $result['goods_num'] = $goods_num;

            self::outsuccess($result);
        } else {
            self::outerr(errcode::ErrAddCart,$ret['err_info']);
        }
    }

    public function do_edit($cart_id,$quantity_in)
    {
        $model_cart = Model('cart');
        $model_goods= Model('goods');
        $logic_buy_1 = logic('buy_1');

        $quantity = $quantity_in;

        //存放返回信息
        $cart_info = $model_cart->getCartInfo(array('cart_id'=>$cart_id,'buyer_id'=>$_SESSION['member_id']));
        if ($cart_info['bl_id'] == '0')
        {
            //普通商品
            $goods_id = intval($cart_info['goods_id']);
            $goods_info	= $logic_buy_1->getGoodsOnlineInfo($goods_id,$quantity);
            if(empty($goods_info))
            {
                if($_SESSION['is_login'] == 1) {
                    QueueClient::push('delCart', array('buyer_id'=>$_SESSION['member_id'],'cart_ids'=>array($cart_id)));
                }
                return array('cart_id' => $cart_id, 'quantity' => $quantity, 'err_info' => '商品已被下架');
            }

            $logic_buy_1->getGroupbuyInfo($goods_info);
            $logic_buy_1->getXianshiInfo($goods_info,$quantity);
            $quantity = $goods_info['goods_num'];
            if($quantity == $cart_info['goods_num']) {
                return array('cart_id' => $cart_id, 'quantity' => $quantity, 'err_info' => "该商品只允许抢购{$quantity}件~");
            }
            if(intval($goods_info['goods_storage']) < $quantity) {
                $model_cart->editCart(array('goods_num'=>$goods_info['goods_storage']),array('cart_id'=>$cart_id,'buyer_id'=>$_SESSION['member_id']));
                return array('cart_id' => $cart_id, 'quantity' => $goods_info['goods_storage'], 'err_info' => '库存不足，已将您购物车更新为库存数量.');
            }
        }
        else
        {
            //优惠套装商品
            $model_bl = Model('p_bundling');
            $bl_goods_list = $model_bl->getBundlingGoodsList(array('bl_id'=>$cart_info['bl_id']));
            $goods_id_array = array();
            foreach ($bl_goods_list as $goods) {
                $goods_id_array[] = $goods['goods_id'];
            }
            $goods_list = $model_goods->getGoodsOnlineListAndPromotionByIdArray($goods_id_array);

            //如果其中有商品下架，删除
            if (count($goods_list) != count($goods_id_array)) {
                QueueClient::push('delCart', array('buyer_id'=>$_SESSION['member_id'],'cart_ids'=>array($cart_id)));
                return array('cart_id' => $cart_id, 'quantity' => 0, 'err_info' => '该优惠套装已经无效，建议您购买单个商品.');
            }

            //如果有商品库存不足，更新购买数量到目前最大库存
            foreach ($goods_list as $goods_info)
            {
                if ($quantity > $goods_info['goods_storage']) {
                    $model_cart->editCart(array('goods_num'=>$goods_info['goods_storage']),array('cart_id'=>$cart_id,'buyer_id'=>$_SESSION['member_id']));
                    return array('cart_id' => $cart_id, 'quantity' => $goods_info['goods_storage'], 'err_info' => '该优惠套装部分商品库存不足，建议您降低购买数量或购买库存足够的单个商品.');
                }
            }
            $goods_info['goods_price'] = $cart_info['goods_price'];
        }

        $data = array();
        $data['goods_num'] = $quantity;
        $data['goods_price'] = $goods_info['goods_price'];

        $update = $model_cart->editCart($data,array('cart_id'=>$cart_id,'buyer_id'=>$_SESSION['member_id']));
        if ($update) {
            return true;
        } else {
            return array('cart_id' => $cart_id, 'quantity' => 0, 'err_info' => '更新购物车失败.');
        }
    }

    private function do_del($cart_id)
    {
        $save_type = $this->save_type();
        $model_cart	= Model('cart');
        if ($_SESSION['member_id']) {
            $delete	= $model_cart->delCart($save_type,array('cart_id'=>$cart_id,'buyer_id'=>$_SESSION['member_id']));
            return $delete;
        } else {
            $delete	= $model_cart->delCart($save_type,array('cart_id'=>$cart_id));
            return $delete;
        }
    }

    public function delOp()
    {
        $cart_id = intval($_POST['cart_id']);
        if($cart_id <=0 ) {
            return self::outerr(errcode::ErrInputParam);
        }

        $ret = $this->do_del($cart_id);
        if($ret) {
            return self::outsuccess(array('result' => '1'));
        } else {
            return self::outerr(errcode::ErrCartDelError);
        }
    }

    public function cart_delOp()
    {
        if($_SESSION['is_login'] != 1) {
            return self::outerr(errcode::ErrUnLogin);
        }

        $cart_id = intval($_POST['cart_id']);
        $model_cart = Model('cart');
        if ($cart_id > 0) {
            $condition = array();
            $condition['buyer_id'] = $_SESSION['member_id'];
            $condition['cart_id'] = $cart_id;

            $model_cart->delCart(self::db_type, $condition);
        }

        self::outsuccess(array('result' => '1'));
    }

    private function check_goods_storage($cart_info, $quantity)
    {
        $model_goods = Model('goods');
        $model_bl = Model('p_bundling');
        $logic_buy_1 = Logic('buy_1');

        if ($cart_info['bl_id'] == '0') {
            //普通商品
            $goods_info = $model_goods->getGoodsOnlineInfoAndPromotionById($cart_info['goods_id']);
            $logic_buy_1->getGroupbuyInfo($goods_info);
            $logic_buy_1->getXianshiInfo($goods_info, $quantity);

            if (intval($goods_info['goods_storage']) < $quantity) {
                return false;
            }
        }
        else
        {
            //优惠套装商品
            $bl_goods_list = $model_bl->getBundlingGoodsList(array('bl_id' => $cart_info['bl_id']));
            $goods_id_array = array();
            foreach ($bl_goods_list as $goods) {
                $goods_id_array[] = $goods['goods_id'];
            }
            $bl_goods_list = $model_goods->getGoodsOnlineListAndPromotionByIdArray($goods_id_array);

            //如果有商品库存不足，更新购买数量到目前最大库存
            foreach ($bl_goods_list as $goods_info) {
                if (intval($goods_info['goods_storage']) < $quantity) {
                    return false;
                }
            }
        }
        return true;
    }

    private function save_type()
    {
        if ($_SESSION['is_login'] == 1) {
            $save_type = self::db_type;
        } else {
            $save_type = self::session_type;
        }
        return $save_type;
    }
}
