Giftuser.php 40.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司,并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 2015-11-21
 */

namespace app\mobile\controller;

use app\home\logic\UsersLogic;
use app\home\model\Message;
use think\Cookie;
use think\Page;
use think\Request;
use think\Session;
use think\Verify;
use think\db;
use think\Cache;
use qcloudcos\Conf;
use qcloudcos\Myqcloudcos;


class Giftuser extends MobileBase
{

    public $cartLogic; // 购物车逻辑操作类
    public $user_id = 0;
    public $user = array();
    /**
     * 析构流函数
     */
    public function __construct()
    {
        parent::__construct();
        $this->cartLogic = new \app\home\logic\CartLogic();
        $sid = I('stoid');
        if (session('?user')) {
            $user = session('user');
            $user = M('users')->where("user_id", $user['user_id'])->where("store_id", $sid)->find();
            session('user', $user);  //覆盖session 中的 user
            $this->user = $user;
            $this->user_id = $user['user_id'];
            $this->assign('user', $user); //存储用户信息
        } else {
            $usrid = Cookie::get('user_id');
            if ($usrid) {
                $user = M('users')->where("user_id", $usrid)->where("store_id", $sid)->find();
                session('user', $user);  //覆盖session 中的 user
                $this->user = $user;
                $this->user_id = $user['user_id'];
                $this->assign('user', $user); //存储用户信息
            }
        }

        if (!$this->user_id) {
            $this->redirect(U('mobile/User/login', array('stoid' => getMobileStoId())));
            exit;
        }
        if (($this->pm_erpid && (!$user || !$user['erpvipid'])) || (empty($this->pm_erpid) && !$user || !$user['mobile'])) {
            $this->redirect(U('mobile/User/login', array('stoid' => getMobileStoId())));
            exit;
        }

    }

    //选择赠送单个或多人
    public function senduser()
    {
        //
        return $this->fetch('',getMobileStoId());
    }
    //确认数量
    public function selobject()
    {
        $typeinfo=M('giftuser_type')->where('isshow',1)->order('lb_ordid asc')->select();
        $this->assign('typeinfo',$typeinfo);
        return $this->fetch('',getMobileStoId());
    }

    //分享礼物
    public function sharethegift()
    {
        $return = M('wx_ewmlist')->where(array('store_id' => getMobileStoId(), 'scene_id' => ''))->field('ticket')->find();
        if ($return){
            $ticket=$return['ticket'];
        }
        $this->assign('ticket',$ticket);
        return $this->fetch('',getMobileStoId());
    }

    //确认支付
    public function sumbitpay()
    {

        $killarr=null;
        if ($this->user_id == 0)
            $this->error('请先登录', U('Mobile/User/login', array('stoid' => getMobileStoId())));
        /*--不能重复的一张表--*/
        $userd = $this->user;
        $locking_money = M('withdrawals')->where(array('user_id' => $this->user_id, 'status' => 0))->sum('money');
        $this->assign('u_money', number_format($userd['user_money'] - $userd['frozen_money'] - $locking_money, 2));

        /*--是否是购物车--*/
        $tocart = I("tocart/d", 0);
        $result = null;

        if ($tocart == 0) {
            if ($this->cartLogic->cart_count($this->user_id, 1) == 0)
                $this->error('你的购物车没有选中商品', 'Index/index', array('stoid' => getMobileStoId()));
            $result = $this->cartLogic->cartList_cart2($this->user, $this->session_id, 1, 1); //获取购物车商品
        } else {
            $count = M('Cart')->where(['user_id' => $this->user_id, 'state' => 1])->count();
            if ($count == 0)
                $this->redirect('Index/index', array('stoid' => getMobileStoId()));
            $result = $this->cartLogic->gobuyList_cart2($this->user, $this->session_id); //获取购物车商品
        }

        /*--购物车商品分组--*/
        $cart_goods = $result['cartList'];
        $expty = 2;
        foreach ($cart_goods as $kp => $vp) {
            $exp2=0;
            $cart_goods[$kp]['expty']=2;
        }
        $this->assign("expty", $expty);
        $shippingList = M('store_shipping')->alias('a')->join("shipping b", "a.shipping_id=b.shipping_id")
            ->field('b.shipping_id,b.shipping_code,b.shipping_name,b.shipping_desc,b.shipping_logo')
            ->where("a.status=1 and a.store_id=" . getMobileStoId())->cache("shippingList_" . getMobileStoId(), TPSHOP_CACHE_TIME)
            ->select();//物流公司
        /*--
        if(I('cid') != ''){
            $cid = I('cid');
            $checkconpon = M('coupon')->field('id,name,money')->where("id = $cid")->find();    //要使用的优惠券
            $checkconpon['lid'] = I('lid');
        }--*/

        /*----------购物车商品分组---------*/
        $sql = null;
        if ($tocart == 0) {
            $sql = "select pickup_id,pickup_name from __PREFIX__pick_up where pickup_id in(select pick_id from __PREFIX__cart where user_id=" . $this->user_id . " and selected=1 and state=0 GROUP BY pick_id)";
        } else if ($tocart == 1) {
            $sql = "select pickup_id,pickup_name from __PREFIX__pick_up where pickup_id in(select pick_id from __PREFIX__cart where user_id=" . $this->user_id . " and state=1 GROUP BY pick_id)";
        } else {
            $sql = "select pickup_id,pickup_name from __PREFIX__pick_up where pickup_id in(select pick_id from __PREFIX__cart where user_id=" . $this->user_id . " and state=2 GROUP BY pick_id)";
        }

        //mlog('$tocart:'.$sql,'cart');
        $plist_cart = Db::query($sql);
        foreach ($plist_cart as $k => $v) {
            $isallskill = 1;
            foreach ($cart_goods as $kk => $vv) {if ($vv['pick_id'] == $v['pickup_id']) {$list[] = $vv; }

                if ($vv['prom_type'] != 1){
                    $isallskill = 0;
                }else{
                    $t=time();
                    $fl=M('flash_sale')->where('store_id',getMobileStoId())->where('goods_id',$vv['goods_id'])
                        ->where('start_time<'.$t)->where('end_time>'.$t)->where('is_end',0)
                        ->find();
                    if($fl) {
                        $killarr[] = ['goods_id' => $vv['goods_id'], 'fid' =>$fl['id'],'num'=>$vv['goods_num']];
                    }
                }
            }
            if($killarr){
                $this->assign("killarr", json_encode($killarr));
            }
            $plist_cart[$k]["goods"] = $list;
            $plist_cart[$k]["expty"]=2;
            // 获取订单商品总价,$tocart=0为购物车 1为立即购买
            //$r = $this->cartLogic->my_calculate($list,$this->user_id,$tocart);
            $r = $this->cartLogic->my_calculate_cart2($list, $this->user_id);
            // 找出这个用户的优惠券没过期的 并且订单金额达到condition 优惠券指定标准的
            $fzquan = M('frozen_quan')->where('user_id', $this->user_id)->field('CashRepNo')->select();
            $snow = date("Y-m-d", time());
            //--如果所有商品不全是秒杀且没有优惠商品--
            if($isallskill == 0) {
                //$tk = M("store")->where("store_id", getMobileStoId())->field("api_token")->find();
                //通过缓存拿tk
                $tk = tpCache('shop_info.api_token', getMobileStoId());
                //$user = M("users")->where("user_id",$this->user_id)->field("erpvipid")->find();
                $where = "VIPId='" . $this->user['erpvipid'] . "'";
                $where .= " and IsUse=0 and (ValidDate is null or ValidDate='' or ValidDate>='" . $snow . "')";
                $where .= " and BuySum<=" . $r;
                $where .= " and Sum<=" . $r;
                $order['Sum'] = 'desc';
                //$rs=getApiData("wxderp.cashreplace.list.get",$tk["api_token"],null,$where,1,1000,$order);
                $rs = getApiData("wxderp.cashreplace.list.get", $tk, null, $where, 1, 1000, $order);

                $qlistall = json_decode($rs, true);
                if (!empty($qlistall)) {
                    if ($qlistall['data']) {
                        foreach ($qlistall['data'] as $k1 => $v1) {
                            $qlistall['data'][$k1]['Sum'] = number_format(empty($v1['Sum']) ? 0 : $v1['Sum'], 2);
                            $qlistall['data'][$k1]['BuySum'] = number_format(empty($v1['BuySum']) ? 0 : $v1['BuySum'], 2);
                            $qlistall['data'][$k1]['BillDate'] = date('Y-m-d', strtotime($v1['BillDate']));
                            if (empty($v1['ValidDate'])) {
                                $qlistall['data'][$k1]['ValidDate'] = "不限";
                            } else {
                                $qlistall['data'][$k1]['ValidDate'] = date('Y-m-d', strtotime($v1['ValidDate']));
                            }
                            foreach ($fzquan as $ku => $vu) {
                                if ($qlistall['data'][$k1]['CashRepNo'] == $vu['CashRepNo']) {
                                    unset($qlistall['data'][$k1]);
                                    break;
                                }
                            }
                        }
                    }
                }
                //$couponList = DB::query($sql);
                $plist_cart[$k]["couponList"] = $qlistall['data'];
                unset($qlistall);
            }
            unset($list);
        }

        $this->assign('slist', $plist_cart);
        $this->assign('shippingList', $shippingList); // 物流公司
        //$this->assign('cartList', $result['cartList']); // 购物车的商品
        $this->assign('total_price', $result['total_price']); // 总计
        upload_ylp_log('购物车已选商品显示');
        return $this->fetch('', getMobileStoId());
    }

    //领取提示
    public function togroup()
    {
        //
        $return = M('wx_ewmlist')->where(array('store_id' => getMobileStoId(), 'scene_id' => ''))->field('ticket')->find();
        if ($return)
        {
            $ticket=$return['ticket'];
        }
        $this->assign('ticket',$ticket);
        return $this->fetch('',getMobileStoId());
    }

    public function togiftcardfromgroup()
    {
        $ordno=I('ordno');

        return $this->fetch('',getMobileStoId());
    }

    /**
     * ajax 获取订单商品价格或者提交订单
     */
    public function cart_gift2()
    {
        if(empty($this->redis)){
            //$this->redis=new \Redis();
            //$this->redis->connect(redisip, 6379);
            $this->redis=get_redis_handle();
        }
        $popvalue=null;
        $stoid = I("stoid");

        if ($_REQUEST['act'] == 'submit_order') {
            $sd=I('da');
            if(!empty($sd)){
                $skillarray=json_decode($sd,true);
                foreach ($skillarray as $lk=>$lv){
                    //判断秒杀数量是否超限
                    $name='ms'.$lv['fid'].'-'.$stoid;
                    $num0=$lv['num'];
                    //秒杀队列控制
                    for($i=0;$i<$num0;$i++) {
                        $value = $this->redis->lPop($name);
                        if (empty($value)) {
                            if($popvalue){
                                foreach ($popvalue as $k=>$v)
                                    $this->redis->lPush($name,$v);
                            }
                            return array('status' => -4, 'msg' => "秒杀商品已经抢光", 'result' => '');
                        }
                        $popvalue[]=$value;
                    }
                }
            }
        }
        /*--物流方式--*/
        $exptype = I("exptype/d");
        $state = I("state/d");
        if ($this->user_id == 0)
            exit(json_encode(array('status' => -100, 'msg' => "登录超时请重新登录!", 'result' => null))); // 返回结果状态
        $address_id = I("address_id/d"); //  收货地址id
        $setadd = I("setadd/d");
        $is_skill = I("skill");  //是否是秒杀

        /*--是否是编辑地址--*/
        if ($setadd == 1 && $exptype == 2 && empty($address_id)) {
            $consignee = I("consignee");
            $mobile = I("mobile");
            $province = I("province");
            $city = I("city");
            $district = I("district");
            $twon = I("twon");
            $address = I("address");
            $data = ['consignee' => $consignee,
                'mobile' => $mobile,
                'province' => $province,
                'city' => $city,
                'district' => $district,
                'twon' => $twon,
                'address' => $address,
            ];

            $logic = new UsersLogic();
            $data = $logic->add_address($this->user_id, 0, $data);
            $address_id = $data['result'];
        }

        $shipping_code = I("shipping_code/a"); //  物流编号
        $invoice_title = I('invoice_title/a'); // 发票
        $exparr= I('exparr/a');//获取物流配送数组
        $couponTypeSelect = I("couponTypeSelect"); //  优惠券类型  1 下拉框选择优惠券 2 输入框输入优惠券代码
        $coupon_id = I("coupon_id/a"); //  优惠券id
        $couponCode = I("couponCode"); //  优惠券代码
        $user_note = I('user_note');   //买家留言
        $pay_points = I("pay_points", 0); //  使用积分
        $user_money = I("user_money", 0); //  使用余额
        $user_money = str_replace(',', '', $user_money);
        $user_money = doubleval($user_money);

        //送礼神器关键字段
        $kl_man_num=I('kl_man_num');
        $kl_num=I('kl_num');
        $lb_type=I('lb_type');

        $exptype=0;
        foreach ($exparr as $ko=>$vo){
            if($vo==1){ $exptype=1; break;}
        }

        if($user_money<0)
            exit(json_encode(array('status' => -2, 'msg' => '你的余额不足', 'result' => null))); //返回结果状态
        $result = null;

        if ($state == 0) {
            $result = $this->cartLogic->cartList($this->user, $this->session_id, 1, 1); //获取购物车商品
        } else {
            $result = $this->cartLogic->gobuyList($this->user, $this->session_id); //获取购物车商品
        }
        $cart_goods = $result['cartList'];

        if (empty($cart_goods))
            exit(json_encode(array('status' => -2, 'msg' => '你的购物车没有选中商品', 'result' => null))); //返回结果状态
        $address = M('UserAddress')->where("address_id", $address_id)->find();
        $allusrnum = $user_money;
        $locking_money = M('withdrawals')->where(array('user_id' => $this->user_id, 'status' => 0))->sum('money');

        $userd = $this->user;
        $salerule = tpCache('basic.sales_rules', $stoid);
        $erpid = tpCache('shop_info.ERPId', $stoid);
        $userd['sales_rules'] = $salerule;
        $userd['ERPId'] = $erpid;

        //订单余额判断
        if (!empty($allusrnum)) {
            $ye = $userd['user_money'] - $userd['frozen_money'] - $locking_money;
            if ($ye . '' < $allusrnum) {
                return array('status' => -4,
                    'msg' => "您的可用余额不足", 'result' => '');
            }
        }

        $count_arr = null;
        /*----如果是线下库存,获取线下库存----*/
        if ($userd['sales_rules'] == 2) {
            if ($is_skill != 1) {
                $count_arr = getcountarr($cart_goods, $stoid);
            }
        }

        $err_txt = "";
        $prom_goods = array();

        //建立优惠促销数组
        foreach ($cart_goods as $k => $value) {
            if ($value['prom_type'] == 3 && $value['is_gift'] == 0 && $value['is_collocation'] == 0) {
                $prom_goods[$value['pick_id']][$value['prom_id']]['num'] += $value['goods_num'];
                $prom_goods[$value['pick_id']][$value['prom_id']]['price'] += $value['goods_num'] * $value['goods_price'];
            }
            if ($value['is_gift'] == 1) {
                $prom_goods[$value['pick_id']][$value['prom_id']]['key'] = $k;
            }
        }

        if (!empty($prom_goods)) {
            $prom_info = M('prom_goods')->where(['start_time' => ['lt', time()], 'end_time' => ['gt', time()], 'is_end' => 0])->getfield('id,name');

            foreach ($prom_goods as $kk => $vv) {
                foreach ($vv as $key => $val) {
                    if (!empty($prom_info[$key])) {
                        $prom = discount($val['price'], $key, $val['num'], $this->user_id);
                        if (empty($prom['goods_id']) && !empty($val['key'])) {
                            unset($cart_goods[$val['key']]);
                        }
                        $prom_goods[$kk][$key]['int'] = $prom['int'];
                        $prom_goods[$kk][$key]['coupon'] = $prom['coupon_id'];
                        $prom_goods[$kk][$key]['is_past'] = $prom['is_past'];
                        $prom_goods[$kk][$key]['gift_id'] = $prom['gift_id'];
                        $prom_goods[$kk][$key]['price'] = $prom['price'];
                        $prom_goods[$kk][$key]['all_price'] = $val['price'];
                    } else {
                        return array('status' => -4, 'msg' => "优惠活动已经结束", 'result' => '');
                    }
                }
            }
        }

        /*--预出库库存--*/
        $gidarr=get_arr_column($cart_goods,'goods_id');
        $fgid0=implode(',',$gidarr);
        $strq = 'select pickup_id,goods_id,sum(out_qty) as sum0 from wxd_erp_yqty where goods_id in(' . $fgid0 . ') and store_id='.$stoid.' GROUP BY pickup_id,goods_id';
        $dd = Db::query($strq);
        $ddd = [];
        //---组装数组---
        if ($dd){
            foreach ($dd as $ku => $vu) {
                $ypkid=$vu['pickup_id'];
                $ypgid=$vu['goods_id'];
                $ddd[$ypkid.".".$ypgid]=$vu['sum0'];
            }
        }

        /*--库存判断和活动判断,商品的库存和活动不能过期--*/
        foreach ($cart_goods as $k => $value) {
            $ginfo = $value;
            /*--线下库存的序列key--*/
            $bkey = $value['pick_id'] . $value['goods_id'];
            //商品参与活动查看
            if ($value['prom_type'] > 0 && $value['prom_type'] != 3 && $value['is_collocation'] == 0) {
                /*--修改获取活动的函数--*/
                $prom = get_goods_promotion2($ginfo, null, $this->user_id);
                if ($prom['is_end'] == 1) {
                    return array('status' => -4, 'msg' => "{$ginfo['goods_name']} 此商品活动已经结束", 'result' => '');
                }
                if ($prom['is_end'] == 2) {
                    return array('status' => -4, 'msg' => "{$ginfo['goods_name']} 此商品已经售完", 'result' => '');
                }
                if ($prom['is_end'] == 3) {
                    return array('status' => -4, 'msg' => "{$ginfo['goods_name']} 此活动商品超出限购数量", 'result' => '');
                }
                if ($value['prom_type'] == 1 || $value['prom_type'] == 2 || $value['prom_type'] == 4) {
                    if ($value['goods_num'] > $prom['buy_limit']) {
                        return array('status' => -4, 'msg' => "{$ginfo['goods_name']} 此活动商品超出限购数量", 'result' => '');
                    }
                }
                if ($value['member_goods_price'] != $prom['price']) {
                    $err_txt .= "{$ginfo['goods_name']}商品价格已经变化,是否继续购买!<br>";
                }
                if ($value['prom_type'] == 1 || $value['prom_type'] == 2 || $value['prom_type'] == 4) {
                    if ($value['goods_num'] > $ginfo['store_count']) {
                        return array('status' => -4, 'msg' => "库存不足", 'result' => '');
                    }
                } else {
                    if ($userd['sales_rules'] == 1) {
                        if ($value['goods_num'] > $ginfo['store_count']) {
                            return array('status' => -4, 'msg' => "库存不足", 'result' => '');
                        }
                    } else if ($userd['sales_rules'] == 2) {
                        if (empty($count_arr)) {
                            return array('status' => -4, 'msg' => "库存获取失败", 'result' => '');
                        }
                        /*--预出库判断--*/
                        $ynum=$ddd[$bkey];
                        if($ynum) {
                            if ($value['goods_num']+$ynum > $count_arr[$bkey]) {
                                return array('status' => -4, 'msg' => "库存不足", 'result' => '');
                            }
                        }else{
                            if ($value['goods_num'] > $count_arr[$bkey]) {
                                return array('status' => -4, 'msg' => "库存不足", 'result' => '');
                            }
                        }
                    }
                }
            } else {
                if ($value['is_gift'] == 0) {
                    if ($userd['sales_rules'] == 1) {
                        if ($value['goods_num'] > $ginfo['store_count']) {
                            return array('status' => -4, 'msg' => "库存不足", 'result' => '');
                        }
                    } else if ($userd['sales_rules'] == 2) {
                        if (empty($count_arr)) {
                            return array('status' => -4, 'msg' => "库存获取失败", 'result' => '');
                        }
                        if ($value['goods_num'] > $count_arr[$bkey]) {
                            return array('status' => -4, 'msg' => "库存不足", 'result' => '');
                        }
                    }
                    /*--判断价格是否发生变化 并且不是搭配商品--*/
                    if ($value['member_goods_price'] != $ginfo['shop_price'] && $value['is_collocation'] == 0) {
                        $err_txt .= "{$ginfo['goods_name']} 商品价格已经变化<br>";
                    }
                }
            }
        }
        if ($err_txt != "") {
            return array('status' => -1004, 'msg' => $err_txt, 'result' => '');
        }

        /*--购物车商品分组,生成不同订单--*/
        $plist = null;
        if ($state == 0) {
            $sql = "select pick_id from __PREFIX__cart where user_id=" . $this->user_id . " and selected=1 and state=0 GROUP BY pick_id";
            $plist = Db::query($sql);
            foreach ($plist as $k => $v) {
                $count = array();
                foreach ($cart_goods as $kk => $vv) {
                    if ($v['pick_id'] == $vv['pickup_id']) {
                        $list[] = $vv;
                    }
                    if (!empty($prom_goods[$v['pick_id']]) && $vv['prom_type'] == 3 && $count[$vv['prom_id']] == 0) {
                        $plist[$k]['order']['int'] += $prom_goods[$v['pick_id']][$vv['prom_id']]['int'];
                        $plist[$k]['order']['coupon'][] = $prom_goods[$v['pick_id']][$vv['prom_id']]['coupon'];
                        $plist[$k]['order'][$vv['prom_id']]['gift_id'] = $prom_goods[$vv['pick_id']][$vv['prom_id']]['gift_id'];
                        $plist[$k]['discount'] = $prom_goods[$v['pick_id']];
                        $count[$vv['prom_id']] += 1;
                    }
                }
                $plist[$k]["goods"] = $list;
                unset($list);
            }
        } else {
            $sql1 = "select pick_id from __PREFIX__cart where user_id=" . $this->user_id . " and state=1 GROUP BY pick_id";
            $plist = Db::query($sql1);
            foreach ($plist as $k => $v) {
                $count = array();
                foreach ($cart_goods as $kk => $vv) {
                    if ($v['pick_id'] == $vv['pickup_id']) {
                        $list[] = $vv;
                    }
                    if (!empty($prom_goods[$v['pick_id']]) && $vv['prom_type'] == 3 && $count[$vv['prom_id']] == 0) {
                        $plist[$k]['order']['int'] += $prom_goods[$v['pick_id']][$vv['prom_id']]['int'];
                        $plist[$k]['order']['coupon'][] = $prom_goods[$v['pick_id']][$vv['prom_id']]['coupon'];
                        $plist[$k]['order'][$vv['prom_id']]['gift_id'] = $prom_goods[$vv['pick_id']][$vv['prom_id']]['gift_id'];
                        $plist[$k]['discount'] = $prom_goods[$v['pick_id']];
                        $count[$vv['prom_id']] += 1;
                    }
                }
                $plist[$k]["goods"] = $list;
                unset($list);
            }
        }
        /*--开始生成多单--*/
        $pno = "";
        if (count($plist) > 1) $pno = 'g_'.$userd['ERPId'] . date('ymdHis') . get_total_millisecond() . rand(1000, 9999);
        $postFee = 0;$couponFee = 0;$balance = 0;$pointsFee = 0;$payables = 0;$payables1 = 0;$goodsFee = 0;$order_prom_id = 0;$order_prom_amount = 0;

        //启动事务
        Db::startTrans();
        try {
            foreach ($plist as $k => $v) {
                /*--计算订单相关--*/
                $result = calculate_price4($this->user, $v["goods"], $shipping_code[$v['pick_id']], 0, $pay_points, $user_money, $coupon_id[$v['pick_id']], $couponCode, $stoid, $exparr[$v['pick_id']], $v['discount']);

                if ($result['status'] < 0)
                    exit(json_encode($result));
                /*---余额使用---*/
                $user_money = round($user_money - $result['result']['user_money'], 2);
                /*----
                $order_prom = get_order_promotion($result['result']['order_amount'],$stoid);
                $result['result']['order_amount'] = $order_prom['order_amount'];
                $result['result']['order_prom_id'] = $order_prom['order_prom_id'];
                $result['result']['order_prom_amount'] = $order_prom['order_prom_amount'];
                ---*/
                $postFee += $result['result']['shipping_price']; // 物流费
                $couponFee += $result['result']['coupon_price'];// 优惠券
                $balance += $result['result']['user_money']; // 使用用户余额
                $pointsFee += $result['result']['integral_money']; // 积分支付
                $payables += $result['result']['order_amount'];// 应付金额
                $payables1 += $result['result']['order_amount1'];// 应付金额,不包含余额的那部分
                $goodsFee += $result['result']['goods_price'];// 商品价格
                $order_prom_id .= $result['result']['order_prom_id'] . ",";// 订单优惠活动id
                $order_prom_amount += $result['result']['order_prom_amount'] + $result['result']['discount'];// 订单优惠活动优惠了多少钱

                // 提交订单
                if ($_REQUEST['act'] == 'submit_order') {
                    if (!$shipping_code && $exptype == 0) exit(json_encode(array('status' => -4, 'msg' => '请选择物流信息', 'result' => null))); // 返回结果状态
                    if (empty($coupon_id) && !empty($couponCode)) {
                        $coupon_id = M('CouponList')->where("code", $couponCode)->getField('id');
                    }
                    //$iii=$result['result']['user_money'];
                    $car_price0 = array(
                        'postFee' => $result['result']['shipping_price'], // 物流费
                        'couponFee' => $result['result']['coupon_price'], // 优惠券
                        'balance' => $result['result']['user_money'], // 使用用户余额
                        'pointsFee' => $result['result']['integral_money'], // 积分支付
                        'payables' => $result['result']['order_amount'], // 应付金额
                        'payables1' => $result['result']['order_amount1'], // 应付金额
                        'goodsFee' => $result['result']['goods_price'],// 商品价格
                        'order_prom_id' => $result['result']['order_prom_id'], // 订单优惠活动id
                        'order_prom_amount' => $result['result']['order_prom_amount'], // 订单优惠活动优惠了多少钱
                        'discount_amount' => $result['result']['discount'],//优惠、搭配促销优惠的金额
                    );

                    /*--调用生成订单的函数--*/
                    $result = $this->cartLogic->addOrder2($this->user_id, $address_id,
                        $shipping_code[$v['pick_id']], $invoice_title[$v['pick_id']], $car_price0,
                        $v["goods"], $coupon_id[$v['pick_id']], $user_note[$v['pick_id']], $stoid, 0, $pno, $v['pick_id'], $v['order'], $this->user,$kl_man_num,$kl_num,$lb_type,$state ); // 添加订单

                    if($result["status"] != 1) {
                        //如果失败就补回队列
                        $sd=I('da');
                        if(!empty($sd)){
                            $skillarray=json_decode($sd,true);
                            foreach ($skillarray as $lk=>$lv){
                                $name='ms'.$lv['fid'].'-'.$stoid;
                                $num0=$lv['num'];
                                //秒杀队列控制
                                for($i=0;$i<$num0;$i++) {
                                    $this->redis->lPush($name,time().'_'.$i);
                                }
                            }
                        }
                        //如果订单失败要还原数量
                        exit(json_encode($result));
                    }
                    if (empty($pno) && count($plist) == 1) {
                        $pno = $result["result"];
                    }
                }
            }
            //提交订单
            if ($_REQUEST['act'] == 'submit_order') {
                upload_ylp_log('提交订单');
                if ($state == 0) {
                    // 删除购物车中已提交订单商品
                    M('Cart')->where(['user_id' => $this->user_id, 'selected' => 1])->delete();
                    //删除购物车的cookie
                    Cookie::delete("cn");
                    Db::commit();
                    exit(json_encode(array('status' => 1, 'msg' => '提交订单成功', 'result' => $pno, 'payables' => $payables)));
                } else {
                    // 删除cart表中立即购买的商品
                    M('Cart')->where(['user_id' => $this->user_id, 'state' => 1])->delete();
                    Db::commit();
                    exit(json_encode(array('status' => 1, 'msg' => '提交订单成功', 'result' => $pno, 'payables' => $payables)));
                }
            }

        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            if ($_REQUEST['act'] == 'submit_order') {
                //如果失败就补回队列
                $sd=I('da');
                if(!empty($sd)){
                    $skillarray=json_decode($sd,true);
                    foreach ($skillarray as $lk=>$lv){
                        $name='ms'.$lv['fid'].'-'.$stoid;
                        $num0=$lv['num'];
                        //秒杀队列控制
                        for($i=0;$i<$num0;$i++) {
                            $this->redis->lPush($name,time().'_'.$i);
                        }
                    }
                }
            }
            exit(json_encode(array('status' => -1, 'msg' => '提交订单失败')));
        }

        $car_price = array(
            'postFee' => round($postFee, 2), // 物流费
            'couponFee' => round($couponFee, 2), // 优惠券
            'balance' => round($allusrnum - $user_money, 2), // 使用用户余额
            'pointsFee' => round($pointsFee, 2), // 积分支付
            'payables' => round($payables, 2), // 应付金额
            'payables1' => round($payables1, 2), // 应付金额,不包含使用余额的那一部分
            'goodsFee' => round($goodsFee, 2),// 商品价格
            'order_prom_id' => $order_prom_id, // 订单优惠活动id
            'order_prom_amount' => round($order_prom_amount, 2), // 订单优惠活动优惠了多少钱
        );

        $return_arr = array('status' => 1, 'msg' => '计算成功', 'result' => $car_price); // 返回结果状态
        exit(json_encode($return_arr));
    }


    /**
     * ajax 获取订单商品价格
     */
    public function cart_gift2_nosub()
    {
        /*--物流方式--*/
        $exptype = I("exptype/d");
        $stoid = I("stoid");
        $state = I("state/d");
        if ($this->user_id == 0)
            exit(json_encode(array('status' => -100, 'msg' => "登录超时请重新登录!", 'result' => null))); // 返回结果状态
        $address_id = I("address_id/d"); //收货地址id
        $setadd = I("setadd/d");
        $is_skill = I("skill");  //是否是秒杀
        $exparr= I('exparr/a');//获取物流配送数组

        /*--是否是编辑地址--*/
        if ($setadd == 1 && $exptype == 0 && empty($address_id)) {
            $consignee = I("consignee");
            $mobile = I("mobile");
            $province = I("province");
            $city = I("city");
            $district = I("district");
            $twon = I("twon");
            $address = I("address");
            $data = ['consignee' => $consignee,
                'mobile' => $mobile,
                'province' => $province,
                'city' => $city,
                'district' => $district,
                'twon' => $twon,
                'address' => $address,
            ];

            $logic = new UsersLogic();
            $data = $logic->add_address($this->user_id, 0, $data);
            $address_id = $data['result'];
        }
        $shipping_code = I("shipping_code/a"); //  物流编号
        $invoice_title = I('invoice_title/a'); // 发票
        $couponTypeSelect = I("couponTypeSelect"); //  优惠券类型  1 下拉框选择优惠券 2 输入框输入优惠券代码
        $coupon_id = I("coupon_id/a"); //  优惠券id
        $couponCode = I("couponCode"); //  优惠券代码
        $user_note = I('user_note/a');   //买家留言
        $pay_points = I("pay_points", 0); //  使用积分
        $user_money = I("user_money", 0); //  使用余额

        $user_money = str_replace(',', '', $user_money);
        $user_money = doubleval($user_money);

        //if(!empty($user_money))
        //$user_money=number_format($user_money,2);  //使用俩位

        $result = null;
        if ($state == 0) {
            $result = $this->cartLogic->cartList_cart2($this->user, $this->session_id, 1, 1); //获取购物车商品
        } else {
            $result = $this->cartLogic->gobuyList_cart2($this->user, $this->session_id); //获取购物车商品
        }
        $cart_goods = $result['cartList'];
        if (empty($cart_goods))
            exit(json_encode(array('status' => -2, 'msg' => '你的购物车没有选中商品', 'result' => null))); //返回结果状态
        $address = M('UserAddress')->where("address_id", $address_id)->find();
        $allusrnum = $user_money;
        $locking_money = M('withdrawals')->where(array('user_id' => $this->user_id, 'status' => 0))->sum('money');

        $userd = $this->user;
        $salerule = tpCache('basic.sales_rules', $stoid);
        $erpid = tpCache('shop_info.ERPId', $stoid);
        $userd['sales_rules'] = $salerule;
        $userd['ERPId'] = $erpid;

        //订单余额判断
        if (!empty($allusrnum)) {
            $ye = $userd['user_money'] - $userd['frozen_money'] - $locking_money;
            if ($ye . '' < $allusrnum) {
                return array('status' => -4,
                    'msg' => "您的可用余额不足", 'result' => '');
            }
        }

        /*----如果是线下库存,获取线下库存----*/
        $count_arr = null;
        if ($userd['sales_rules'] == 2) {
            if ($is_skill != 1)
                $count_arr = getcountarr($cart_goods, $stoid);
        }
        /*--购物车商品分组,生成不同订单--*/
        $plist = null;
        if ($state == 0) {
            $sql = "select pick_id from __PREFIX__cart where user_id=" . $this->user_id . " and selected=1 and state=0 GROUP BY pick_id";
            $plist = Db::query($sql);
            foreach ($plist as $k => $v) {
                foreach ($cart_goods as $kk => $vv) {
                    if ($v['pick_id'] == $vv['pickup_id']) {
                        $list[] = $vv;
                    }
                }
                $plist[$k]["goods"] = $list;
                unset($list);
            }
        } else {
            $sql1 = "select pick_id from __PREFIX__cart where user_id=" . $this->user_id . " and state=1 GROUP BY pick_id";
            $plist = Db::query($sql1);
            foreach ($plist as $k => $v) {
                foreach ($cart_goods as $kk => $vv) {
                    if ($v['pick_id'] == $vv['pickup_id']) {
                        $list[] = $vv;
                    }
                }
                $plist[$k]["goods"] = $list;
                unset($list);
            }
        }

        /*--开始生成多单--*/
        //$uerp=M('store')->where('store_id',$stoid)->find();
        $pno = "";
        if (count($plist) > 1) $pno = $userd['ERPId'] . date('ymdHis') . get_total_millisecond() . rand(1000, 9999);
        $postFee = 0;$couponFee = 0;$balance = 0;$pointsFee = 0;$payables = 0;$payables1 = 0;$goodsFee = 0;$order_prom_id = 0;$order_prom_amount = 0;
        foreach ($plist as $k => $v) {

            /*--计算订单相关--*/
            $result = calculate_price4($this->user, $v["goods"], $shipping_code[$v['pick_id']], 0, $pay_points, $user_money, $coupon_id[$v['pick_id']], $couponCode, $stoid, $exparr[$v['pick_id']],$v['discount']);
            if ($result['status'] < 0)
                exit(json_encode($result));
            /*---余额使用---*/
            $user_money = round($user_money - $result['result']['user_money'], 2);

            $postFee += $result['result']['shipping_price']; // 物流费
            $couponFee += $result['result']['coupon_price'];// 优惠券
            $balance += $result['result']['user_money']; // 使用用户余额
            $pointsFee += $result['result']['integral_money']; // 积分支付
            $payables += $result['result']['order_amount'];// 应付金额
            $payables1 += $result['result']['order_amount1'];// 应付金额,不包含余额的那部分
            $goodsFee += $result['result']['goods_price'];// 商品价格
            $order_prom_id .= $result['result']['order_prom_id'] . ",";// 订单优惠活动id
            $order_prom_amount += $result['result']['order_prom_amount'] + $result['result']['discount'];;// 订单优惠加优惠促销活动,优惠了多少钱
        }
        $car_price = array(
            'postFee' => round($postFee, 2), // 物流费
            'couponFee' => round($couponFee, 2), // 优惠券
            'balance' => round($allusrnum - $user_money, 2), // 使用用户余额
            'pointsFee' => round($pointsFee, 2), // 积分支付
            'payables' => round($payables, 2), // 应付金额
            'payables1' => round($payables1, 2), // 应付金额,不包含使用余额的那一部分
            'goodsFee' => round($goodsFee, 2),// 商品价格
            'order_prom_id' => $order_prom_id, // 订单优惠活动id
            'order_prom_amount' => round($order_prom_amount, 2), // 订单优惠活动优惠了多少钱
        );

        $return_arr = array('status' => 1, 'msg' => '计算成功', 'result' => $car_price); // 返回结果状态
        exit(json_encode($return_arr));
    }

    //去赠送
    public function to_send(){
        //判断赠送单人,赠送多人
        $ordno=I('ordno');
        $rs=M("giftuser_order")->where('order_sn',$ordno)->find();
        $btn_text="";
        $share_text="";
        $fenx_url="/index.php/Mobile/Giftuser/togiftcardfromgroup/stoid/1/ordno/"+$ordno;
        if($rs){
            $user=M("users")->where('user_id',$rs['user_id'])->find();
            $good=M("giftuser_order_goods")->where('order_sn',$ordno)->select();
            $goodname="";
            foreach ($good as $k=>$v){
                $goodname.='【'.$v['goods_name'].'】'.$v['goods_num'].'份 ';
            }
            if($rs['kl_man_num']>1){
                $btn_text="多人群抢";
                $share_text=$user['nickname']."送大家".$goodname;
                $fenx_url.="/state/more";
            }else{
                $fenx_url.="/state/one";
                $btn_text="赠送单人";
                $share_text=$user['nickname']."送您".$goodname;;
            }
        }

        $this->assign("btn_text",$btn_text);
        $this->assign("fenx_url",$fenx_url);
        $this->assign("share_text",$share_text);
        return $this->fetch('',getMobileStoId());
    }

    //送礼成功
    public function send_success(){
        return $this->fetch('',getMobileStoId());
    }
}