CartLogic.php 78.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 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司,并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: IT宇宙人
 * Date: 2015-09-09
 */

namespace app\home\logic;

use think\Cookie;
use think\Model;
use think\Db;

/**
 * 购物车 逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class CartLogic extends Model
{
    /**
     * 加入购物车方法
     * @param type $goods_id 商品id
     * @param type $goods_num 商品数量
     * @param type $goods_spec 选择规格
     * @param type $user 用户详细
     */
    function addCart($goods_id, $goods_num, $goods_spec, $session_id, $user = null, $pickup_id = 0, $to_catr = 0, $goods_list = null,$isinte=0,$ispd=0)
    {
        $user_id = $user['user_id'];
        $mz_vip = $user['is_mzvip'];//美妆会员
        $rank_field = $user['card_field'];//等级会员
        $mz_switch = tpCache('shopping.is_beauty',getMobileStoId());//美妆价开关
        $rank_switch = tpCache('shopping.rank_switch',getMobileStoId());//等级开关

        if ($user_id == 0)
            return array('status' => -101, 'msg' => '购买商品必须先登录', 'result' => '');
        if ($goods_num <= 0)
            return array('status' => -2, 'msg' => '购买商品数量不能为0', 'result' => '');
        if (empty($pickup_id)) {
            return array('status' => -2, 'msg' => '取货门店不能为空', 'result' => '');
        }
        $t=time();

        /*查找商品*/
        $goods = M('Goods')
            ->where("on_time<".$t." and (down_time>".$t." or down_time=0)")
            ->where("goods_id", $goods_id)->where('is_on_sale', 1)
            //->cache(true,TPSHOP_CACHE_TIME)
            ->find(); // 找出这个商品
        if (empty($goods))
            return array('status' => -3, 'msg' => '购买商品不存在或者已下架', 'result' => '');

        //购买商品超出限购
        if($goods['viplimited']) {
            $limit = M('order')->alias('a')->join('order_goods b', 'a.order_id=b.order_id')
                ->where(['a.user_id' => $user_id, 'b.goods_id' => $goods_id, 'a.order_status' => [['=', 4], ['<', 3], 'or']])
                ->sum('b.goods_num');

            if ($goods_num + $limit > $goods['viplimited']) {
                return array('status' => -3, 'msg' => '购买商品超出限购', 'result' => '');
            }
        }

        /*--加入购物车是的线下库存判断--*/
        $sale_r = tpCache('basic.sales_rules', getMobileStoId());
        M('Cart')->where("session_id ='" . $session_id . "' or user_id=" . $user_id)->where('state<>0')->delete();

        //判断库存
        $cart_goods_num = M('Cart')->where("goods_id", $goods_id)
            ->where("session_id ='" . $session_id . "' or user_id=" . $user_id)->getField('goods_num');

        $cart_goods_num2 = M('Cart')->where("goods_id", $goods_id)->where('pick_id', $pickup_id)
            ->where("session_id ='" . $session_id . "' or user_id=" . $user_id)->getField('goods_num');

        if ($sale_r == 1) {
            if (($cart_goods_num + $goods_num) > $goods['store_count']) {
                return array('status' => -4, 'msg' => "库存不足", 'result' => '');
            }
        } else {
            if ($goods['prom_type'] == 3 || $goods['prom_type'] == 0 || $isinte==1) {
                $count1 = getpickwarecount($goods_id, $pickup_id, getMobileStoId());
                $strq = 'select sum(out_qty) as sum0 from __PREFIX__erp_yqty where goods_id='.$goods_id.' and pickup_id='.$pickup_id;
                $dd = Db::query($strq);
                $ddd = 0;
                //-----预出库-----
                if ($dd){
                    $ddd=$dd[0]['sum0'];$count1=$count1-$ddd;
                }

                if ($count1 == -1) {
                    return array('status' => -4, 'msg' => "获取库存失败", 'result' => '');
                } else {
                    if (($cart_goods_num2 + $goods_num) > $count1) {
                        return array('status' => -4, 'msg' => "库存不足", 'result' => '');
                    }
                }
            } else {
                if (($cart_goods_num + $goods_num) > $goods['store_count']) {
                    return array('status' => -4, 'msg' => "库存不足", 'result' => '');
                }
            }
        }

        mlog("<会员:" . $user_id . ">" . $session_id, "addCart/" . $goods['store_id']);
        $where = " session_id = :session_id ";
        $bind['session_id'] = $session_id;
        $user_id = $user_id ? $user_id : 0;
        if ($user_id) {
            $where .= "  or user_id= :user_id ";
            $bind['user_id'] = $user_id;
        }
        $where .= ' and state=0 and is_gift=0';

        $catr_count = M('Cart')->where($where)->bind($bind)->count(); // 查找购物车商品总数量
        if ($catr_count >= 20 && $to_catr == 0)
            return array('status' => -9, 'msg' => '购物车最多只能放20种商品', 'result' => '');

        $where = " goods_id = :goods_id";
        $cart_bind['goods_id'] = $goods_id;
        if ($user_id > 0) {
            $where .= " and (session_id = :session_id or user_id = :user_id) ";
            $cart_bind['session_id'] = $session_id;
            $cart_bind['user_id'] = $user_id;
        } else {
            $where .= " and  session_id = :session_id ";
            $cart_bind['session_id'] = $session_id;
        }

        $price = $goods['shop_price']; // 如果商品规格没有指定价格则用商品原始价格
        $isset=0;
        if ($mz_vip == 1 && $goods['mz_price'] > 0 && !empty($mz_switch)){
            $price = $goods['mz_price'];
            $isset=1;
        }
        if (!empty($rank_switch)){
            if (!empty($rank_field) && $goods[$rank_field] > 0 && strtotime($user['card_expiredate']) > time()){
                $price = $goods[$rank_field];
            }
            $isset=1;
        }

        //商品参与活动查看
        if ($goods['prom_type'] > 0 && $isinte!=1 && $ispd!=1) {
            if($goods['prom_type']==3){
                $now=time();
                $prominfo = M('prom_goods')->alias('a')
                    ->where('a.store_id', $goods['store_id'])
                    ->where('a.id', $goods['prom_id'])
                    ->where(['a.end_time' => ['gt', $now], 'a.start_time' => ['lt', $now],
                        'a.is_end' => 0])
                    ->field('id,is_bz')
                    ->find();
                if (!empty($prominfo)) {
                    //全场商品
                    $prom = discount($price * $goods_num,
                        $prominfo['id'], $goods_num, $user_id,$prominfo['is_bz']);
                    $goods['prom_type'] = 3;
                    $goods['prom_id'] = $prom['prom_id'];
                    if(empty($isset))
                        $price = $goods['shop_price'];
                }
            }else {
                $prom = get_goods_promotion1($goods, null, $user_id, $goods_num, $goods_list);
                if ($prom['is_end'] != 1 && $prom['is_end'] != 4 && $prom['is_end'] != 2 ) {
                    if ($prom['prom_type'] != 3 && $prom['prom_type']!=5) {
                        $price = $prom['price'];
                    } else {
                        if (empty($isset))
                            $price = $goods['shop_price'];
                    }
                    $goods['prom_type'] = $prom['prom_type'];
                    $goods['prom_id'] = $prom['prom_id'];

                    if (($cart_goods_num + $goods_num) > $goods['store_count']) {
                        return array('status' => -4, 'msg' => "库存不足", 'result' => '');
                    }

                    if ($prom['prom_type'] != 3 && $prom['prom_type'] != 5) {
                        if (($cart_goods_num + $goods_num) > $prom['onlybuy']) {
                            if($cart_goods_num>0)
                                return array('status' => -5, 'msg' => "此商品已在购物车,去购物车结算", 'result' => '');
                            return array('status' => -4, 'msg' => "此商品的活动库存不足", 'result' => '');
                        }
                    }
                    if ($prom['prom_type'] == 1 || $prom['prom_type'] == 4 || $prom['prom_type'] == 2 || $prom['prom_type'] == 6) {
                        if (!empty($prom['buy_limit'])) {
                            $cart_goods_num = M('Cart')->where("goods_id", $goods_id)->where('prom_type', 4)
                                ->where("session_id ='" . $session_id . "' or user_id=" . $user_id)->getField('goods_num');
                            // 如果购买数量(先增数量,购物车中的数量,以前订单中购买的数量) 大于每人限购数量
                            if (($goods_num + $cart_goods_num) > $prom['buy_limit'] && $prom['buy_limit0']>0) {
                                $cart_goods_num && $error_msg = "你当前购物车已有 $cart_goods_num 件,之前订单买 $cart_goods_num 件!";
                                return array('status' => -4, 'msg' => "每人限购 {$prom['buy_limit']}件,$error_msg", 'result' => '');
                            }
                        }
                    }
                } else if ($prom['is_end'] == 2) {
                    return array('status' => -4, 'msg' => "此商品的活动库存不足", 'result' => '');
                } else {
                    $goods['prom_type'] = 0;
                    $goods['prom_id'] = null;

                    $now=time();
                    $w1="(b.goods_listid='' or b.goods_listid is null or locate(',".$goods['goods_id'].",',b.goods_listid)=0)";
                    $prominfo = M('prom_goods')->alias('a')->join('activitylist b','b.act_id=a.id and b.prom_type=3')
                        ->where('a.store_id', $goods['store_id'])->where($w1)
                        ->where(['a.end_time' => ['gt', $now], 'a.start_time' => ['lt', $now], 'a.is_end' => 0, 'a.good_object' => 0])
                        ->field('a.*')
                        ->find();
                    if (!empty($prominfo)) {
                        //全场商品
                        $prom = discount($price * $goods_num,
                            $prominfo['id'], $goods_num, $user_id,$prominfo['is_bz']);
                        $goods['prom_type'] = 3;
                        $goods['prom_id'] = $prom['prom_id'];
                        if(empty($isset))
                            $price = $goods['shop_price'];
                    }

                    /*--当是线下库存的时候--*/
                    if ($sale_r == 2) {
                        $count1 = getpickwarecount($goods_id, $pickup_id, getMobileStoId());
                        if ($count1 == -1) {
                            return array('status' => -4, 'msg' => "获取库存失败", 'result' => '');
                        } else {
                            if (($cart_goods_num2 + $goods_num) > $count1) {
                                return array('status' => -4, 'msg' => "库存不足", 'result' => '');
                            }
                        }
                    }
                }
            }
        } else {
            //$prominfo = M('prom_goods')->where(['end_time' => ['gt', time()], 'start_time' => ['lt', time()], 'is_end' => 0, 'store_id' => $goods['store_id'], 'good_object' => 0])->field('id,')->find();
            //指定部分商品不参与活动,或者全场活动
            $now=time();
            $w1="(b.goods_listid='' or b.goods_listid is null or locate(',".$goods['goods_id'].",',b.goods_listid)=0)";

            $prominfo = M('prom_goods')->alias('a')->join('activitylist b','b.act_id=a.id and b.prom_type=3')
                ->where('a.store_id', $goods['store_id'])->where($w1)
                ->where(['a.end_time' => ['gt', $now], 'a.start_time' => ['lt', $now], 'a.is_end' => 0, 'a.good_object' => 0])
                ->field('a.*')
                ->find();

            mlog("查找购物车".json_encode($prominfo), "addCart/" . $goods['store_id']);

            if (!empty($prominfo)) {
                //全场商品
                $prom = discount($price * $goods_num,
                    $prominfo['id'], $goods_num, $user_id,$prominfo['is_bz']);
                $goods['prom_type'] = 3;
                $goods['prom_id'] = $prom['prom_id'];
                if(empty($isset))
                    $price = $goods['shop_price'];
            }
        }

        mlog("<会员:" . $user_id . ">" . "查找购物车", "addCart/" . $goods['store_id']);
        //查找购物车是否已经存在该商品
        $cart_goods = M('Cart')->where("goods_id", $goods_id)
            ->where("session_id ='" . $session_id . "' or user_id=" . $user_id)
            ->where('pick_id', $pickup_id)
            ->where('state', 0)
            ->find();

//      $rec_count = M('cart')->where(['prom_id' => $goods['prom_id'], 'user_id' => $user_id, 'is_gift' => 1])->count();

        // 如果商品购物车已经存在
        if ($to_catr == 0 && $cart_goods > 0) {
            // 如果购物车的已有数量加上 这次要购买的数量  大于  库存输  则不再增加数量
            M('Cart')->where("id", $cart_goods['id'])->where('pick_id', $pickup_id)->save(["goods_num" => (int)($cart_goods_num + $goods_num)]); // 数量相加
            $cart_count = cart_goods_num($user_id, $session_id); // 查找购物车数量
            setcookie('cn', $cart_count, null, '/');
            return array('status' => 1, 'msg' => '成功加入购物车', 'result' => $cart_count);
        } else {
            $data = array(
                'user_id' => $user_id,    // 用户id
                'session_id' => $session_id, // sessionid
                'goods_id' => $goods_id,   // 商品id
                'goods_sn' => $goods['goods_sn'],   // 商品货号
                'goods_name' => $goods['goods_name'],   // 商品名称
                'market_price' => $goods['market_price'],   // 市场价
                'goods_price' => $price,  // 购买价
                'member_goods_price' => $price,  // 会员折扣价默认为购买价
                'goods_num' => $goods_num, // 购买数量
                'sku' => $goods['sku'], // 商品条形码
                'add_time' => time(), // 加入购物车时间
                'prom_type' => $goods['prom_type'],   // 0 普通订单,1 限时抢购, 2 团购 ,3 促销优惠
                'prom_id' => $goods['prom_id'],   // 活动id
                'pick_id' => $pickup_id,
                'store_id' => $goods['store_id'],
            );

            if($isinte==1) {
                if($data['prom_type']!=3) $data['prom_type']=0;
                $data['is_integral_normal']=$isinte;
            }
            if($ispd==1) {
                if($data['prom_type']!=3) $data['prom_type']=0;
                $data['is_pd_normal']=1;
            }

            mlog("<会员:" . $user_id . ">" . json_encode($data), "addCart/" . $goods['store_id']);

            if ($to_catr == 1)//立即购买
            {
//                M('Cart')->where('user_id', $user_id)->where('state', 1)->delete();
                $data['state'] = 1;
            } else if ($to_catr == 2)//积分购
            {
                M('Cart')->where('user_id', $user_id)->where('state', 2)->delete();
                $data['state'] = 2;
            }

            $insert_id = M('Cart')->add($data);
            if (!empty($prom['goods_id']) && $to_catr == 1) {
                $num=1;
                if($prom['is_bz']==1) {
                    $limitnum = $prom['limit_num'];
                    $num = $prom['bs'];
                    if ($num > $limitnum) $num = 0;
                }

                //---如果礼品的库存不足,就不送---
                if($num>$prom['gift_storecount']) $num=0;
                //数据大于0才加入购物车
                if($num>0) {
                    $data['goods_sn'] = '';
                    $data['goods_name'] = $prom['goods_name'];
                    $data['goods_id'] = $prom['goods_id'];
                    $data['market_price'] = $data['goods_price'] = $data['member_goods_price'] = 0;
                    $data['goods_num'] = $num;
                    $data['sku'] = '';
                    $data['is_gift'] = 1;
                    $data['main_cart_id'] = $insert_id;
                    $data['gift_id'] = $prom['gift_id'];
                    M('cart')->add($data);
                }
            }
            if (!empty($prom['goods'])) {
                foreach ($prom['goods'] as $kk => $vv) {
                    $collocation[] = [
                        'user_id' => $user_id,    // 用户id
                        'session_id' => $session_id, // sessionid
                        'goods_id' => $vv['goods_id'],   // 商品id
                        'goods_sn' => $vv['goods_sn'],   // 商品货号
                        'goods_name' => $vv['goods_name'],   // 商品名称
                        'market_price' => $vv['market_price'],   // 市场价
                        'goods_price' => $vv['price'],  // 购买价
                        'member_goods_price' => $vv['price'],  // 会员折扣价默认为购买价
                        'goods_num' => 1, // 购买数量
                        'sku' => $vv['sku'], // 商品条形码
                        'add_time' => time(), // 加入购物车时间
                        'prom_type' => $goods['prom_type'],   // 0 普通订单,1 限时抢购, 2 团购 ,3 促销优惠
                        'prom_id' => $goods['prom_id'],   // 活动id
                        'pick_id' => $pickup_id,
                        'store_id' => $goods['store_id'],
                        'state' => 1,
                        'main_cart_id' => $insert_id,
                        'is_collocation' => 1
                    ];
                }
                M('cart')->insertAll($collocation);
            }
            mlog("<会员:" . $user_id . ">" . json_encode($insert_id), "addCart/" . $goods['store_id']);
            $cart_count = cart_goods_num($user_id, $session_id); // 查找购物车数量
            mlog("<会员:" . $user_id . ">购物车数量" . $cart_count, "addCart/" . $goods['store_id']);
            setcookie('cn', $cart_count, null, '/');
            return array('status' => 1, 'msg' => '成功加入购物车', 'result' => $cart_count);
        }
        return array('status' => -5, 'msg' => '加入购物车失败', 'result' => "");
    }

    /**
     * 购物车列表,还有提交订单都会调用
     * @param type $user 用户
     * @param type $session_id session_id
     * @param type $selected 是否被用户勾选中的 0 为全部 1为选中  一般没有查询不选中的商品情况
     * @param type $blinearr 购物车中的是商品线下库存对
     * $mode 0  返回数组形式  1 直接返回result
     */
    function cartList($user = array(), $session_id = '', $selected = 0, $mode = 0)
    {
        //$state=0,即为加入购物车的
        $cartList=$this->getCartlist($user,getMobileStoId(),$session_id,$selected);
        $arr=$this->handle_cart($cartList,$user,1);
        $total_price=$arr[0];
        $cartList=$arr[1];

        setcookie('cn', $total_price['num'], null, '/');
        if ($mode == 1) return array('cartList' => $cartList, 'total_price' => $total_price);
        return array('status' => 1, 'msg' => '', 'result' => array('cartList' => $cartList, 'total_price' => $total_price));
    }
    /**
     * 立即购买确认页面
     * @param type $user 用户
     * @param type $session_id session_id
     */
    function gobuyList($user = array(), $session_id = '')
    {
        //立即购买State=1
        $cartList=$this->getCartlist($user,getMobileStoId(),$session_id,1,1);
        $arr=$this->handle_cart($cartList,$user,1);
        $total_price=$arr[0];
        $cartList=$arr[1];
        return array('cartList' => $cartList, 'total_price' => $total_price);
    }
    /**
     * 积分购买确认页面
     * @param type $user 用户
     * @param type $session_id session_id
     */
    function gointeList($user = array(), $session_id = '')
    {
        //立即购买State=1
        $cartList=$this->getCartlist($user,getMobileStoId(),$session_id,1,2);
        $anum = $total_price = $cut_fee = $total_integral = 0;
        /*--循环更新状态--*/
        foreach ($cartList as $k => $v) {
            if ($v["prom_type"] != 0) {
                $cartList[$k]["prom"] = get_goods_promotion1($v, null, $user[user_id]);
                $v["member_goods_price"] = $cartList[$k]["member_goods_price"] = $cartList[$k]["prom"]["addmoney"];
                $v["member_goods_integral"] = $cartList[$k]["member_goods_integral"] = $cartList[$k]["prom"]["integral"];
                $date = ['addmoney' => $v["member_goods_price"], "member_goods_price" => $v['member_goods_price']];
                M("Cart")->where("id", $v['id'])->save($date);
            }
            //$g=M("goods")->where("goods_id",$v["goods_id"])->find();
            //更新最新的商品价格
//            if($val['shop_price']!=$g["shop_price"])
//            {
//                $date=['shop_price'=>$g["shop_price"]];
//                M("Cart")->where("id",$val['$val'])->save($date);
//            }

            /*------商品规格,价格--------*/
            $sp1 = $v["goods_spec"];
            $cn1 = $v["goods_color"];
            $guige1 = "规格";
            $gorder1 = 1;
            $tgg1 = "";
            if ($sp1 == "" && $cn1 == "") {
                $tgg1 = $guige1 . $gorder1;
                $gorder1++;
            } else if ($sp1 != "" && $cn1 == "") {
                $tgg2 = $sp1;
            } else if ($sp1 == "" && $cn1 != "") {
                $tgg1 = $cn1;
            } else {
                $tgg1 = $sp1 . "/" . $cn1;
            }
            $cartList[$k]['guige'] = $tgg1;
            $cartList[$k]['goods_fee'] = $v['goods_num'] * $v['member_goods_price'];
            $cartList[$k]['store_count'] = getGoodNum($v['goods_id'], $v['spec_key']); // 最多可购买的库存数量

            $anum += $v['goods_num'];
            // 如果要求只计算购物车选中商品的价格 和数量  并且  当前商品没选择 则跳过
            if ($v['selected'] == 0)  continue;

            $cf = $v['goods_num'] * $v['market_price'] - $v['goods_num'] * $v['member_goods_price'];
            $allp = $v['goods_num'] * $v['member_goods_price'];
            $alli = $v['goods_num'] * $v['member_goods_integral'];

            $cut_fee += $cf;
            $total_price += $allp;
            $total_integral += $alli;
        }
        $total_price = array('total_fee' => $total_price, 'total_integral' => $total_integral, 'cut_fee' => $cut_fee, 'num' => $anum,); // 总计
        return array('cartList' => $cartList, 'total_price' => $total_price);
    }
    /**
     * 购物车列表
     * @param type $user 用户
     * @param type $session_id session_id
     * @param type $selected 是否被用户勾选中的 0 为全部 1为选中  一般没有查询不选中的商品情况
     * @param type $blinearr 购物车中的是商品线下库存对
     * $mode 0  返回数组形式  1 直接返回result
     */
    function cartList_cart2($user = array(), $session_id = '', $selected = 0, $mode = 0)
    {
        $cartList=$this->getCartlist($user,getMobileStoId(),$session_id,$selected);
        //不需要更新
        $arr=$this->handle_cart($cartList,$user);
        $total_price=$arr[0];
        $cartList=$arr[1];
        setcookie('cn', $total_price['num'], null, '/');
        if ($mode == 1) return array('cartList' => $cartList, 'total_price' => $total_price);
        return array('status' => 1, 'msg' => '', 'result' => array('cartList' => $cartList, 'total_price' => $total_price));
    }
    /**
     * 立即购买确认页面
     * @param type $user 用户
     * @param type $session_id session_id
     */
    function gobuyList_cart2($user = array(), $session_id = '')
    {
        //$state=1立即购买
        $cartList=$this->getCartlist($user,getMobileStoId(),$session_id,1,1);
        //不需要更新
        $arr=$this->handle_cart($cartList,$user);
        $total_price=$arr[0];
        $cartList=$arr[1];
        return array('cartList' => $cartList, 'total_price' => $total_price);
    }

    function my_calculate($goodslist, $user_id, $state)
    {
        foreach ($goodslist as $k => $v) {
            $id[] = $v["goods_id"];
        }
        $total_price = 0;
        $member_goods_price = 0;
        $cartList = null;
        if ($state == 0) {
            $cartList = M('Cart')->where('user_id', $user_id)
                ->where('state', 0)->where('selected', 1)->where("goods_id", "in", $id)->select();
        } else {
            $cartList = M('Cart')->where('user_id', $user_id)
                ->where('state', 1)->where("goods_id", "in", $id)->select();
        }
        /*--循环更新状态--*/
        foreach ($cartList as $k => $v) {
            if ($v["prom_type"] != 0) {
                $prom = get_goods_promotion($v["goods_id"], $user_id);
                $member_goods_price = $prom["price"];
            } else {
                $g = M("goods")->where("goods_id", $v["goods_id"])->find();
                $member_goods_price = $g["shop_price"];
            }
            $total_price += $v['goods_num'] * $member_goods_price;
        }
        return $total_price;
    }

    /*--循环计算总价--*/
    function my_calculate_cart2($goodslist, $user_id)
    {
        $total_price = 0;
        $cartList = $goodslist;
        /*--循环更新状态--*/
        foreach ($cartList as $k => $v) {
            /*--
            if($v['prom_type']==3){
                $r=M('prom_goods')->where('id',$v['prom_id'])->field('is_xz_yh')->find();
                if($r && $r['is_xz_yh']==1) continue;
            }--*/
            $member_goods_price = $v["goods_price"];
            $total_price += $v['goods_num'] * $member_goods_price;
        }
        return $total_price;
    }

    /**
     * 计算商品的的运费,按重量算
     * @param type $shipping_code 物流 编号
     * @param type $province 省份
     * @param type $city
     * @param type $district
     * @return int
     */
    function cart_freight2($shipping_code, $province, $city, $district, $weight, $stoid)
    {

        if ($shipping_code == '') return 0;
        // 先根据 镇 县 区找 shipping_area_id
        $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  " . C('database.prefix') . "shipping_area where shipping_code = :shipping_code) and region_id = :region_id")->where('store_id', $stoid)
            ->bind(['shipping_code' => $shipping_code, 'region_id' => $district])->getField('shipping_area_id');
        // 先根据市区找 shipping_area_id
        if ($shipping_area_id == false)
            $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  " . C('database.prefix') . "shipping_area where shipping_code = :shipping_code) and region_id = :region_id")->where('store_id', $stoid)
                ->bind(['shipping_code' => $shipping_code, 'region_id' => $city])->getField('shipping_area_id');

        // 市区找不到 根据省份找shipping_area_id
        if ($shipping_area_id == false)
            $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  " . C('database.prefix') . "shipping_area where shipping_code = :shipping_code) and region_id = :region_id")
                ->where('store_id', $stoid)->bind(['shipping_code' => $shipping_code, 'region_id' => $province])->getField('shipping_area_id');

        // 省份找不到 找默认配置全国的物流费
        if ($shipping_area_id == false) {
            // 如果市和省份都没查到, 就查询 tp_shipping_area 表 is_default = 1 的  表示全国的  select * from `tp_plugin`  select * from  `tp_shipping_area` select * from  `tp_area_region`
            $shipping_area_id = M("ShippingArea")->where(['shipping_code' => $shipping_code, 'is_default' => 1])
                ->where("store_id", $stoid)->getField('shipping_area_id');
        }
        if ($shipping_area_id == false) {
            mlog($shipping_code . ":" . $province . ':' . $city . ':' . $district . ':' . $weight . '未找到物流1', 'no_findshipping/' . $stoid);
            return 0;
        }
        /// 找到了 shipping_area_id  找config
        $shipping_config = M('ShippingArea')->where("shipping_area_id", $shipping_area_id)->where("store_id", $stoid)
            ->getField('config');
        $shipping_config = unserialize($shipping_config);

        if (empty($shipping_config)) {
            mlog($shipping_code . ":" . $province . ':' . $city . ':' . $district . ':' . $weight . '未找到物流2', 'no_findshipping/' . $stoid);
        }

        $shipping_config['money'] = $shipping_config['money'] ? $shipping_config['money'] : 0;

        // 1000 克以内的 只算个首重费
        if ($weight < $shipping_config['first_weight']) {
            return $shipping_config['money'];
        }
        // 超过 1000 克的计算方法
        $weight = $weight - $shipping_config['first_weight']; // 续重
        if ($shipping_config['second_weight'])
            $weight = ceil($weight / $shipping_config['second_weight']); // 续重不够取整
        $freight = $shipping_config['money'] + $weight * $shipping_config['add_money']; // 首重 + 续重 * 续重费

        return $freight;
    }


    /**
     * 计算商品的的运费,按件数算
     * @param type $shipping_code 物流 编号
     * @param type $province 省份
     * @param type $city
     * @param type $district
     * @return int
     */
    function cart_piece2($shipping_code, $province, $city, $district, $weight, $stoid)
    {

        if ($shipping_code == '') return 0;
        // 先根据 镇 县 区找 shipping_area_id
        $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  " . C('database.prefix') . "shipping_area where shipping_code = :shipping_code) and region_id = :region_id")
            ->where('store_id', $stoid)->bind(['shipping_code' => $shipping_code, 'region_id' => $district])->getField('shipping_area_id');
        // 先根据市区找 shipping_area_id
        if ($shipping_area_id == false)
            $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  " . C('database.prefix') . "shipping_area where shipping_code = :shipping_code) and region_id = :region_id")->bind(['shipping_code' => $shipping_code, 'region_id' => $city])->where('store_id', $stoid)->getField('shipping_area_id');

        // 市区找不到 根据省份找shipping_area_id
        if ($shipping_area_id == false)
            $shipping_area_id = M('AreaRegion')->where("shipping_area_id in (select shipping_area_id from  " . C('database.prefix') . "shipping_area where shipping_code = :shipping_code) and region_id = :region_id")->bind(['shipping_code' => $shipping_code, 'region_id' => $province])->where('store_id', $stoid)->getField('shipping_area_id');

        // 省份找不到 找默认配置全国的物流费
        if ($shipping_area_id == false) {
            // 如果市和省份都没查到, 就查询 tp_shipping_area 表 is_default = 1 的  表示全国的  select * from `tp_plugin`  select * from  `tp_shipping_area` select * from  `tp_area_region`
            $shipping_area_id = M("ShippingArea")->where(['shipping_code' => $shipping_code, 'is_default' => 1])
                ->where("store_id", $stoid)->getField('shipping_area_id');
        }
        if ($shipping_area_id == false)
            return 0;
        /// 找到了 shipping_area_id  找config
        $shipping_config = M('ShippingArea')->where("shipping_area_id", $shipping_area_id)->where("store_id", $stoid)
            ->getField('config');
        $shipping_config = unserialize($shipping_config);
        $shipping_config['piecemoney'] = $shipping_config['piecemoney'] ? $shipping_config['piecemoney'] : 0;
        $shipping_config['add_piecemoney'] = $shipping_config['add_piecemoney'] ? $shipping_config['add_piecemoney'] : 0;

        // 1000 克以内的 只算个首重费
        if ($weight < $shipping_config['first_piece']) {
            return $shipping_config['piecemoney'];
        }

        // 超过 1000 克的计算方法
        $weight = $weight - $shipping_config['first_piece']; // 续数量取整
        if ($shipping_config['second_piece'])
            $weight = ceil($weight / $shipping_config['second_piece']);
        $freight = $shipping_config['piecemoney'] + $weight * $shipping_config['add_piecemoney']; // 首件 + 续件 * 续件费
        return $freight;
    }

    /**
     * 获取用户可以使用的优惠券
     * @param type $user_id 用户id
     * @param type $coupon_id 优惠券id
     * $mode 0  返回数组形式  1 直接返回result
     */
    public function getCouponMoney($user_id, $coupon_id, $mode,$user0=null,$erpid="")
    {
        /*---
        if ($coupon_id == 0) {
            if ($mode == 1) return 0;
            return array('status' => 1, 'msg' => '', 'result' => 0);
        }
        $couponlist = M('CouponList')->where("uid", $user_id)->where('id', $coupon_id)->find(); // 获取用户的优惠券
        if (empty($couponlist)) {
            if ($mode == 1) return 0;
            return array('status' => 1, 'msg' => '', 'result' => 0);
        }

        $coupon = M('Coupon')->where("id", $couponlist['cid'])->find(); // 获取 优惠券类型表
        $coupon['money'] = $coupon['money'] ? $coupon['money'] : 0;
        */

        //$tk = M("store")->where("store_id", getMobileStoId())->field("api_token")->find();

        $user=$user0;
        if(empty($user0)){
            $user = M("users")->where("user_id", $user_id)->field("erpvipid")->find();
        }

        //如果是非erp用户
        if(empty($erpid)){
            $where = "code='" . $coupon_id . "'";
            $where.= " and uid='" . $user_id . "'";
            $q = M("coupon_list")->where($where)->field('sum')->find();
            if($q) {
                if ($mode == 1) return $q['sum'];
                return array('status' => 1, 'msg' => '', 'result' => $q['sum']);
            }
            else {
                if ($mode == 1) return 0;
                return array('status' => 1, 'msg' => '', 'result' => 0);
            }
        }else {
            $tk = tpCache("shop_info", getMobileStoId());
            $where = "VIPId='" . $user['erpvipid'] . "'";
            $where.= " and CashRepNo='" . $coupon_id . "'";
            //$where .= " and IsUse=0 and ValidDate>='" . $snow . "'";
            //$where .= " and BuySum<=".$r;
            $rs = getApiData("wxderp.cashreplace.list.get", $tk["api_token"], null, $where, null, null);
            $qlistall = json_decode($rs, true);
            if ($qlistall) {
                if ($mode == 1) return $qlistall["data"][0]['Sum'];
                return array('status' => 1, 'msg' => '', 'result' => $qlistall["data"][0]['Sum']);
            } else {
                if ($mode == 1) return 0;
                return array('status' => 1, 'msg' => '', 'result' => 0);
            }
        }
    }

    /**
     * 获取用户可以使用的优惠券
     * @param type $user_id 用户id
     * @param type $coupon_id 优惠券id
     * $mode 0  返回数组形式  1 直接返回result
     */
    public function getCouponMoney2($user_id, $coupon_id,$user0=null,$erpid="",$wlist,$sumlist)
    {


        $user=$user0;
        if(empty($user0)){
            $user = M("users")->where("user_id", $user_id)->field("erpvipid")->find();
        }
        //如果是非erp用户
        if(empty($erpid)){
            $where = "code='" . $coupon_id . "'";
            $where.= " and uid='" . $user_id . "'";
            $q = M("coupon_list")->where($where)->field('sum')->find();
            if($q) {
                return array('status' => 1, 'msg' => '', 'result' => $q['sum']);
            }
            else {
                return array('status' => 1, 'msg' => '', 'result' => 0);
            }
        }else {
            $accdb = tpCache('shop_info.ERPId',getMobileStoId());
            $data['CashRepNo']=$coupon_id;
            $data['WareIds']=urlencode($wlist);
            $data['WaresSum']=$sumlist;
            $rs = getApiData_java("api/erp/shop/cash/wares/list",$accdb,$data);
            $qlistall = json_decode($rs, true);
            $arr=null;
            if ($qlistall) {
                if($qlistall['code']==0) {
                    $sum1=0;
                    foreach ($qlistall['data'] as $kv=>$vv){
                        $sum1+=$vv['WareCashSum'];
                    }
                    mlog($sum1,"getCouponMoney2/".getMobileStoId());
                    mlog(json_encode($qlistall['data']),"getCouponMoney2/".getMobileStoId());

                    return array('status' => 1, 'msg' => '', 'result' => $sum1, 'arr' => $qlistall['data']);
                }

            }else {
                return array('status' => 1, 'msg' => '', 'result' => 0,'arr'=>$arr);
            }
        }
    }

    /**
     * 根据优惠券代码获取优惠券金额
     * @param type $couponCode 优惠券代码
     * @param type $order_momey Description 订单金额
     * return -1 优惠券不存在 -2 优惠券已过期 -3 订单金额没达到使用券条件
     */
    public function getCouponMoneyByCode($couponCode, $order_momey)
    {
        $couponlist = M('CouponList')->where("code", $couponCode)->find(); // 获取用户的优惠券
        if (empty($couponlist))
            return array('status' => -9, 'msg' => '优惠券码不存在', 'result' => '');
        if ($couponlist['order_id'] > 0) {
            return array('status' => -20, 'msg' => '该优惠券已被使用', 'result' => '');
        }
        $coupon = M('Coupon')->where("id", $couponlist['cid'])->find(); // 获取优惠券类型表
        if (time() > $coupon['use_end_time'])
            return array('status' => -10, 'msg' => '优惠券已经过期', 'result' => '');
        if ($order_momey < $coupon['condition'])
            return array('status' => -11, 'msg' => '金额没达到优惠券使用条件', 'result' => '');
        if ($couponlist['order_id'] > 0)
            return array('status' => -12, 'msg' => '优惠券已被使用', 'result' => '');
        return array('status' => 1, 'msg' => '', 'result' => $coupon['money']);
    }

    /**
     *  添加一个订单
     * @param type $user_id 用户id
     * @param type $address_id 地址id
     * @param type $shipping_code 物流编号
     * @param type $invoice_title 发票
     * @param type $coupon_id 优惠券id
     * @param type $car_price 各种价格
     * @param type $user_note 用户备注
     * @param type $stoid 门店ID
     * @param type $order_goods 订单商品
     * @return type $order_id 返回新增的订单id
     * @return type isone 生成单个订单
     * @return type $parentno
     */
    public function addOrder($user_id, $address_id, $shipping_code, $invoice_title, $car_price,
                             $order_goods = null, $coupon_id = '',
                             $user_note = '', $stoid = 0, $exptype = 0, $parentno = "", $pickup_id = 0, $discount = array(),$userarr=null,$no='',$ispt=0,$pdid=0,$team_qh='',$youhui_arr=null)
    {
        // 仿制灌水 1天只能下 50 单  // select * from `tp_order` where user_id = 1  and order_sn like '20151217%' 
	    //$time=strtotime(date('Y-m-d',time()));
        //$order_count = M('Order')->where('store_id',$stoid )->where("user_id", $user_id)->where('add_time>', $time)->count(); // //查找购物车商品总数量
        //if ($order_count >= 50)
           // return array('status' => -9, 'msg' => '一天只能下50个订单', 'result' => '');
        //0插入订单 order

        $address=null;
        if ($exptype == 0) {
            if (empty($shipping_code)) {
                return array('status' => -9, 'msg' => '请选择物流', 'result' => '');
            }
            if (empty($address_id)) {
                return array('status' => -9, 'msg' => '请填写物流地址', 'result' => '');
            }
            $address = M('UserAddress')->where("address_id", $address_id)->find();
            if (empty($address)) {
                return array('status' => -9, 'msg' => '请填写物流地址', 'result' => '');
            }

            $shipping = M('shipping')->where("shipping_code", $shipping_code)->find();
        }
        //$uerp = M('users')->alias('a')->join('store b', 'a.store_id=b.store_id')->where("a.store_id", $stoid)->field('a.*,b.ERPId')->find();
        $uerp=null;
        if(empty($userarr) || $userarr['mobile']==""){
            $uerp= M('users')->where("store_id", $stoid)->where('user_id',$user_id)->find();
        }else{
            $uerp=$userarr;
        }
        $uerp['ERPId']=tpCache('shop_info.ERPId',$stoid);

        $order_sn = $uerp['ERPId'] . date('YmdHis') . rand(1000, 9999);
        /*--是否是单个单--*/
        if (empty($parentno)) {
            $parentno = $order_sn;
        }
        //优惠券
        if (!empty($discount['coupon'])){
            $coupon_list = implode(',',$discount['coupon']);
        }else{
            $coupon_list = 0;
        }
        //礼包
        if (!empty($discount['libao'])){
            $libao = implode(',',$discount['libao']);
        }else{
            $libao = 0;
        }

        //是否启用平摊
        $getis_split=0;
        $switch = tpCache('shopping.switch_list',$stoid);//获取开关json
        $switch_list = json_decode($switch,true);//获取开关列表
        if (empty($switch_list['ispt_goods'])) {//0或空值 代表平摊
            $getis_split=1;
        }
        $data = array(
            'order_sn' => $order_sn, // 订单编号
            'parent_sn' => $parentno, // 组合订单编号
            'user_id' => $user_id, // 用户id
            'consignee' => $address['consignee'], // 收货人
            'province' => $address['province'],//'省份id',
            'city' => $address['city'],//'城市id',
            'district' => $address['district'],//'县',
            'twon' => $address['twon'],// '街道',
            'address' => $address['address'],//'详细地址',
            'more_address' => $address['more_address'],//'详细地址',
            'mobile' => $address['mobile'],//'手机',
            'zipcode' => $address['zipcode'],//'邮编',
            'email' => $address['email'],//'邮箱',
            'shipping_code' => $shipping_code,//'物流编号',
            'shipping_name' => $shipping['shipping_name'], //'物流名称',
            'invoice_title' => $invoice_title, //'发票抬头',
            'goods_price' => $car_price['goodsFee'],//'商品价格',
            'shipping_price' => $car_price['postFee'],//'物流价格',
            'user_money' => $car_price['balance'],//'使用余额',
            'coupon_price' => $car_price['couponFee'],//'使用优惠券',
            'coupon_no' => $coupon_id,
            'integral' => $car_price['pointsFee'], //'使用积分
            'integral_money' => $car_price['pointsFee'],//使用积分+钱 的钱的那一部分
            'total_amount' => ($car_price['goodsFee'] + $car_price['postFee']),// 订单总额
            'order_amount' => $car_price['payables'],//'应付款金额',
            'add_time' =>microtime_float(), // 下单时间
            'order_prom_id' => $car_price['order_prom_id'],//'订单优惠活动id',
            'order_prom_amount' => $car_price['order_prom_amount'],//'订单优惠活动优惠了多少钱',
            'discount_amount' => (float)$car_price['discount_amount'],//'优惠促销活动优惠了多少钱',
            'user_note' => $user_note, // 用户下单备注
            'store_id' => $stoid, // 门店ID
            'pickup_id' => $pickup_id, // 门店ID
            'exp_type' => $exptype, // 配送方式
            'give_integral' => (int)$discount['int'], // 购买商品赠送积分
            'give_coupon_id' => $coupon_list, // 购买商品赠送优惠券列表
            'give_lb_id'=>$libao,
            'prom_pt_json'=>json_encode($car_price['good_prom']),  //优惠活动的json
            'is_split'=>$getis_split,  //优惠活动的json
            'redis_no'=>$no,
        );

        //如果是有优惠活动倍增是情况下
        if($discount['coupon_num']){
            $data['g_coupon_num']=json_encode($discount['coupon_num']);
        }
        //如果是有优惠活动倍增是情况下
        if($discount['lb_num']){
            $data['g_lb_num']=json_encode($discount['lb_num']);
        }

        //如果是拼团的订单
        if($ispt){
            switch ($ispt){
                case "1":$data['is_zsorder']=2;break;
                case "2":$data['is_zsorder']=3;break;
                case "3":$data['is_zsorder']=4;break;
            }
            $data['pt_status']=0;
            $data['pt_prom_id']=$pdid;
            //如果有期号,就是参团,没有期号,就是开团
            $th_qh=trim($team_qh);
            if(empty($th_qh)) {
                //不是商家团的控制操作
                if ($ispt!="1"){
                    $rs = M('teamlist')->where('id', $pdid)->field('ct_num,actno,kt_time,ct_rylist')->find();
                    /*-----随机期号
                    $rs=M('teamlist')->where('id',$pdid)->field('actno')->find();
                    $max_num=M('teamgroup')->where('team_id',$pdid)
                        ->where('store_id',$stoid)
                        ->max('listno');
                    //期号的生成
                    if($max_num) {
                        $no1 = substr($max_num, -4);
                        $title = substr($max_num, 0, -4);
                        $no2 = (int)$no1;
                        $no2++;
                        $no2 = create_4no($no2);
                        //最后生成单号
                        $no3 = $title . $no2;
                        $data['pt_listno'] = $no3;
                        $data['is_pt_tz']=1;
                    }else{
                        $no3=$rs['actno'].'0001';
                        $data['pt_listno'] = $no3;
                        $data['is_pt_tz']=1;
                    }
                    -----*/
                    $no3=$pdid."_".date('ymdHis') . get_total_millisecond() . rand(1000, 9999);
                    $data['pt_listno'] = $no3;
                    $data['is_pt_tz']=1;

                    //如果是会员团,要控制团员数量
                    if ($ispt=="2") {
                        //同时生成队列
                        //$redis = new \Redis();
                        //$redis->connect(redisip, 6379);
                        $redis=get_redis_handle();
                        //团的缓存数据
                        //$name2 = 'pind' . $pdid . '-' . $data['pt_listno'] . $stoid;
                        $name2=get_redis_name($pdid,6,$stoid).":".$data['pt_listno'];
                        for ($i = 1; $i <= $rs['ct_num'] - 1; $i++) {
                            //本人已经算一个数量了
                            $redis->lPush($name2, $i);
                        }
                    }
                    //要往期号表里面添加数据
                    //修改期号表的记录
                    $r=M("teamgroup")->where('store_id',$stoid)->where("team_id", $pdid)
                        ->where('listno',$data['pt_listno'])->find();
                    if(empty($r)){
                        $t=time();
                        $grda['store_id']=$stoid;
                        $grda['team_id']=$pdid;
                        $grda['openvipid']=$user_id;
                        $grda['listno']=$data['pt_listno'];
                        $grda['buystartdate']=$t;
                        $grda['addtime']=$t;
                        //到期时间
                        $grda['kt_end_time']=strtotime('+'.$rs['kt_time'].' hour',$t);
                        //拼单的类型
                        $grda['team_type']=$ispt;
                        $grda['jt_json']=$rs['ct_rylist'];
                        M("teamgroup")->save($grda);
                    }else{
                        $t=time();
                        //拼单的类型
                        $grda['buystartdate']=$t;
                        $grda['kt_end_time']=strtotime('+'.$rs['kt_time'].' hour',$t);
                        M("teamgroup")->save($grda);
                    }
                }
            }else{
                $data['pt_listno']=$th_qh;
            }
        }

        /*--自提的时候判断--*/
        if ($exptype == 1) {
            //$u = M("users")->where("user_id", $user_id)->find();
            $u=$uerp;
            $data['consignee'] = $u["nickname"]; // 收货人
            $data['mobile'] = $u["mobile"];//'手机',
            $data['address'] = '';//'详细地址',

            if(!$data['consignee']) $data['consignee']=$u["mobile"];
        }

        //如果未找到拼单编号的话(会员团和阶梯团)
        if($ispt>1){
            if(empty( $data['pt_listno']))
                return array('status' => -8, 'msg' => '未找到拼单编号', 'result' => NULL);
        }

        $data['order_id'] = $order_id = M("Order")->insertGetId($data);
        $order = $data;//M('Order')->where("order_id", $order_id)->find();
        if (!$order_id)
            return array('status' => -8, 'msg' => '添加订单失败', 'result' => NULL);

        // 记录订单操作日志
        $action_info = array(
            'order_id' => $order_id,
            'action_user' => $user_id,
            'action_note' => '您提交了订单,请等待系统确认',
            'status_desc' => '提交订单', //''
            'log_time' => time(),
            'store_id' => $stoid,
        );

        $ut=null;
        M('order_action')->insertGetId($action_info);
        $cartList = $order_goods;

        mlog("$cartList".json_encode($cartList),"addorder/".$stoid);
        foreach ($cartList as $key => $val) {
            $goods = M('goods')->where("goods_id", $val['goods_id'])->find();
            $data2['order_id'] = $order_id; // 订单id
            $data2['order_sn'] = $order_sn; // 订单编号
            //$data2['order_sn'] = null; // 订单编号
            $data2['goods_id'] = $val['goods_id']; // 商品id
            $data2['goods_name'] = $goods['goods_name']; // 商品名称
            $data2['goods_sn'] = $goods['goods_sn']; // 商品货号
            $data2['goods_num'] = $val['goods_num']; // 购买数量
            $data2['market_price'] = $val['market_price']; // 市场价
            $data2['goods_price'] = $val['goods_price']; // 商品价
            $data2['spec_key'] = $val['spec_key']; // 商品规格
            $data2['spec_key_name'] = $val['spec_key_name']; // 商品规格名称
            $data2['member_goods_price'] = $val['member_goods_price']; // 会员折扣价
            $data2['cost_price'] = $goods['cost_price']; // 成本价
            $data2['prom_type'] = $val['prom_type1']; // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠 , 5搭配促销
            $data2['prom_id'] = $val['prom_id1']; //活动id
            $data2['store_id'] = $stoid; //门店ID
            $data2['pick_id'] = $pickup_id; //门店supplyid
            $data2['is_collocation'] = $val['is_collocation'];
            $data2['give_integral'] = $goods['give_integral'];
            $data2['account'] = $val['goods_price'];


            mlog("isgift".$val['is_gift'],"addorder/".$stoid);
            //---如果是赠品的情况下---
            if ($val['is_gift'] == 1) {
                //--给从表做标记--
                $data2['is_gift'] = 1;
                $data2['gift_id'] =$val['gift_id'] ;

                //--乐观锁,让赠品不会送出去--
                $rs=M("gift")->where('store_id',$stoid)
                    ->where('id',$val['gift_id'])
                    ->where("is_end",0)
                    ->where("goods_num>=".$val['goods_num'])
                    ->setDec('goods_num',$val['goods_num']);
                if(!$rs){
                    //是不是继续购买
                    $is_continue=I("is_continue");

                    mlog("iscon".$is_continue,"addorder/".$stoid);

                    if($is_continue) continue;
                    else{
                        $rss=M("gift")->where('store_id',$stoid)
                            ->where('id',$val['gift_id'])
                            ->field("goods_num,is_end")->find();

                        $erro_txt='赠品数不足无法赠送,是否继续买单?';
                        if($rss['is_end']==1)
                            $erro_txt='赠品活动已经取消,无法赠送,是否继续买单?';

                        return array('status' => -19,'msg' => $erro_txt,'result' => NULL);
                    }
                }
            }

            $data2['is_integral_normal'] = $val['is_integral_normal'];
            $data2['is_pd_normal'] = $val['is_pd_normal'];

            if($youhui_arr) {
                //----判断是否有优惠----
                foreach ($youhui_arr as $kj => $vj) {
                    if ($val['erpwareid'] == $vj['WareId']) {
                        $data2['quan_no'] = $vj['CashRepNo'];
                        $data2['quan_num'] = $vj['WareCashSum'];
                    }
                }
            }
            $order_goods_id = M("OrderGoods")->insertGetId($data2);

            $data2['rec_id']=$order_goods_id;
            $ut[]=$data2;
            $data2=null;
            //扣除商品库存  扣除库存移到 付完款后扣除
            //M('Goods')->where("goods_id = ".$val['goods_id'])->setDec('store_count',$val['goods_num']); //商品减少库存
            if ($val['is_gift'] == 1) {
                $gift_receive[] = M('gift_receive')->add(['user_id' => $user_id, 'prom_id' => $val['prom_id'], 'gift_id' => $discount[$val['prom_id']]['gift_id'], 'add_time' => time(),'gift_num'=>$val['goods_num'],'orderGoods_id'=>$order_goods_id]);
            }
        }

        if (!empty($gift_receive)){
            $gift_receive=implode(',',$gift_receive);
            M('order')->where('order_id', $order_id)->save(['gift_receive_id' => $gift_receive]);
        }

        if ($order['user_money'] > 0) {
            //冻结余额
            M('Users')->where('store_id',$stoid)->where("user_id", $user_id)
                ->setInc('frozen_money', $order['user_money']);
        }
        /*---优惠券冻结---*/
        $quanno = $order['coupon_no'];
        if (!empty($quanno)) {
            $dada = ['CashRepNo' => $quanno, 'user_id' => $user_id, 'BillDate' => time()];
            //冻结优惠券
            M('frozen_quan')->save($dada);
        }

        //拼单商品不参与分销
        if(empty($data['pt_prom_id'])) {
            //分销开关全局
            $distribut_switch = tpCache('distribut.switch', getMobileStoId());
            mlog("分成开关-" . $order['order_id'] . $order['order_sn'] . ":" . $distribut_switch, 'rebate_log/' . getAdmStoId());

            $dis=tpCache('distribut', getMobileStoId());
            mlog("分成参数-" . $order['order_id'] . $order['order_sn'] . ":" . json_encode($dis), 'rebate_log/' . getAdmStoId());

            if ($distribut_switch == 1 && file_exists(APP_PATH . 'common/logic/DistributLogic.php')) {
                $distributLogic = new \app\common\logic\DistributLogic();
                $distributLogic->rebate_log($order, getMobileStoId(), $ut); // 生成分成记录,$ut就是从表数组
            }
        }

        //if(!empty($car_price['payables']) {
        // 如果有微信公众号 则推送一条消息到微信
        //$user = M('users')->where("user_id", $user_id)->find();
        //if ($user['oauth'] == 'weixin') {
        //$wx_user = M('wx_user')->find();
        //$jssdk = new \app\mobile\logic\Jssdk($wx_user['appid'], $wx_user['appsecret']);
        //$wx_content = "你刚刚下了一笔订单:{$order['order_sn']} 尽快支付,过期失效!";
        //$jssdk->push_msg($user['openid'], $wx_content);
        //}
        //}
        //用户下单, 发送短信给商家
        //$res = checkEnableSendSms("3");
        //$sender = tpCache("shop_info.mobile",getMobileStoId());
        /*---
        if($res && $res['status'] ==1 && !empty($sender)){

            $params = array('consignee'=>$order['consignee'] , 'mobile' => $order['mobile']);
            $resp = sendSms("3", $sender, $params);
        }---*/
        // 如果应付金额为0  可能是余额支付 + 积分 + 优惠券 这里订单支付状态直接变成已支付
        return array('status' => 1, 'msg' => '提交订单成功', 'result' => $order_sn); // 返回新增的订单id
    }


    /**
     *  添加一个订单,送礼神器添加订单
     * @param type $user_id 用户id
     * @param type $address_id 地址id
     * @param type $shipping_code 物流编号
     * @param type $invoice_title 发票
     * @param type $coupon_id 优惠券id
     * @param type $car_price 各种价格
     * @param type $user_note 用户备注
     * @param type $stoid 门店ID
     * @param type $order_goods 订单商品
     * @return type $order_id 返回新增的订单id
     * @return type isone 生成单个订单
     * @return type $parentno
     */
    public function addOrder2($user_id, $address_id, $shipping_code, $invoice_title, $car_price,
                             $order_goods = null, $coupon_id = '',
                             $user_note = '', $stoid = 0, $exptype = 0, $parentno = "", $pickup_id = 0, $discount = array(),$userarr=null, $kl_man_num=0,$kl_num=0,$lb_type=0,$state=0
    )
    {
        // 仿制灌水 1天只能下 50 单  // select * from `tp_order` where user_id = 1  and order_sn like '20151217%'
        $order_count = M('Order')->where("user_id", $user_id)->where('order_sn', 'like', date('Ymd') . "%")->count(); // 查找购物车商品总数量
        if ($order_count >= 50)
            return array('status' => -9, 'msg' => '一天只能下50个订单', 'result' => '');
        //0插入订单 order

        $address=null;
        if ($exptype == 0) {
            if (empty($shipping_code)) {
                return array('status' => -9, 'msg' => '请选择物流', 'result' => '');
            }
            $address = M('UserAddress')->where("address_id", $address_id)->find();
            $shipping = M('shipping')->where("shipping_code", $shipping_code)->find();
        }

        //$uerp = M('users')->alias('a')->join('store b', 'a.store_id=b.store_id')->where("a.store_id", $stoid)->field('a.*,b.ERPId')->find();
        $uerp=null;
        if(empty($userarr) || $userarr['mobile']==""){
            $uerp= M('users')->where("store_id", $stoid)->find();
        }else{
            $uerp=$userarr;
        }
        $uerp['ERPId']=tpCache('shop_info.ERPId',$stoid);

        $order_sn = 'g_'.$uerp['ERPId'] . date('YmdHis'). get_total_millisecond(). rand(1000, 9999);
        /*--是否是单个单--*/
        if (empty($parentno)) {
            $parentno = $order_sn;
        }
        if (!empty($discount['coupon'])){
            $coupon_list = implode(',',$discount['coupon']);
        }else{
            $coupon_list = 0;
        }
        /*----
            'consignee' => $address['consignee'], // 收货人
            'province' => $address['province'],//'省份id',
            'city' => $address['city'],//'城市id',
            'district' => $address['district'],//'县',
            'twon' => $address['twon'],// '街道',
            'address' => $address['address'],//'详细地址',
            'mobile' => $address['mobile'],//'手机',
            'zipcode' => $address['zipcode'],//'邮编',
            'email' => $address['email'],//'邮箱',
        -----*/
        $data = array(
            'order_sn' => $order_sn, // 订单编号
            'parent_sn' => $parentno, // 组合订单编号
            'user_id' => $user_id, // 用户id
            'shipping_code' => $shipping_code,//'物流编号',
            'shipping_name' => $shipping['shipping_name'], //'物流名称',
            'invoice_title' => $invoice_title, //'发票抬头',
            'goods_price' => $car_price['goodsFee'],//'商品价格',
            'shipping_price' => $car_price['postFee'],//'物流价格',
            'user_money' => $car_price['balance'],//'使用余额',
            'coupon_price' => $car_price['couponFee'],//'使用优惠券',
            'coupon_no' => $coupon_id,
            'integral' => $car_price['pointsFee'], //'使用积分
            'integral_money' => $car_price['pointsFee'],//使用积分+钱 的钱的那一部分
            'total_amount' => ($car_price['goodsFee'] + $car_price['postFee']),// 订单总额
            'order_amount' => $car_price['payables'],//'应付款金额',
            'add_time' =>microtime_float(), // 下单时间
            'order_prom_id' => $car_price['order_prom_id'],//'订单优惠活动id',
            'order_prom_amount' => $car_price['order_prom_amount'],//'订单优惠活动优惠了多少钱',
            'discount_amount' => (float)$car_price['discount_amount'],//'优惠促销活动优惠了多少钱',
            'user_note' => $user_note, // 用户下单备注
            'store_id' => $stoid, // 门店ID
            'pickup_id' => $pickup_id, // 门店ID
            'exp_type' => $exptype, // 配送方式
            'give_integral' => (int)$discount['int'], // 购买商品赠送积分
            'give_coupon_id' => $coupon_list, // 购买商品赠送优惠券列表
            'kl_num' => $kl_num, // 单人领取的数量
            'lb_type' => $lb_type, // 显示礼包的类型
            'kl_totalnum' => $kl_num*$kl_man_num, // 可领的总数
            'kl_man_num' => $kl_man_num, // 可领的总数
            'bstate' => $state, // 订单状态
        );

        /*--自提的时候判断--*/
        if ($exptype == 1) {
            //$u = M("users")->where("user_id", $user_id)->find();
            $u=$uerp;
            $data['consignee'] = $u["nickname"]; // 收货人
            $data['mobile'] = $u["mobile"];//'手机',
            $data['address'] = '';//'详细地址',

            if(!$data['consignee']) $data['consignee']=$u["mobile"];
        }

        $data['order_id'] = $order_id = M("giftuser_order")->insertGetId($data);
        $order = $data;//M('Order')->where("order_id", $order_id)->find();
        if (!$order_id)
            return array('status' => -8, 'msg' => '添加订单失败', 'result' => NULL);
        $cartList = $order_goods;
        foreach ($cartList as $key => $val) {
            $goods = M('goods')->where("goods_id", $val['goods_id'])->find();
            $data2['order_id'] = $order_id; // 订单id
            $data2['order_sn'] = $order_sn; // 订单编号
            $data2['goods_id'] = $val['goods_id']; // 商品id
            $data2['goods_name'] = $goods['goods_name']; // 商品名称
            $data2['goods_sn'] = $goods['goods_sn']; // 商品货号
            $data2['goods_num'] = $val['goods_num']; // 购买数量
            $data2['market_price'] = $val['market_price']; // 市场价
            $data2['goods_price'] = $val['goods_price']; // 商品价
            $data2['spec_key'] = $val['spec_key']; // 商品规格
            $data2['spec_key_name'] = $val['spec_key_name']; // 商品规格名称
            $data2['member_goods_price'] = $val['member_goods_price']; // 会员折扣价
            $data2['cost_price'] = $goods['cost_price']; // 成本价
            $data2['prom_type'] = $val['prom_type']; // 0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠 , 5搭配促销
            $data2['prom_id'] = $val['prom_id']; //活动id
            $data2['store_id'] = $stoid; //门店ID
            $data2['pick_id'] = $pickup_id; //门店supplyid
            $data2['is_collocation'] = $val['is_collocation'];
            $data2['give_integral'] = $goods['give_integral'];
            $order_goods_id = M("giftuser_order_goods")->insertGetId($data2);
            // 扣除商品库存  扣除库存移到 付完款后扣除
            //M('Goods')->where("goods_id = ".$val['goods_id'])->setDec('store_count',$val['goods_num']); //商品减少库存
            if ($val['is_gift'] == 1) {
                $gift_receive[] = M('gift_receive')->add(['user_id' => $user_id, 'prom_id' => $val['prom_id'], 'gift_id' => $discount[$val['prom_id']]['gift_id'], 'add_time' => time()]);
            }
        }

        if (!empty($gift_receive)){
            $gift_receive=implode(',',$gift_receive);
            M('order')->where('order_id', $order_id)->save(['gift_receive_id' => $gift_receive]);
        }

        if ($order['user_money'] > 0) {
            //冻结余额
            M('Users')->where("user_id", $user_id)->setInc('frozen_money', $order['user_money']);
        }
        /*---优惠券冻结---*/
        $quanno = $order['coupon_no'];
        if (!empty($quanno)) {
            $dada = ['CashRepNo' => $quanno, 'user_id' => $user_id, 'BillDate' => time()];
            //冻结优惠券
            M('frozen_quan')->save($dada);
        }

        //分销开关全局
        $distribut_switch = tpCache('distribut.switch', getMobileStoId());
        mlog("分成开关-" . $order['order_id'] . $order['order_sn'] . ":" . $distribut_switch, 'rebate_log/' . getAdmStoId());

        if ($distribut_switch == 1 && file_exists(APP_PATH . 'common/logic/DistributLogic.php')) {
            $distributLogic = new \app\common\logic\DistributLogic();
            $distributLogic->rebate_log($order, getMobileStoId()); // 生成分成记录
        }
        // 如果应付金额为0  可能是余额支付 + 积分 + 优惠券 这里订单支付状态直接变成已支付
        if ($data['order_amount'] == 0) {
            update_pay_status_gift2($order['order_sn'], 1);
        }
        return array('status' => 1, 'msg' => '提交订单成功', 'result' => $order_sn); // 返回新增的订单id
    }


    /**
     * 查看购物车的商品数量
     * @param type $user_id
     * $mode 0  返回数组形式  1 直接返回result
     */
    public function cart_count($user_id, $mode = 0)
    {
        $count = M('Cart')->where(['user_id' => $user_id, 'selected' => 1])->count();
        if ($mode == 1) return $count;
        return array('status' => 1, 'msg' => '', 'result' => $count);
    }

    /**
     * 获取商品团购价
     * 如果商品没有团购活动 则返回 0
     * @param type $attr_id
     * $mode 0  返回数组形式  1 直接返回result
     */
    public function get_group_buy_price($goods_id, $mode = 0)
    {
        $group_buy = M('GroupBuy')->where(['goods_id' => $goods_id, 'start_time' => ['<=', time()], 'end_time' => ['>=', time()]])->find(); // 找出这个商品
        if (empty($group_buy))
            return 0;

        if ($mode == 1) return $group_buy['groupbuy_price'];
        return array('status' => 1, 'msg' => '', 'result' => $group_buy['groupbuy_price']);
    }

    /**
     * 用户登录后 需要对购物车 一些操作
     * @param type $session_id
     * @param type $user_id
     */
    public function login_cart_handle($session_id, $user_id)
    {
        if (empty($session_id) || empty($user_id))
            return false;
        // 登录后将购物车的商品的 user_id 改为当前登录的id            
        M('cart')->where("session_id", $session_id)->save(array('user_id' => $user_id));
        // 查找购物车两件完全相同的商品
        $cart_id_arr = DB::query("select id from `__PREFIX__cart` where user_id = $user_id group by  goods_id,spec_key having count(goods_id) > 1");
        if (!empty($cart_id_arr)) {
            $cart_id_arr = get_arr_column($cart_id_arr, 'id');
            $cart_id_str = implode(',', $cart_id_arr);
            M('cart')->delete($cart_id_str); // 删除购物车完全相同的商品
        }
    }

    //购物车list,$selected是否选择,$state为是否立即购买
    public function getCartlist($user = array(),$stoid=0,$session_id = '', $selected = 0,$state=0){
        if(empty($stoid)) $stoid=getMobileStoId();
        $t=time();
        $where = " 1 = 1 ";
        if ($selected != NULL)
            $where = " selected = $selected "; // 购物车选中状态
        $bind = array();
        if ($user['user_id'])// 如果用户已经登录则按照用户id查询
        {
            $where .= " and a.user_id = " . $user['user_id'];
            // 给用户计算会员价 登录前后不一样
        } else {
            $where .= " and a.session_id = :session_id";
            $bind['session_id'] = $session_id;
            $user['user_id'] = 0;
        }

        $where .= ' and state='.$state;
        $where .= ' and a.store_id=' .$stoid;
        //实时获取数据
        //$m_db=Db::connect('mian_db');
        $cartList = M('Cart')->alias("a")->join("pick_up b", "a.pick_id=b.pickup_id and a.store_id=b.store_id", 'left')
            ->join('goods c', "a.goods_id=c.goods_id",'left')
            ->where($where)->bind($bind)
            ->where("c.on_time < ".$t." and (down_time > ".$t." or down_time=0 or down_time='' or down_time is null) ")
            ->where("c.is_on_sale=1")
            ->field("a.id,a.spec_key_name,a.user_id,a.goods_id,c.erpwareid,a.goods_name,a.market_price,a.goods_price,a.member_goods_price,a.goods_num,a.selected,a.pick_id,a.state,a.is_gift,a.is_collocation,a.store_id,a.main_cart_id,a.is_integral_normal,a.is_pd_normal,b.pickup_id,b.pickup_name,c.original_img,b.distr_type as bdistr_type,c.distr_type,c.shop_price,goods_spec,goods_color,a.spec_key,store_count,c.prom_type,c.prom_id,
            c.viplimited,c.mz_price,c.cardprice1,c.cardprice2,c.cardprice3,a.prom_type as prom_type1,a.prom_id as prom_id1,a.gift_id")
            ->order('id asc')->select();  // 获取购物车商品
        return $cartList;
    }
    //处理购物车
    public function handle_cart($cartList,$user,$isupdate=0){
        $anum = $total_price = $cut_fee = 0;
        $mz_switch = tpCache('shopping.is_beauty',getMobileStoId());//美妆
        $rank_switch = tpCache('shopping.rank_switch',getMobileStoId());//等级价格
        $mz_vip = $user['is_mzvip'];
        $rank_field = $user['card_field'];

        $now=time();
        $obj = M('activitylist')->where(['is_end' => 0, 'good_object' => 0, 'prom_type'=>3,
            'store_id' => getMobileStoId()])
            ->where('s_time<'.$now.' and e_time>'.$now)
            ->field('act_id as id,goods_listid,prom_type')->find();

        foreach ($cartList as $k => $v) {
            $is_get_p=0;
            if($v['is_integral_normal']==1 || $v['is_pd_normal']==1 ){
                $is_get_p=1;
            }

            if ($v['prom_type'] == 0){
                if (!empty($mz_vip) && !empty($mz_switch) && $v['mz_price'] >0){
                    $cartList[$k]['shop_price'] = $v['shop_price'] = $v['mz_price'];//美妆会员价格
                }
                if (!empty($rank_switch)){
                    if (!empty($rank_field) && $v[$rank_field] >0 && strtotime($user['card_expiredate'])>time() ){
                        $cartList[$k]['shop_price'] = $v['shop_price'] = $v[$rank_field];//等级会员价格
                    }
                }
            }

            if (!empty($obj) && empty($v['prom_type']) && empty($v['is_collocation'])) {
                if(empty($obj['goods_listid'])){
                    $cartList[$k]['prom_type'] = 3;
                    $cartList[$k]['prom_id'] = $obj['id'];
                }
                else{
                    $str=",".$v['goods_id'].",";
                    if(strpos($obj['goods_listid'],$str)===false) {
                        $cartList[$k]['prom_type'] = $obj['prom_type'];
                        $cartList[$k]['prom_id'] = $obj['id'];
                    }
                }
            }

            if($v['is_gift']==1){
                $cartList[$k]['prom_type'] = 3;
                $cartList[$k]['prom_id'] = $v['prom_id1'];
            }

            /*--循环更新状态--*/
            if($isupdate==1 && $v['is_collocation'] == 0) {
                if ($v['is_gift'] == 0) {
                    if ($v["prom_type"] != 0 && $v['prom_type'] != 3 && $v['prom_type'] != 5  && $is_get_p!=1) {
                        $cartList[$k]['prom'] = get_goods_promotion1($v, null, $user['user_id']);
                        if ($v['goods_price'] != $cartList[$k]['prom']['price']) {
                            $cartList[$k]['member_goods_price'] = $cartList[$k]['goods_price'] = $cartList[$k]['prom']['price'];
                            $v['member_goods_price'] = $v['goods_price'] = $cartList[$k]['prom']['price'];
                            $data = ['goods_price' => $cartList[$k]["goods_price"],
                                     "member_goods_price" => $cartList[$k]['goods_price'],
                                     'prom_type'=>$cartList[$k]['prom']['prom_type'],
                                     'prom_id'=>$cartList[$k]['prom']['prom_id'],
                                    ];
                            M("Cart")->where("id", $v['id'])->save($data);
                        }
                    }else if($v['prom_type1'] == 3 && $v['prom_type']!=0 &&
                         ($v['prom_type']==4 or $v['prom_type']==6)
                    ){
                        $now = time();
                        $where = [
                            'end_time' => ['gt', $now],
                            'start_time' => ['lt', $now],
                            'id' => $v['prom_id1'],
                            'is_end' => 0,
                        ];
                        $prominfo = M('prom_goods')->where($where)->field('id')->find();
                        if (empty($prominfo)) {
                            $data=[ 'prom_type'=>0,'prom_id'=>0,];
                            M("Cart")->where("id", $v['id'])->save($data);
                            $cartList[$k]['prom_type']=0;
                            $cartList[$k]['prom_id']=0;
                        }else{
                            $cartList[$k]['prom_type']=3;
                            $cartList[$k]['prom_id']=$prominfo['id'];
                        }
                    }
                    else if($v['prom_id']!=$v['prom_id1'] && $v["prom_type"]=0)
                    {
                        //更新最新的商品价格
                        if ($v['goods_price'] != $v["shop_price"]) {
                            $date = ['goods_price' => $v["shop_price"], "member_goods_price" => $v['shop_price']];
                            $cartList[$k]["member_goods_price"] = $v['shop_price'];
                            $cartList[$k]["goods_price"] = $v['shop_price'];
                            M("Cart")->where("id", $v['id'])->save($date);
                        }
                        $cartList[$k]['prom_type']=0;
                        $cartList[$k]['prom_id']=0;
                        $cartList[$k]['prom_type1']=0;
                        $cartList[$k]['prom_id1']=0;
                    }
                }
            }

            //当是全场优惠活动的时候,拼单或者积分的普通购买,此时商品的prom_type绝对不等于零
            if($v['prom_type']!=$v['prom_type1'] && $v['prom_type1']==3 &&
                ($v['prom_type']==4 or $v['prom_type']==6)
            ){
                $now = time();
                $where = [
                    'end_time' => ['gt', $now],
                    'start_time' => ['lt', $now],
                    'id' => $v['prom_id1'],
                    'is_end' => 0,
                ];
                $prominfo = M('prom_goods')->where($where)->field('id')->find();
                if (empty($prominfo)) {
                    $data=[ 'prom_type'=>0,'prom_id'=>0,];
                    M("Cart")->where("id", $v['id'])->save($data);
                    $cartList[$k]['prom_type']=0;
                    $cartList[$k]['prom_id']=0;
                }else{
                    $cartList[$k]['prom_type']=3;
                    $cartList[$k]['prom_id']=$prominfo['id'];
                }
            }

            /*------商品规格,价格--------*/
            $sp1 = $v["goods_spec"];
            $cn1 = $v["goods_color"];
            $guige1 = "规格";
            $gorder1 = 1;
            $tgg1 = "";
            if ($sp1 == "" && $cn1 == "") {
                $tgg1 = $guige1 . $gorder1;
                $gorder1++;
            } else if ($sp1 != "" && $cn1 == "") {
                $tgg1 = $sp1;
            } else if ($sp1 == "" && $cn1 != "") {
                $tgg1 = $cn1;
            } else {
                $tgg1 = $sp1 . "/" . $cn1;
            }
            $cartList[$k]['guige'] = $tgg1;
            $cartList[$k]['goods_fee'] = $v['goods_num'] * $v['member_goods_price'];
            //$cartList[$k]['store_count'] = getGoodNum($v['goods_id'], $v['spec_key']); // 最多可购买的库存数量
            $anum += $v['goods_num'];
            // 如果要求只计算购物车选中商品的价格 和数量  并且  当前商品没选择 则跳过
            if ($v['selected'] == 0)
                continue;
            $cut_fee += $v['goods_num'] * $v['market_price'] - $v['goods_num'] * $v['member_goods_price'];
            $total_price += $v['goods_num'] * $v['member_goods_price'];
        }

        $total_price = array('total_fee' => $total_price, 'cut_fee' => $cut_fee, 'num' => $anum,); // 总计
        return [$total_price,$cartList];
    }

    //判断是否包邮
    public function isby($address,$free_id){
        if(empty($free_id)) return 1;
         //不包邮地区
         $frlist=M('feemail_region')->alias('a')
             ->join('area_feemail b','a.area_feemail_id=b.id')
             ->join('region c','a.region_id=c.id')
             ->where("b.id",$free_id)
             ->field('c.id,c.level')
             ->select();

         $isby=1;
         if($frlist) {
             foreach ($frlist as $k => $v) {
                 switch ($v['level']) {
                     case "1":
                         if($v['id']==$address['province']) $isby=0;
                         break;
                     case "2":
                         if($v['id']==$address['city']) $isby=0;
                         break;
                     case "3":
                         if($v['id']==$address['district']) $isby=0;
                         break;
                 }
                 if($isby==0) break;
             }
         }else{
             $isby=0;
         }
         return $isby;
    }
    public function isby2($p,$c,$d,$free_id){
        if(empty($free_id)) return 1;
        //不包邮地区
        $frlist=M('feemail_region')->alias('a')
            ->join('area_feemail b','a.area_feemail_id=b.id')
            ->join('region c','a.region_id=c.id')
            ->where("b.id",$free_id)
            ->field('c.id,c.level')
            ->select();

        $isby=1;
        if($frlist) {
            foreach ($frlist as $k => $v) {
                switch ($v['level']) {
                    case "1":
                        if($v['id']==$p) $isby=0;
                        break;
                    case "2":
                        if($v['id']==$c) $isby=0;
                        break;
                    case "3":
                        if($v['id']==$d) $isby=0;
                        break;
                }
                if($isby==0) break;
            }
        }else{
            $isby=0;
        }
        return $isby;
    }
}