UsersLogic.php 78 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 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司,并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。验证码=======================
 * Author: IT宇宙人
 * Date: 2015-09-09
 */

namespace app\home\logic;

use app\home\model\UserAddress;
use think\image\Exception;
use think\Model;
use think\Page;
use think\db;
use think\Cookie;
use think\Cache;

/**
 * 分类逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class UsersLogic extends Model
{
    /*
     * 登陆
     */
    public function login($username, $stoid)
    {
        $result = array();
        if (!$username)
            $result = array('status' => 0, 'msg' => '请填写账号');
        $user = M('users')->where("mobile", $username)->where('store_id', $stoid)->find();
        if (!$user) {
            $result = array('status' => -1, 'msg' => '账号不存在!');
        } elseif ($user['is_lock'] == 1) {
            $result = array('status' => -3, 'msg' => '账号异常已被锁定!!!');
        } else {
            //查询用户信息之后, 查询用户的登记昵称
            $levelId = $user['level'];
            $levelName = M("user_level")->where("level_id", $levelId)->where('store_id', $stoid)->getField("level_name");
            $user['level_name'] = $levelName;

            $result = array('status' => 1, 'msg' => '登陆成功', 'result' => $user);
        }
        return $result;
    }

    /*
     * app端登陆
     */
    public function app_login($username, $password)
    {

        $result = array();
        if (!$username || !$password)
            $result = array('status' => 0, 'msg' => '请填写账号或密码');
        $user = M('users')->where("mobile|email", "=", $username)->find();
        if (!$user) {
            $result = array('status' => -1, 'msg' => '账号不存在!');
        } elseif ($password != $user['password']) {
            $result = array('status' => -2, 'msg' => '密码错误!');
        } elseif ($user['is_lock'] == 1) {
            $result = array('status' => -3, 'msg' => '账号异常已被锁定!!!');
        } else {
            //查询用户信息之后, 查询用户的登记昵称
            $levelId = $user['level'];
            $levelName = M("user_level")->where("level_id", $levelId)->getField("level_name");
            $user['level_name'] = $levelName;
            $user['token'] = md5(time() . mt_rand(1, 999999999));
            M('users')->where("user_id", $user['user_id'])->save(array('token' => $user['token'], 'last_login' => time()));
            $result = array('status' => 1, 'msg' => '登陆成功', 'result' => $user);
        }
        return $result;
    }


    //绑定账号
    public function oauth_bind($data = array())
    {
        $user = session('user');
        if (empty($user['openid'])) {
            if (M('users')->where(array('openid' => $data['openid']))->count() > 0) {
                return array('status' => -1, 'msg' => '您的' . $data['oauth'] . '账号已经绑定过账号');
            } else {
                M('users')->where(array('user_id' => $user['user_id']))->save($data);
                return array('status' => 1, 'msg' => '绑定成功', 'result' => $data);
            }
        } else {
            return array('status' => -1, 'msg' => '您的账号已绑定过,请不要重复绑定');
        }
    }

    /*
     * 第三方登录
     */
    public function thirdLogin($data = array(), $stoid = 0)
    {

        if (empty($stoid)) {
            $stoid = getMobileStoId();
        }
        $openid = $data['openid']; //第三方返回唯一标识
        $oauth = $data['oauth']; //来源
        if (!$openid || !$oauth)
            return array('status' => -1, 'msg' => '参数有误', 'result' => '');


        $user = get_user_info($openid, 3, $stoid, $oauth);

        if (!$user) {
            //账户不存在 注册一个
            $map['password'] = '';
            $map['openid'] = $openid;
            if (isset($data['unionid'])) {
                $map['unionid'] = $data['unionid'];
            }
            $na = $this->filterEmoji($data['nickname']);
            $map['nickname'] = $na;
            $map['reg_time'] = time();
            $map['oauth'] = $oauth;
            $map['head_pic'] = $data['head_pic'];
            $map['sex'] = empty($data['sex']) ? 0 : $data['sex'];
            $map['token'] = md5(time() . mt_rand(1, 99999));

            $ck1 = cookie('first_leader');
            if (!empty($ck1))
                $map['first_leader'] = $ck1; // 推荐人id
            $map['store_id'] = $stoid; // 推荐人id
            $map['supplyid'] = getMobileSupplyId($stoid); // 推荐人id


            mlog(json_encode($map), 'getusers/' . $stoid);

            // 成为分销商条件
            /*---
            $distribut_condition = tpCache('distribut.condition', $stoid);
            $distribut_switch = tpCache('distribut.switch', $stoid);
            if ($distribut_condition=== 0 && $distribut_switch===1)  // 直接成为分销商, 每个人都可以做分销
                $map['is_distribut'] = 1;---*/

            $row_id = M('users')->insertGetId($map);
            //$user = M('users')->alias('a')->join('store b',' a.store_id=b.store_id','left')->field('a.*,b.ERPId')->where("a.user_id", $row_id)->find();
            $user = M('users')->where("user_id", $row_id)->find();
            $user['ERPId'] = tpCache('shop_info.ERPId', $stoid);

        } else {


            //更新昵称等信息
            $newnickname = $this->filterEmoji($data['nickname']);
            if ($user['nickname'] != $newnickname || $user['head_pic'] != $data['head_pic'] || $user['oauth'] != $data['oauth'] || $user['unionid'] != $data['unionid']) {

                $updateuser['nickname'] = $newnickname;
                if (isset($data['unionid'])) {
                    $updateuser['unionid'] = $data['unionid'];

                }
                $updateuser['head_pic'] = $data['head_pic'];
                $updateuser['oauth'] = $data['oauth'];
                $updateuser['token'] = md5(time() . mt_rand(1, 99999));

                $updateres = M('users')->where('store_id', getMobileStoId())->where('openid', $openid)->save($updateuser);

            }
            $updateuser['token'] = md5(time() . mt_rand(1, 999999999));
            $updateuser['last_login'] = time();
            M('users')->where("user_id", $user['user_id'])->save(array('token' => $user['token'], 'last_login' => time()));
        }


        return array('status' => 1, 'msg' => '登陆成功', 'result' => $user);
    }

    /**
     * 注册
     * @param $username  邮箱或手机
     * @param $stoid    门店ID
     * @param $open_id  openid
     * @return array
     */
    public function reg($username, $stoid = '', $open_id, $reg_data)
    {
        $is_validated = 0;
        if (empty($stoid)) {
            $stoid = getMobileStoId();
        }
        if (empty($username))
        {
            return array('status' => -1, 'msg' => '手机不能为空,请输入!');
        }
        $sto = tpCache('shop_info', $stoid);//商户信息
        $sto_erpid = $sto['ERPId'];
        //$open_id = 'ou608v8eDheyiw-IB1CrGWBWiEhQ';
        /**
         * 测试阶段使用,直接获取手机号,如果系统中已经存在,直接返回会员信息
         */
        mlog("账套:".json_encode($sto_erpid), 'smslog/' . $stoid);
        mlog("手机:".$username.",openId:".$open_id, 'smslog/' . $stoid);
        mlog("提交注册:".json_encode($reg_data), 'smslog/' . $stoid);
        $ceshi_user = M('users')->where(array('mobile' => $username, 'store_id' => $stoid))->find();
        mlog("会员查找返回:".json_encode($ceshi_user), 'smslog/' . $stoid);
        if ($ceshi_user)
        {
            if ($ceshi_user['mobile']==$username && $ceshi_user['openid'] && $ceshi_user['openid']!=$open_id)
            {
                return array('status' => -1, 'msg' => '该手机已被注册过!', 'result' => $ceshi_user);
            }
            if (($sto_erpid && ($ceshi_user && $ceshi_user['erpvipid'] && $ceshi_user['openid'] && $ceshi_user['mobile'])) || (empty($sto_erpid) && ($ceshi_user && $ceshi_user['mobile'] && $ceshi_user['openid']))) {
                mlog("提交注册001:", 'smslog/' . $stoid);
                return array('status' => 1, 'msg' => '登陆成功', 'result' => $ceshi_user);
            }

        }



        $is_olduserinfo = 0;
        //判断如果openid为空且手机有值的话,取旧的
        if ($ceshi_user['mobile'] && empty($ceshi_user['openid'])) {
            $is_olduserinfo = 1;
            $user_info = $ceshi_user;
        } else {
            $user_info = M('users')->where(array('openid' => $open_id, 'store_id' => $stoid))->find();
        }

        $user_info['ERPId'] = $sto_erpid;
        $user_info['api_token'] = $sto['api_token'];


        if (!$user_info) {//如果会员信息为空,说明获取不到open_id
            insert_errlog($stoid, "会员绑定", "查询会员", "提交的openid:" . $open_id . "返回:" . json_encode($user_info));
            return array('status' => -1, 'msg' => '会员信息有误!');
        }
        //开始逻辑操作
        //最新的线下用户信息,当插入时为插入的会员的信息,当更新时为更新的会员信息
        $new_user_info = "";

        mlog("2 步骤3:" . json_encode($reg_data), 'smslog/' . $stoid);

        //有账套时
        if ($sto_erpid) {
            //用户信息,用于调用接口数据
            $user_data = array();

            if ($reg_data['erpuuid']) {
                $user_data['Id'] = $reg_data['erpuuid'];
            }

            $user_data['MobileTel'] = $username;
            if (!empty($reg_data['name'])) {
                $user_data['VIPName'] = $reg_data['name'];
            }

            if (!empty($reg_data['birthday'])) {
                $user_data['BirthDate'] = $reg_data['birthday'];
                $user_data['IsLunar'] = $reg_data['islunar'];
            }

            if (!empty($reg_data['idcard'])) {
                $user_data['IDCard'] = $reg_data['idcard'];
            }
            if (!empty($reg_data['address'])) {
                $user_data['Address'] = $reg_data['address'];
            }
            if (!empty($reg_data['pickup_id'])) {
                $pick = M("pick_up")->where("pickup_id", $reg_data['pickup_id'])->find();
                if ($pick) {
                    $user_data['StoragesId'] = $pick['keyid'];
                }
            }
            if (!empty($reg_data['sex'])) {
                $user_data['Sex'] = "";
                if ($reg_data['sex'] == 1) $user_data['Sex'] = '男';
                if ($reg_data['sex'] == 2) $user_data['Sex'] = '女';
            }
            if ($reg_data['IntroducerVIPID']) {
                $user_data['IntroducerVIPID'] = $reg_data['IntroducerVIPID'];
            }

            $user_data['property1'] = $open_id;
            $user_data['ClientId'] = uuid();
            mlog("提交会员信息:" . json_encode($user_data), 'smslog/' . $stoid);
            $api = "/api/erp/vip/register";
            $rs = getApiData_java_p($api, $sto_erpid, $user_data, 1, 10, null, "POST",0,1);

            mlog("注册回调:" . $rs, 'smslog/' . $stoid);
            if (empty($rs)) {

                //判断当前会员Id已经绑定openid的话
                $whereMobile['MobileTel'] = $username;
                $rs_one = getApiData_java_p("/api/erp/vip/info/page", $sto_erpid, $whereMobile, 1, 10, null, "GET");
                if (empty($rs_one)) {
                    $user_data['first_leader']=   Cookie::get('first_leader');
                    $user_data['fromuser_id']=$reg_data['fromuser_id'];

                    insert_errlog($stoid, "会员绑定", "线下会员插入" . $api, "提交数据:" . json_encode($user_data) . "返回空值" . $rs_one,$username,json_encode($user_data));
                    return array('status' => -1, 'msg' => '绑定失败,网络繁忙请稍等点击重试【200】!');
                }
                $rs_one_data = json_decode($rs_one, true);
                if ($rs_one_data['code'] != 0 || empty($rs_one_data['data']['pageData'])) {
                    $user_data['first_leader']=   Cookie::get('first_leader');
                    $user_data['fromuser_id']=$reg_data['fromuser_id'];
                    insert_errlog($stoid, "会员绑定", "线下会员插入" . $api, "提交数据:" . json_encode($user_data) . "返回空值" . $rs_one,$username,json_encode($user_data));
                    return array('status' => -1, 'msg' => '绑定失败,网络繁忙请稍等点击重试【200】!');
                }
                $rs_one1datainfo = $rs_one_data['data']['pageData'][0];
                if (empty($rs_one1datainfo['property1']) || $rs_one1datainfo['property1'] != $open_id) {
                    $user_data['first_leader']=   Cookie::get('first_leader');
                    $user_data['fromuser_id']=$reg_data['fromuser_id'];
                    insert_errlog($stoid, "会员绑定", "线下会员插入" . $api, "提交数据:" . json_encode($user_data) . "返回空值" . $rs_one,$username,json_encode($user_data));
                    return array('status' => -1, 'msg' => '绑定失败,网络繁忙请稍等点击重试【201】!');
                }
                $rs = $rs_one;
            }

            if (isJson($rs) == false) {
                insert_errlog($stoid, "会员绑定", "线下会员插入" . $api, "返回:" . json_encode($rs));
                return array('status' => -1, 'msg' => '绑定失败false');
            }
            $rs = json_decode($rs, true);
            if ($rs['code'] != 0) {
                insert_errlog($stoid, "会员绑定", "线下会员插入" . $api, "返回:" . json_encode($rs));
                return array('status' => -1, 'msg' => '绑定失败' . $rs['code']);
            }
            //如果再次查询有值的话,就取第一条
            if ($rs_one1datainfo) {
                $new_user_info = $rs_one1datainfo;
            } else {
                $new_user_info = $rs['data'];
            }
            if (empty($new_user_info) || empty($new_user_info['VIPNo'])) {
                insert_errlog($stoid, "会员绑定", "线下会员插入" . $api, "返回:" . json_encode($new_user_info));
                return array('status' => -1, 'msg' => '网络繁忙,请点击重试!');
            }

            $map['erpvipid'] = $new_user_info['Id'];
            $map['erpvipno'] = $new_user_info['VIPNo'];
            $map['vipname'] = $new_user_info['VIPName'];
            $map['openid'] = $open_id;
            switch ($new_user_info['Sex']) {
                case "男":
                    $map['sex'] = 1;
                    break;
                case "女":
                    $map['sex'] = 2;
                    break;
                default:
                    $map['sex'] = 0;
                    break;

            }
            if ($new_user_info['IDCard']) {
                $map['idcard'] = $new_user_info['IDCard'];
            }
            $map['birthday'] = strtotime($new_user_info['BirthDate']);
            $map['islunar'] = $new_user_info['Islunar'] == '1' ? 1 : 2;
            if ($new_user_info['Address']) {
                $map['address'] = $new_user_info['Address'];
            }
            $map['mobile'] = $new_user_info['MobileTel'];
            if ($new_user_info['EMail']) {
                $map['email'] = $new_user_info['EMail'];
            }
            $pick = M("pick_up")->where("keyid", $new_user_info['StoragesId'])->where("keyid<>''")->field("pickup_id")->find();
            if ($pick) {
                $map['pickup_id'] = $pick['pickup_id'];
            }
            //判断PLUS是否有值
            if ($new_user_info['GradeCardID'] && $new_user_info['ExpiryDate'])
            {
                $switch_list = tpCache('basic.switch_list', $stoid);
                if ($switch_list)
                {
                    $switch_list=json_decode($switch_list,true);
                    $rank_switch=$switch_list['rank_switch'];
                    if ($rank_switch==2)
                    {
                        $Cardwhere['CardId']=$new_user_info['GradeCardID'];
                        $rs_cardset = getApiData_java_p("/api/erp/vip/mem/bership/get", $sto_erpid, $Cardwhere, 1, 10, null, "GET");
                        if ($rs_cardset) {
                            $rs_cardset=json_decode($rs_cardset,true);
                            $rs_cardset_data=$rs_cardset['data'];
                            $getcard_field="cardprice1";
                            switch ($rs_cardset_data['CorrPrice']) {
                                case "Price1":
                                    $getcard_field="cardprice1";
                                    break;
                                case "Price2":
                                    $getcard_field="cardprice2";
                                    break;
                                case "Price3":
                                    $getcard_field="cardprice3";
                                    break;
                            }
                            $map['card_expiredate'] = $new_user_info['ExpiryDate'];
                            $map['card_field'] = $getcard_field;
                        }


                    }
                }
            }




        } else {
            $map['openid'] = $open_id;
            $map['mobile'] = $username;
            $map['vipname'] = $reg_data['name'];
            $map['sex'] = $reg_data['sex'] != '' ? $reg_data['sex'] : 0;
            $map['idcard'] = $reg_data['idcard'];
            $map['birthday'] = strtotime($reg_data['birthday']);
            $map['islunar'] = $reg_data['islunar'];
            $map['address'] = $reg_data['address'];
            $map['pickup_id'] = $reg_data['pickup_id'];
        }
        //有账套  end
        $map['reg_time'] = time();//绑定重新更新注册时间
        $map['mobile_validated'] = 1;

        //更新线上会员信息
        // 成为分销商条件
        $distribut_condition = tpCache('distribut.condition', $stoid);
        $distribut_switch = tpCache('distribut.switch', $stoid);
        if ($distribut_switch === 1 && $distribut_condition === 0 && $user_info['is_distribut'] == 0)  // 本来要购买成为分销,后来商家改为直接注册就可以成为分销商进行更改
        {
            //判断分销可以注册的人数
            $distr_num = M('store_distribut')->where('store_id', $stoid)->field('distribut_num')->find();
            $count1 = M("users")->where('store_id', getMobileStoId())->where('is_distribut', 1)->count();
            if ($distr_num['distribut_num'] > $count1) {
                $map['is_distribut'] = 1;
                $map['be_distribut_time'] = time();
                $map['be_dis_condition'] = "直接购买成为分销商";
            } else {
                $is_out = M("store_module_endtime")
                    ->where('store_id', getMobileStoId())
                    ->where('type', 2)->find();
                if (empty($is_out)) {
                    $yy = M('distri_price')->where('type', 0)->where('money', 0)->find();
                    $allnum = $yy['user_num'];
                    if ($allnum > $count1) {
                        $map['is_distribut'] = 1;
                        $map['be_distribut_time'] = time();
                        $map['be_dis_condition'] = "直接购买成为分销商";
                    }
                }
            }
        }

        $first_leader = Cookie::get('first_leader');//上级会员ID
        mlog('mobile:' . $username . '-' . $first_leader, 'reg/' . $stoid);

        $first_info = null;
        if ($first_leader != "") {
            $first_info = M('users')->where(array('user_id' => $first_leader, 'store_id' => $stoid))->find();
            if ($first_info) {
                $map['Inviter_id'] = $first_leader;
            }

            if ($first_info && $first_info['is_distribut'] == "1") {
                $map['first_leader'] = $first_leader;
            } else {
                //往上找会员是否的分销商,
                //如果是分销商则注册会员的 first_leader 就是此分销商
                $first_info0 = M('users')->where(array('user_id' => $first_info['first_leader'], 'store_id' => $stoid))->find();
                if ($first_info0 && $first_info0['is_distribut'] == "1") {
                    $map['first_leader'] = $first_info0['user_id'];
                }
            }

            if ($map['first_leader']) {
                $first_leader = M('users')->where("user_id", $map['first_leader'])->field("first_leader,second_leader")->find();
                $map['second_leader'] = $first_leader['first_leader']; //  第一级推荐人
                $map['third_leader'] = $first_leader['second_leader']; // 第二级推荐人
                //他上线分销的下线人数要加1
                M('users')->where(array('user_id' => $map['first_leader']))->setInc('underling_number');
                M('users')->where(array('user_id' => $map['second_leader']))->setInc('underling_number');
                M('users')->where(array('user_id' => $map['third_leader']))->setInc('underling_number');
            } else {
                $map['first_leader'] = 0;
            }

            //如果邀请人存在,要弄个token
            if ($first_info) {
                $first_info['api_token'] = tpCache('shop_info.api_token', $stoid);
            }
        }

        //--介绍人--
        $intr_user = null;
        if (!empty($reg_data['fromuser_id'])) {
            $map['fromuser_id'] = $reg_data['fromuser_id'];
        }

        mlog("users:" . json_encode($map), 'smslog/' . $stoid);
        $falg = M('users')->where('user_id', $user_info['user_id'])->save($map);//线上用户信息
        //如果更新旧的话要删除新产生的记录
        if ($is_olduserinfo) {
            M('users')->where(array('store_id' => $user_info['store_id'], 'user_id' => array('neq', $user_info['user_id']), 'openid' => $open_id, 'mobile' => array('eq', '')))->delete();
        }
        mlog("isok:" . $falg, 'smslog/' . $stoid);

        if ($falg === false) {
            insert_errlog($stoid, "会员绑定", "保存线上数据", "保存失败:提交的数据的" . json_encode($map));
            return json(array('status' => -1, 'msg' => '绑定失败2'));
        }
        //如果是新会员才增
        if (empty($is_olduserinfo)) {
            $r = M('usercount')->where('daynum', date("Y-m-d"))->where('store_id', $stoid)->find();
            if ($r) {
                $dd['new_vipnum'] = $r['new_vipnum'] + 1;
                $dd['sum_vipnum'] = $r['sum_vipnum'] + 1;
                M('usercount')->where('id', $r['id'])->save($dd);
            } else {
                //最大数
                $r0 = M('usercount')->where('store_id', $stoid)->Max('daynum');

                $dd['daynum'] = date("Y-m-d");
                $dd['store_id'] = $stoid;
                $dd['new_vipnum'] = 1;

                if ($r0) {
                    $dd['sum_vipnum'] = $r0 + 1;
                } else {
                    //统计的数量
                    $num = M('users')->where('store_id', $stoid)->where("mobile<>''")
                        ->count();
                    $dd['sum_vipnum'] = $num;
                }

                M('usercount')->save($dd);
            }
        }

        //减少分销人数
        if ($map['is_distribut'] === 1) {
        }

        //后续操作 ZXH更新于2017-6-19   跟新内容:判断商家注册的信息。1==默认,2==自定义
        // 会员注册赠送积、优惠券
        //获取最新的用户信息

        $news_info = M("users")
            ->where("user_id", $user_info['user_id'])->find();
        $news_info['api_token'] = tpCache('shop_info.api_token', $stoid);
        $news_info['ERPId'] = $sto_erpid;

        $reg_type = tpCache('basic.reg_type', $stoid);
        //默认的注册规则
        if ($reg_type == 0) {
            mlog("61", 'smslog/' . $stoid);
            //$reg_info = M('store_config')->where('store_id',$stoid)->find();
            /*--读取默认注册属性--*/
            $reg_def = tpCache('basic.reg_default', $stoid);
            $reg_default = json_decode($reg_def, true);
            $reg_def_ty = $reg_default['reg_def_ty'];

            mlog("62", 'smslog/' . $stoid);

            if ($reg_def_ty == 0) {//积分
                //如果赠送的积分大于0
                if ($reg_default['jf'] > 0) {
                    if ($sto_erpid) {
                        /*---
                        $data = array(
                            'VIPId' => $news_info["erpvipid"],//会员id
                            'OrderNo' => date('YmdHis') . rand(1000, 9999),//单号
                            'Integral' => $reg_default['jf'],//积分
                            'Remark' => '注册送积分',
                        );
                        $add_rs = getApiData_java_p("/api/erp/vip/integral/update", $sto_erpid, $data, 1, 10, null, "PUT");
                        mlog("62送积分:" . json_encode($data) . "返回" . $add_rs, 'smslog/' . $stoid);
                        $add_rs = json_decode($add_rs, true);--*/
                        $res=com_update_integral($sto_erpid,$news_info,$reg_default['jf'],"注册送积分",$module="logic/userslogic");
                        if(!$res){
                            return json(array('status' => -1, 'msg' => '服务器繁忙, 请联系管理员!'));
                        }
                    } else {
                        accountLog($news_info["user_id"], 0, $reg_default['jf'], '注册送积分', 0, $stoid, $news_info["pay_points"]);//线上表
                    }
                }

            }
            else  if ($reg_def_ty == 2) {//成长值
                //--如果赠送的成长值大于0--
                if ($reg_default['reg_cz'] > 0 && $sto_erpid) {
                    $this->send_czz($news_info['erpvipid'],$reg_default['reg_cz'],$sto_erpid,"注册赠送成长值");
                }
            }
            else {
                if ($reg_default['coupon'] != "") {//优惠券
                    $coupon = M("coupon")->where(array("id"=>$reg_default['coupon'],'send_start_time'=>array('elt',time()),'send_end_time'=>array('egt',time())))->find();
                    if ($coupon) {
                        $this->reg_send_quan($coupon, $news_info, $sto_erpid, $stoid);
                    }
                }
            }
        } //自定义
        else {
            mlog("62", 'smslog/' . $stoid);
            $reg_info = json_decode(tpCache('basic.reg_info', $stoid), true);
            $jf = 0;$czz=0;
            mlog("620:" . json_encode($reg_info), 'smslog/' . $stoid);
            if (!empty($reg_data['name']) && $reg_info['name_state'] == 1) {
                if($reg_info['name_val_type']){
                    $czz+=$reg_info['name'];
                }else{
                    $jf += $reg_info['name'];
                }

            }
            if (!empty($reg_data['birthday']) && $reg_info['birthday_state'] == 1) {
                if($reg_info['birthday_type']){
                    $czz=$reg_info['birthday'];
                }else {
                    $jf += $reg_info['birthday'];
                }
            }
            if (!empty($reg_data['idcard']) && $reg_info['idcard_state'] == 1) {
                if($reg_info['idcard_type']){
                    $czz+=$reg_info['idcard'];
                }else {
                   $jf += $reg_info['idcard'];
                }
            }
            if (!empty($reg_data['address']) && $reg_info['address_state'] == 1) {
                if($reg_info['address_type']){
                    $czz+=$reg_info['address'];
                }else {
                    $jf += $reg_info['address'];
                }
            }
            if (!empty($reg_data['pickup_id']) && $reg_info['pick_state'] == 1) {
                if($reg_info['pick_type']){
                    $czz+=$reg_info['pick'];
                }else {
                    $jf += $reg_info['pick'];
                }
            }
            if (!empty($reg_data['sex']) && $reg_info['sex_state'] == 1) {
                if($reg_info['sex_state_type']){
                    $czz+=$reg_info['sex'];
                }else {
                    $jf += $reg_info['sex'];
                }
            }
            //存在会员
            if (!empty($reg_data['fromuser_id']) && $reg_info['introducer_state'] == 1) {
                if($reg_info['introducer_type']){
                    $czz+=$reg_info['introducer'];
                }else {
                    $jf += $reg_info['introducer'];
                }
            }

            mlog("621:" . $jf, 'smslog/' . $stoid);
            if ($jf > 0) {
                if ($sto_erpid) {
                    /*--
                    $data = array(
                        'VIPId' => $news_info["erpvipid"],//会员id
                        'OrderNo' => date('YmdHis') . rand(1000, 9999),//单号
                        'Integral' => $jf,//积分
                        'Remark' => '注册送积分',
                    );
                    $add_rs = getApiData_java_p("/api/erp/vip/integral/update", $sto_erpid, $data, 1, 10, null, "PUT");
//                    $data = array(
//                        'Id' => $news_info["erpvipid"],//会员id
//                        'Integral' => $jf,//金额
//                        'Remark' => '注册送积分',
//                    );
//                    $add_rs = getApiData("wxd.vip.addreduce", $user_info['api_token'], array($data));
                    mlog("6211送积分:" . json_encode($data) . "返回" . $add_rs, 'smslog/' . $stoid);
                    $add_rs = json_decode($add_rs, true);--*/

                    $result=com_update_integral($sto_erpid,$news_info,$jf,$remark="注册送积分",$module="logic/userlogic");
                    if (!$result) {
                        return array('status' => -1, 'msg' => '服务器繁忙, 请联系管理员2!');
                    }

                } else {
                    accountLog($news_info["user_id"], 0, $jf, '注册送积分', 0, $stoid, $news_info["pay_points"]);//线上表
                }
            }
            if ($czz > 0){
               if($sto_erpid)  $this->send_czz($news_info['erpvipid'],$czz,$sto_erpid,"注册赠送成长值");
            }

                //优惠券
            if ($reg_info['reginfo_coupon'] != "") {
                $coupon = M("coupon")->where(array("store_id"=>$stoid,"id"=>$reg_info['reginfo_coupon'],'send_start_time'=>array('elt',time()),'send_end_time'=>array('egt',time())))->find();
                if ($coupon) {
                    $this->reg_send_quan($coupon, $news_info, $sto_erpid, $stoid);
                }
            }


            mlog("623:" . $jf, 'smslog/' . $stoid);
        }

        $is_distri_rate = tpCache('distribut.is_distri_rate', $stoid);   //分销商奖励
        $is_invitation_rate = tpCache('distribut.is_invitation_rate', $stoid);  //是否参与邀请送积分或代金券

        mlog("7", 'smslog/' . $stoid);
        //邀请赠送积分
        if (!empty($first_info) &&
            !empty($first_info['mobile']) &&
            !empty($first_info['erpvipid'])
        ) {   //如果上级会员是绑定,说明是通过链接进来,给发链接的用户赠送积分、优惠券
            /*---当上级不是分销商 或者 开启分销商奖励,参与邀请送积分或代金券---*/
            if ($first_info['is_distribut'] == 0 || $is_distri_rate == 0 || ($is_invitation_rate == 1 && $is_distri_rate == 1)) {
                mlog("701", 'smslog/' . $stoid);
                $inv_type = tpCache('basic.inv_type', $stoid);
                $inv_info = tpCache('basic.invitation_rate', $stoid);
                mlog("703" . $inv_info.":".$inv_type, 'smslog/' . $stoid);
                $invitation_rate = json_decode($inv_info, true);

                /*--当上级的会员是绑定了的--*/
                if ($inv_type == 0) { //邀请送积分
                     if ($invitation_rate['inv_jf']) {
                        mlog("71邀请送积分:" . $invitation_rate['inv_jf'], 'smslog/' . $stoid);
                        if ($sto_erpid) {
                            /*----
                            $data = array(
                                'VIPId' => $first_info["erpvipid"],//会员id
                                'OrderNo' => date('YmdHis') . rand(1000, 9999),//单号
                                'Integral' => $invitation_rate['inv_jf'],//积分
                                'Remark' => '邀请送积分',
                            );
                            $add_rs = getApiData_java_p("/api/erp/vip/integral/update", $sto_erpid, $data, 1, 10, null, "PUT");
                            mlog("711邀请送积分:" . json_encode($data) . "返回:" . $add_rs, 'smslog/' . $stoid);
                            $add_rs = json_decode($add_rs, true);
                            if ($add_rs['code'] != 0) {
                                insert_errlog($stoid, "会员绑定", "邀请送积分/api/erp/vip/integral/update", "提交数据" . json_encode($data) . "|返回:" . json_encode($add_rs));
                                //  return json(array('status' => -1, 'msg' => '服务器繁忙, 请联系管理员!'));
                            }--*/

                            $res=com_update_integral($sto_erpid,$first_info,$invitation_rate['inv_jf'],"邀请送积分",$module="logic/userslogic");
                            if(!$res){
                                return json(array('status' => -1, 'msg' => '服务器繁忙, 请联系管理员!'));
                            }

                        } else {
                            accountLog($first_info["user_id"], 0, $invitation_rate['inv_jf'], '邀请送积分', 0, $stoid, $first_info["pay_points"]);//线上表
                        }
                    }
                }
                //---邀请送成长值---
                else if($inv_type == 2){
                    if($sto_erpid) $this->send_czz($first_info['erpvipid'],  $invitation_rate['inv_cz'],$sto_erpid,"邀请赠送成长值");
                }else {
                     if ($invitation_rate['inv_coupon'] != "") {
                        mlog("72", 'smslog/' . $stoid);
                        $coupon = M("coupon")->where(array("store_id"=>$stoid,"id"=>$invitation_rate['inv_coupon'],'send_start_time'=>array('elt',time()),'send_end_time'=>array('egt',time())))->find();
                        if ($coupon) {
                            $this->reg_send_quan($coupon, $first_info, $sto_erpid, $stoid, 1);
                        }
                    }
                }
            }
        }

        $wx_user = M('wx_user')->where('store_id', $stoid)->find();
        mlog("商家appid:" . $wx_user['appid'], "rebate_log");
        $jssdk = new \app\mobile\logic\Jssdk($wx_user['appid'], $wx_user['appsecret']);
        //会员绑定通知start  (season 2018-08-03)
        $postdata[0] = "亲爱的" . $news_info['nickname'] . ",恭喜您成功绑定成为我们会员!";
        $postdata[1] = $username;
        $postdata[2] = date('Y-m-d h:i:s', time());
        $postdata[3] = "更多精彩进店参与,急速前进";
        $r = $jssdk->WeiXin_MassageModelSend($news_info['store_id'], $news_info['openid'], "1007", "", $postdata);
        //会员绑定通知 end
        mlog("7.1", 'smslog/' . $stoid);
        /*---当是分销商 且 开启分销商奖励---*/
        if ($is_distri_rate == 1) {
             $ydd_str = tpCache('distribut.invitation_ratelist', $stoid);
             $ydd = json_decode($ydd_str, true);
             // 一级 分销商赚 的钱
             if ($ydd['first_money'] > 0 && $first_info['is_distribut'] == 1) {
                // 微信推送消息
                $tmp_user = $first_info;
                $rrs1 = $this->add_user_money($ydd['first_money'], $first_info['user_id']);
                if ($rrs1) {
                    $odata['user_id'] = $first_info['user_id'];
                    $odata['create_time'] = time();
                    $odata['money'] = $ydd['first_money'];
                    $odata['remark'] = "线下一级注册";
                    $odata['store_id'] = $stoid;
                    $odata['order_sn'] = "zc" . date("YmdHis") . rand(1000, 9999);
                    $odata['status'] = 1;
                    $odata['type'] = 4;
                    M('withdrawals')->save($odata);

                    if ($tmp_user['oauth'] == 'weixin') {
                        $wx_content = "你的一级下线刚刚绑定,你获得 ¥" . $ydd['first_money'] . "奖励 !";
                        $first_res = $jssdk->push_msg($tmp_user['openid'], $wx_content);
                        mlog($news_info['mobile'] . "的一级[" . $first_res['mobile'] . "]推送返回:" . json_encode($first_res), 'smslog/' . $stoid);
                    }
                }
             }
             // 二级 分销商赚 的钱
             if ($news_info['second_leader'] > 0 && $ydd['second_money'] > 0) {
                $fuid2 = M('users')->where('store_id=' . $stoid . ' and user_id=' . $news_info['second_leader'])->find();
                if ($fuid2 && $fuid2['is_distribut'] == 1) {

                    $rrs2 = $this->add_user_money($ydd['second_money'], $fuid2['user_id']);
                    if ($rrs2) {
                        $odata['user_id'] = $fuid2['user_id'];
                        $odata['create_time'] = time();
                        $odata['money'] = $ydd['second_money'];
                        $odata['remark'] = "线下二级注册";
                        $odata['store_id'] = $stoid;
                        $odata['order_sn'] = "zc" . date("YmdHis") . rand(1000, 9999);
                        $odata['status'] = 1;
                        $odata['type'] = 4;
                        M('withdrawals')->save($odata);

                        // 微信推送消息
                        $tmp_user = $fuid2;
                        if ($tmp_user['oauth'] == 'weixin') {
                            $wx_content = "你的二级下线刚刚绑定,你获得 ¥" . $ydd['second_money'] . "奖励 !";
                            $second_res = $jssdk->push_msg($tmp_user['openid'], $wx_content);
                            mlog($news_info['mobile'] . "的二级[" . $tmp_user['mobile'] . "]推送返回:" . json_encode($second_res), 'smslog/' . $stoid);
                        }
                    }
                }
            }
             // 三级 分销商赚 的钱
             if ($news_info['third_leader'] > 0 && $ydd['third_money'] > 0) {
                $fuid3 = M('users')->where('store_id=' . $stoid . ' and user_id=' . $news_info['third_leader'])->find();
                if ($fuid3 && $fuid3['is_distribut'] == 1) {
                    $rrs3 = $this->add_user_money($ydd['third_money'], $fuid3['user_id']);
                    if ($rrs3) {
                        $odata['user_id'] = $fuid3['user_id'];
                        $odata['create_time'] = time();
                        $odata['money'] = $ydd['third_money'];
                        $odata['remark'] = "线下三级注册";
                        $odata['store_id'] = $stoid;
                        $odata['order_sn'] = "zc" . date("YmdHis") . rand(1000, 9999);
                        $odata['status'] = 1;
                        $odata['type'] = 4;
                        M('withdrawals')->save($odata);

                        // 微信推送消息
                        $tmp_user = $fuid3;
                        if ($tmp_user['oauth'] == 'weixin') {
                            $wx_content = "你的三级下线刚刚绑定,你获得 ¥" . $ydd['third_money'] . "奖励 !";
                            $third_res = $jssdk->push_msg($tmp_user['openid'], $wx_content);
                            mlog($news_info['mobile'] . "的三级[" . $tmp_user['mobile'] . "]推送返回:" . json_encode($third_res), "rebate_log");
                        }
                    }
                }
            }
        }
        mlog("8", 'smslog/' . $stoid);
        //返回
        return array('status' => 1, 'msg' => '绑定成功', 'result' => $news_info);
    }

    /*----增加会员的余额----*/
    public function add_user_money($addmoney, $user_id)
    {
        $rs = M('users')->where('user_id', $user_id)->setInc('user_money', $addmoney);
        return $rs;
    }


    /*---送券---*/
    public function reg_send_quan($coupon, $user_info, $sto_erpid, $stoid, $t = 0)
    {
        try {
            $first_info = $user_info;
            $geterp_send = 0;
            if ($coupon["send_start_time"] <=time() && $coupon["send_end_time"] > time()) {
                $CashRepNo = "1005" . date("ymdHis") . get_total_millisecond();
                if ($sto_erpid) {
                    $data = array(
                        'CashRepNo' => $CashRepNo,//券号
                        'VIPId' => $first_info["erpvipid"],//会员id
                        'Sum' => $coupon["money"],//金额
                        'SendMan' => '注册发放',//发放类型
                        'Operator' => '微信商城',//来源
                        'BuySum' => $coupon["condition"],//满多少才能使用
                        'Remark' => '注册送微券【消费满' . $coupon["condition"] . '元可用】',
                    );
                    if ($t == 1) {
                        $data['Remark'] = '邀请送微券【消费满' . $coupon["condition"] . '元可用】';
                        $data['SendMan'] = '邀请发放';
                    }
                    if ($coupon['useobjecttype']) {
                        $data['UseObjectType'] = $coupon['useobjecttype'];
                        $data['UseObjectID'] = $coupon['useobjectid'];
                        $data['UseObjectNo'] = $coupon['useobjectno'];
                        $data['UseObjectName'] = $coupon['useobjectname'];
                    }

                    //如果有设置有效期
                    if ($coupon['endtype'] == 1) {
                        $data['BeginDate'] = date('Y-m-d');//使用开始日期
                        if ($coupon['days'] > 0) {
                            $ed = strtotime("+" . $coupon['days'] . " day");
                            $data['ValidDate'] = date('Y-m-d', $ed);//截止期限
                        }
                    } else {
                        if ($coupon["use_start_time"] != "") {
                            $data['BeginDate'] = date('Y-m-d', $coupon["use_start_time"]);//使用开始日期
                        }
                        if ($coupon["use_end_time"] != "") {
                            $data['ValidDate'] = date('Y-m-d', $coupon["use_end_time"]);//截止期限
                        }
                    }

                    $erp = tpCache("shop_info.ERPId", $stoid);
                    $add_rs = getApiData_java_p("/api/erp/vip/cash/insert", $erp, $data, null, null, null, "POST");
                    if ($add_rs) {
                        $add_rs = json_decode($add_rs, true);
                        if ($add_rs['code'] != 0) {
                            $geterp_send = 1;
                        }
                    }
                }

                if (empty($sto_erpid) || ($sto_erpid && $geterp_send)) {
                    //插入线上优惠券领取表
                    $coupon_list['cid'] = $coupon['id'];
                    $coupon_list['type'] = 2;
                    $coupon_list['uid'] = $first_info['user_id'];
                    $coupon_list['send_time'] = time();
                    $coupon_list['code'] = $CashRepNo;
                    $coupon_list['store_id'] = getMobileStoId();
                    $coupon_list['code'] = time();

                    if ($coupon['endtype'] == 1) {
                        $coupon_list['begintime'] = time();
                        if ($coupon['days'] > 0)
                            $coupon_list['validtime'] = strtotime("+" . $coupon['days'] . " day");
                        else
                            $coupon_list['validtime'] = 0;
                    } else {
                        $coupon_list['begintime'] = $coupon["use_start_time"];
                        $coupon_list['validtime'] = $coupon["use_end_time"];
                    }

                    $coupon_list['sum'] = $coupon["money"];
                    $coupon_list['buysum'] = $coupon["condition"];
                    $coupon_list['remark'] = "注册发放";
                    if ($t == 1) $coupon_list['remark'] = "邀请发放";
                    $add_couponinfo = add_coupon($coupon_list, $first_info, $stoid);
                }
            }

        } catch (Exception $exception) {

            mlog("返回1:" . json_encode($user_info), "reg_send_quan/" . $stoid);
            mlog("返回2:" . json_encode($exception), "reg_send_quan/" . $stoid);
        }
    }


    /*
     * 获取当前登录用户信息
     */
    public function get_info($user_id)
    {
        if (!$user_id > 0)
            return array('status' => -1, 'msg' => '缺少参数', 'result' => '');
        $user_info = M('users')->where("user_id", $user_id)->find();
        if (!$user_info)
            return false;

        $user_info['coupon_count'] = M('coupon_list')->where(['uid' => $user_id, 'use_time' => 0])->count(); //获取优惠券列表
        $user_info['collect_count'] = M('goods_collect')->where(array('user_id' => $user_id))->count(); //获取收藏数量

        $user_info['waitPay'] = M('order')->where("user_id = :user_id " . C('WAITPAY'))->bind(['user_id' => $user_id])->count(); //待付款数量
        $user_info['waitSend'] = M('order')->where("user_id = :user_id " . C('WAITSEND'))->bind(['user_id' => $user_id])->count(); //待发货数量
        $user_info['waitReceive'] = M('order')->where("user_id = :user_id " . C('WAITRECEIVE'))->bind(['user_id' => $user_id])->count(); //待收货数量
        $user_info['order_count'] = $user_info['waitPay'] + $user_info['waitSend'] + $user_info['waitReceive'];
        return array('status' => 1, 'msg' => '获取成功', 'result' => $user_info);
    }

    /*
     * 获取最近一笔订单
     */
    public function get_last_order($user_id)
    {
        $last_order = M('order')->where("user_id", $user_id)->order('order_id DESC')->find();
        return $last_order;
    }

    /*
     * 获取订单商品
     */
    public function get_order_goods($order_id)
    {
        $sql = "SELECT og.*,g.goods_spec,g.goods_color,g.original_img FROM __PREFIX__order_goods og LEFT JOIN __PREFIX__goods g ON g.goods_id = og.goods_id WHERE og.order_id = :order_id and og.is_send<2";
        $bind['order_id'] = $order_id;
        $goods_list = DB::query($sql, $bind);

        foreach ($goods_list as $k => $v) {
            $sp = $v["goods_spec"];
            $cn = $v["goods_color"];
            if ($sp == "" && $cn == "") {
                $tgg = "";
            } else if ($sp != "" && $cn == "") {
                $tgg = $sp;
            } else if ($sp == "" && $cn != "") {
                $tgg = $cn;
            } else {
                $tgg = $sp . "/" . $cn;
            }
            $goods_list[$k]['guige'] = $tgg;
        }

        $return['status'] = 1;
        $return['msg'] = '';
        $return['result'] = $goods_list;
        return $return;
    }

    /*
    * 获取订单商品
    */
    public function get_order_goods1($order_id, $o = null)
    {

        $ord_g = M("order_goods")->where("order_id", $order_id)->field('rec_id')->select();
        if (count($ord_g) > 1 && $o['order_status'] != 6) {
            $sql = "SELECT og.*,g.goods_spec,g.goods_color,g.original_img FROM __PREFIX__order_goods og LEFT JOIN __PREFIX__goods g ON g.goods_id = og.goods_id WHERE og.order_id = :order_id and og.is_send<2 ";
        } else {
            $sql = "SELECT og.*,g.goods_spec,g.goods_color,g.original_img FROM __PREFIX__order_goods og LEFT JOIN __PREFIX__goods g ON g.goods_id = og.goods_id WHERE og.order_id = :order_id ";
        }
        $bind['order_id'] = $order_id;
        $goods_list = DB::query($sql, $bind);
        foreach ($goods_list as $k => $v) {
            $sp = $v["goods_spec"];
            $cn = $v["goods_color"];
            if ($sp == "" && $cn == "") {
                $tgg = "";
            } else if ($sp != "" && $cn == "") {
                $tgg = $sp;
            } else if ($sp == "" && $cn != "") {
                $tgg = $cn;
            } else {
                $tgg = $sp . "/" . $cn;
            }
            $goods_list[$k]['guige'] = $tgg;
        }

        $return['status'] = 1;
        $return['msg'] = '';
        $return['result'] = $goods_list;
        return $return;
    }


    /*
     * 获取账户资金记录
     */
    public function get_account_log($user_id, $type = 0)
    {
        //查询条件
//        $type = I('get.type',0);
        if ($type == 1) {
            //收入
            $where = 'user_money > 0 OR pay_points > 0 AND user_id=:user_id';
        }
        if ($type == 2) {
            //支出
            $where = 'user_money < 0 OR pay_points < 0 AND user_id=:user_id';
        }
        $count = M('account_log')->where($where ? $where : 'user_id = :user_id')->bind(['user_id' => $user_id])->count();
        $Page = new Page($count, 10);
        $logs = M('account_log')->where($where ? $where : 'user_id = :user_id')->bind(['user_id' => $user_id])->order('change_time desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $return['status'] = 1;
        $return['msg'] = '';
        $return['result'] = $logs;
        $return['show'] = $Page->show();

        return $return;
    }

    /*
     * 获取优惠券
     */
    public function get_coupon($user_id, $type = 0)
    {

        //查询条件
        //    $type = I('get.type',0);           


        $where = ' AND l.order_id = 0 AND c.use_end_time > ' . time(); // 未使用
        if ($type == 1) {
            //已使用
            $where = ' AND l.order_id > 0 AND l.use_time > 0 ';
        }
        if ($type == 2) {
            //已过期
            $where = ' AND ' . time() . ' > c.use_end_time ';
        }
        //获取数量
        $sql = "SELECT count(l.id) as total_num FROM __PREFIX__coupon_list" .
            " l LEFT JOIN __PREFIX__coupon" .
            " c ON l.cid =  c.id WHERE l.uid = {$user_id} {$where}";
        $count = DB::query($sql);
        $count = $count[0]['total_num'];

        $Page = new Page($count, 10);

        $sql = "SELECT l.*,c.name,c.money,c.use_end_time,c.condition FROM __PREFIX__coupon_list" .
            " l LEFT JOIN __PREFIX__coupon" .
            " c ON l.cid =  c.id WHERE l.uid = {$user_id} {$where}  ORDER BY l.send_time DESC,l.use_time LIMIT {$Page->firstRow},{$Page->listRows}";

        $logs = Db::query($sql);

        $return['status'] = 1;
        $return['msg'] = '获取成功';
        $return['result'] = $logs;
        $return['show'] = $Page->show();
        return $return;
    }

    /**
     * 获取商品收藏列表
     * @param $user_id  用户id
     */
    public function get_goods_collect($user_id)
    {
        $count = M('goods_collect')->where(array('user_id' => $user_id))->count();
        $page = new Page($count, 10);
        $show = $page->show();
        //获取我的收藏列表
        $sql = "SELECT c.collect_id,c.add_time,g.goods_id,g.goods_name,g.shop_price,g.market_price,g.original_img FROM __PREFIX__goods_collect c " .
            "inner JOIN __PREFIX__goods g ON g.goods_id = c.goods_id " .
            "WHERE c.user_id = " . $user_id .
            " ORDER BY c.add_time DESC LIMIT {$page->firstRow},{$page->listRows}";
        $result = Db::query($sql);
        $return['total'] = $count;
        $return['status'] = 3;
        $return['msg'] = '获取成功';
        $return['result'] = $result;
        $return['show'] = $show;
        return $return;
    }

    /**
     * 获取评论列表
     * @param $user_id 用户id
     * @param $status  状态 0 未评论 1 已评论
     * @return mixed
     */
    public function get_comment($user_id, $status = 2,$ord_sn="")
    {
        if ($status == 1) {
            //已评论
            $count2 = DB::query("select count(1) as count from `__PREFIX__comment`  as c inner join __PREFIX__order_goods as g on c.goods_id = g.goods_id and c.order_id = g.order_id where c.user_id = $user_id");
            $count2 = $count2[0]['count'];

            $page = new Page($count2, 10);
            $sql = "select  c.comment_id,c.goods_id,c.username,c.is_show,c.user_id,c.order_id,c.content,c.goods_rank,c.service_rank,c.store_id,g.rec_id,g.goods_name,g.goods_price,c.img,g.*,b.order_sn,b.add_time  from  __PREFIX__comment as c left join __PREFIX__order  as b on b.order_id=c.order_id inner join __PREFIX__order_goods as g on c.goods_id = g.goods_id and c.order_id = g.order_id where c.user_id = $user_id order by c.add_time desc LIMIT {$page->firstRow},{$page->listRows}";
        } else {
            $countsql = " select count(1) as comment_count from __PREFIX__order_goods as og
        	left join __PREFIX__order as o on o.order_id = og.order_id where o.user_id = $user_id  and o.order_status in(2,4) ";
            $where = '';
            if ($status == 0) {
                $countsql .= $where = " and og.is_comment = 0 ";
            }
            if($ord_sn){
                $where.=" and og.order_sn='".$ord_sn."'";
                $countsql .= $where;
            }

            $comment = DB::query($countsql);
            $count1 = $comment[0][comment_count]; // 待评价
            $page = new Page($count1, 10);
            $sql = " select og.*,c.comment_id,c.img,c.goods_rank,c.content,o.add_time,o.total_amount  from __PREFIX__order_goods as og left join __PREFIX__order as o on o.order_id = og.order_id left JOIN  __PREFIX__comment c on  c.goods_id = og.goods_id  and c.order_id=o.order_id where o.user_id=$user_id and o.order_status in(2,4) $where order by o.order_id desc  LIMIT {$page->firstRow},{$page->listRows}";
        }


        //$show = $page->show();
        $p = I('p/d', 1);
        $ishow = 0;
        if ($count2 > $p * 10) {
            $ishow = 1;
        }
        $comment_list = DB::query($sql);
        if ($comment_list) {
            foreach ($comment_list as $k => $v) {
                $comment_list[$k]['img'] = unserialize($v['img']); // 晒单图片

                if($v['prom_type']==4){
                    $ord=M("order")->where('order_id',$v['order_id'])->find();
                    $comment_list[$k]['integral']=$ord['integral'];
                }
            }

            $return['result'] = $comment_list;
            //var_dump($comment_list);
            $return['isshow'] = $ishow; //是否显示加载更多
            return $return;
        } else {
            return array();
        }
    }

    /**
     * 添加评论
     * @param $add
     * @return array
     */
    public function add_comment($add)
    {
        if (!$add['order_id'] || !$add['goods_id'])
            return array('status' => -1, 'msg' => '非法操作', 'result' => '');

        //检查订单是否已完成
        $order = M('order')->where("order_id", $add['order_id'])->where('user_id', $add['user_id'])->find();
        if ($order['order_status'] != 2)
            return array('status' => -1, 'msg' => '该笔订单还未确认收货', 'result' => '');

        //检查是否已评论过
        $goods = M('comment')->where("order_id", $add['order_id'])->where('goods_id', $add['goods_id'])->find();
        if ($goods)
            return array('status' => -1, 'msg' => '您已经评论过该商品', 'result' => '');

        $row = D('comment')->add($add);
        if ($row) {
            //更新订单商品表状态
            M('order_goods')->where(array('goods_id' => $add['goods_id'], 'order_id' => $add['order_id']))->save(array('is_comment' => 1));
            M('goods')->where(array('goods_id' => $add['goods_id']))->setInc('comment_count', 1); // 评论数加一
            // 查看这个订单是否全部已经评论,如果全部评论了 修改整个订单评论状态            
            $comment_count = M('order_goods')->where("order_id", $add['order_id'])->where('is_comment', 0)->count();
            if ($comment_count == 0) // 如果所有的商品都已经评价了 订单状态改成已评价
            {
                M('order')->where("order_id", $add['order_id'])->save(array('order_status' => 4));
            }
            return array('status' => 1, 'msg' => '评论成功', 'comment_id' => $row);
        }
        return array('status' => -1, 'msg' => '评论失败', 'result' => '');
    }

    /**
     * 邮箱或手机绑定
     * @param $email_mobile  邮箱或者手机
     * @param int $type 1 为更新邮箱模式  2 手机
     * @param int $user_id 用户id
     * @return bool
     */
    public function update_email_mobile($email_mobile, $user_id, $type = 1)
    {
        //检查是否存在邮件
        if ($type == 1)
            $field = 'email';
        if ($type == 2)
            $field = 'mobile';
        $condition['user_id'] = array('neq', $user_id);
        $condition[$field] = $email_mobile;

        $is_exist = M('users')->where($condition)->find();
        if ($is_exist)
            return false;
        unset($condition[$field]);
        $condition['user_id'] = $user_id;
        $validate = $field . '_validated';
        M('users')->where($condition)->save(array($field => $email_mobile, $validate => 1));
        return true;
    }

    /**
     * 更新用户信息
     * @param $user_id
     * @param $post  要更新的信息
     * @return bool
     */
    public function update_info($user_id, $post = array())
    {
        $model = M('users')->where("user_id", $user_id);
        $row = $model->setField($post);
        if ($row === false)
            return false;
        return true;
    }

    /**
     * 地址添加/编辑
     * @param $user_id 用户id
     * @param $user_id 地址id(编辑时需传入)
     * @return array
     */
    public function add_address($user_id, $address_id = 0, $data)
    {
        $post = $data;
        if ($address_id == 0) {
            $c = M('UserAddress')->where("user_id", $user_id)->count();
            if ($c >= 20)
                return array('status' => -1, 'msg' => '最多只能添加20个收货地址', 'result' => '');
        }

        //检查手机格式
        if ($post['consignee'] == '')
            return array('status' => -1, 'msg' => '收货人不能为空', 'result' => '');
        if (!$post['province'] || !$post['city'])
            return array('status' => -1, 'msg' => '所在地区不能为空', 'result' => '');
        if (!$post['address'])
            return array('status' => -1, 'msg' => '地址不能为空', 'result' => '');
        if (!check_mobile($post['mobile']))
            return array('status' => -1, 'msg' => '手机号码格式有误', 'result' => '');

        //编辑模式
        if ($address_id > 0) {
            $address = M('user_address')->where(array('address_id' => $address_id, 'user_id' => $user_id))->find();
            if ($post['is_default'] == 1 && $address['is_default'] != 1)
                M('user_address')->where(array('user_id' => $user_id))->save(array('is_default' => 0));
            $row = M('user_address')->where(array('address_id' => $address_id, 'user_id' => $user_id))->save($post);
            if (!$row)
                return array('status' => -1, 'msg' => '操作完成', 'result' => '');
            return array('status' => 1, 'msg' => '编辑成功', 'result' => '');
        }
        //添加模式
        $post['user_id'] = $user_id;

        // 如果目前只有一个收货地址则改为默认收货地址
        $c = M('user_address')->where("user_id", $post['user_id'])->count();
        if ($c == 0) $post['is_default'] = 1;

        $address_id = M('user_address')->add($post);
        //如果设为默认地址
        $insert_id = DB::name('user_address')->getLastInsID();
        $map['user_id'] = $user_id;
        $map['address_id'] = array('neq', $insert_id);
        if ($post['is_default'] == 1)
            M('user_address')->where($map)->save(array('is_default' => 0));
        if (!$address_id)
            return array('status' => -1, 'msg' => '添加失败', 'result' => '', 'fir' => $c);
        return array('status' => 1, 'msg' => '添加成功', 'result' => $address_id, 'fir' => $c);
    }

    /**
     * 添加自提点
     * @author dyr
     * @param $user_id
     * @param $post
     * @return array
     */
    public function add_pick_up($user_id, $post)
    {
        //检查用户是否已经有自提点
        $user_pickup_address_id = M('user_address')->where(['user_id' => $user_id, 'is_pickup' => 1])->getField('address_id');
        $pick_up = M('pick_up')->where(array('pickup_id' => $post['pickup_id']))->find();
        $post['address'] = $pick_up['pickup_address'];
        $post['is_pickup'] = 1;
        $post['user_id'] = $user_id;
        $user_address = new UserAddress();
        if (!empty($user_pickup_address_id)) {
            //更新自提点
            $user_address_save_result = $user_address->allowField(true)->validate(true)->save($post, ['address_id' => $user_pickup_address_id]);
        } else {
            //添加自提点
            $user_address_save_result = $user_address->allowField(true)->validate(true)->save($post);
        }
        if (false === $user_address_save_result) {
            return array('status' => -1, 'msg' => '保存失败', 'result' => $user_address->getError());
        } else {
            return array('status' => 1, 'msg' => '保存成功', 'result' => '');
        }
    }

    /**
     * 设置默认收货地址
     * @param $user_id
     * @param $address_id
     */
    public function set_default($user_id, $address_id)
    {
        M('user_address')->where(array('user_id' => $user_id))->save(array('is_default' => 0)); //改变以前的默认地址地址状态
        $row = M('user_address')->where(array('user_id' => $user_id, 'address_id' => $address_id))->save(array('is_default' => 1));
        if (!$row)
            return false;
        return true;
    }

    /**
     * 修改密码
     * @param $user_id  用户id
     * @param $old_password  旧密码
     * @param $new_password  新密码
     * @param $confirm_password 确认新 密码
     */
    public function password($user_id, $old_password, $new_password, $confirm_password, $is_update = true)
    {
        $data = $this->get_info($user_id);
        $user = $data['result'];
        if (strlen($new_password) < 6)
            return array('status' => -1, 'msg' => '密码不能低于6位字符', 'result' => '');
        if ($new_password != $confirm_password)
            return array('status' => -1, 'msg' => '两次密码输入不一致', 'result' => '');
        //验证原密码
        if ($is_update && ($user['password'] != '' && encrypt($old_password) != $user['password']))
            return array('status' => -1, 'msg' => '密码验证失败', 'result' => '');
        $row = M('users')->where("user_id", $user_id)->save(array('password' => encrypt($new_password)));
        if (!$row)
            return array('status' => -1, 'msg' => '修改失败', 'result' => '');
        return array('status' => 1, 'msg' => '修改成功', 'result' => '');
    }

    /**
     * 取消订单
     */
    public function cancel_order($user_id, $order_id)
    {
        $order = M('order')->where(array('order_id' => $order_id, 'user_id' => $user_id))->find();
        //检查是否未支付订单 已支付联系客服处理退款
        if (empty($order))
            return array('status' => -1, 'msg' => '订单不存在', 'result' => '');
        //检查是否未支付的订单
        if ($order['pay_status'] > 0 || $order['order_status'] > 1)
            return array('status' => -1, 'msg' => '支付状态或订单状态不允许', 'result' => '');

        $row = M('order')->where(array('order_id' => $order_id, 'user_id' => $user_id))
            ->where('order_status<>3')
            ->save(array('order_status' => 3));

        if ($row) {
            $user_id = $order['user_id'];
            //获取记录表信息
            //$log = M('account_log')->where(array('order_id'=>$order_id))->find();
            //有余额支付的情况
            if ($order['user_money'] > 0) {
                //解冻冻余额
                $rs = M('Users')->where("user_id", $user_id)
                    ->where('frozen_money>=' . $order['user_money'])->find();
                if ($rs) {
                    M('Users')->where("user_id", $user_id)->setDec('frozen_money', $order['user_money']);
                }
            }

            /*---优惠券冻结---*/
            $quanno = $order['coupon_no'];
            if (!empty($quanno)) {
                $dada = ['CashRepNo' => $quanno, 'user_id' => $user_id];
                //冻结优惠券
                M('frozen_quan')->where($dada)->delete();
            }

            /*---优惠券冻结---*/
            $quanno = $order['coupon_no'];
            if (!empty($quanno)) {
                $dada = ['CashRepNo' => $quanno, 'user_id' => $user_id];
                //冻结优惠券
                M('frozen_quan')->where($dada)->delete();
            }

            if ($order['is_zsorder'] < 2) {

                //$redis = new \Redis();
                //$redis->connect(redisip, 6379);
                $redis = get_redis_handle();

                //清理秒杀缓存
                $hh = M('order_goods')->where('order_id', $order_id)
                    ->where('prom_type', 1)->where('store_id', $order['store_id'])->field('order_id,goods_num,prom_id,order_sn,rec_id')->select();

                if ($hh) {
                    foreach ($hh as $kl => $vl) {
                        //减少秒杀缓存
                        //$name0 = 'ms' . $vl['prom_id'] . '-' . $order['store_id'];
                        $name0 = get_redis_name($vl['prom_id'], 1, $order['store_id']);
                        //不重复退回redis
                        if (!doublefind($redis, $name0, $vl['rec_id'])) {
                            for ($i = 0; $i < $vl['goods_num']; $i++) {
                                $redis->lPush($name0, $vl['rec_id'] . '_' . $i);
                            }
                            $jsda['num'] = $vl['goods_num'];
                            $jsda['order_sn'] = $vl['order_sn'];
                            $jsda['type'] = 2;  //1是5分钟自动补回
                            mlog(json_encode($jsda), 'flash_log/' . $order['store_id'] . '/' . $vl['prom_id']);
                        }
                    }
                }

                $hh2 = M('order_goods')->where('order_id', $order_id)
                    ->where('prom_type', 2)->where('store_id', $order['store_id'])
                    ->field('order_id,goods_num,prom_id,order_sn,rec_id')->select();
                if ($hh2) {
                    $odarr0 = get_arr_column($hh, 'order_id');
                    //增加队列
                    foreach ($hh2 as $k => $v) {
                        //$name_g ='grb'.$v['prom_id'] . '-' . $order['store_id'];
                        $name_g = get_redis_name($v['prom_id'], 2, $order['store_id']);
                        //不重复退回redis
                        if (!doublefind($redis, $name_g, "2" . $v['rec_id'])) {
                            for ($i = 0; $i < $v['goods_num']; $i++) {
                                $redis->lPush($name_g, "2" . $v['rec_id'] . '_' . $i);
                            }

                            $jsda['num'] = $v['goods_num'];
                            $jsda['order_sn'] = $v['order_sn'];
                            $jsda['type'] = 1;  //1是5分钟自动补回
                            mlog(json_encode($jsda), 'group_buy_log/' . $order['store_id'] . '/' . $v['prom_id']);
                        }
                    }
                }
            }

            //查一下拼团
            $stoid = $order['store_id'];
            if ($order['is_zsorder'] >= 2) {
                //$redis = new \Redis();
                //$redis->connect(redisip, 6379);
                $redis = get_redis_handle();
                //查找会员团,要补回人数
                $v = $order;
                if ($v['is_zsorder'] == 3) {
                    //$name2 = 'pind' . $v['pt_prom_id'] . '-' . $v['pt_listno'] . $stoid;
                    $name2 = get_redis_name($v['pt_prom_id'], 6, $stoid) . ":" . $v['pt_listno'];

                    if (!doublefind($redis, $name2, $v['order_id'])) {
                        $redis->lPush($name2, $v['order_id'] . '_0');
                    }
                    $len = $redis->lLen($name2);
                    //如果这个团,全部补回,那这个单就没有意思了,要delete掉
                    $teamnum = M('teamlist')->field('ct_num')
                        ->where('id', $v['pt_prom_id'])->find();
                    if ($len == $teamnum['ct_num']) {
                        //$redis->delete($name2);
                        del_redis($redis, $name2);
                        //更新团
                        $da['state'] = 1;
                        $map['team_id'] = $v['pt_prom_id'];
                        $map['listno'] = $v['pt_listno'];
                        $map['store_id'] = $stoid;

                        mlog("取消订单:" . $v['pt_listno'] . '-' . $v['order_id'], "cancel_order/" . $stoid);
                        M('teamgroup')->where($map)->save($da);
                    }
                }

                //补回购买的数量
                $hh = M('order_goods')->where('order_id', $order_id)
                    ->where('prom_type', 6)->where('store_id', $stoid)
                    ->field('order_id,goods_num,prom_id,rec_id')->select();

                if ($hh) {
                    //增加队列
                    foreach ($hh as $k => $v) {
                        //$name0 = 'pind' . $v['prom_id'] . '-' . $stoid;
                        $name0 = get_redis_name($v['prom_id'], 6, $stoid);
                        if (!doublefind($redis, $name0, $v['rec_id'])) {
                            for ($i = 0; $i < $v['goods_num']; $i++) {
                                $redis->lPush($name0, $v['rec_id'] . "_" . $i);
                            }
                        }
                    }
                }
                //修改订单是状态
                M('order')->where('order_id', $order_id)->save(['pt_status' => 3]);
            }

            $data['order_id'] = $order_id;
            $data['action_user'] = $user_id;
            $data['action_note'] = '您取消了订单';
            $data['order_status'] = 3;
            $data['pay_status'] = $order['pay_status'];
            $data['shipping_status'] = $order['shipping_status'];
            $data['log_time'] = time();
            $data['status_desc'] = '用户取消订单';
            $data['store_id'] = $order['store_id'];
            M('order_action')->add($data);//订单操作记录

            /*---
            if (!empty($order['gift_receive_id'])) {
                M('gift_receive')->where(['id' => ['in', $order['gift_receive_id']]])->delete();//去掉赠品领用记录
            }--*/
            if (!empty($order['gift_receive_id'])) {
                //M('gift_receive')->where(['id' => ['in', $order['gift_receive_id']]])->delete();//去掉赠品领用记录
                $org = M("order_goods")->where('order_id', $order['order_id'])
                    ->where('is_gift', 1)->where('store_id', $stoid)
                    ->field('rec_id,gift_id,goods_num,prom_id')->select();

                if ($org) {
                    foreach ($org as $ko => $vo) {
                        //从表上删除记录,主表做标记,赠品被取消,同时补回活动的库存
                        //M('order_goods')->where('rec_id',$vo['rec_id'])->delete();
                        M("order")->where('order_id', $v['order_id'])->where('store_id', $stoid)
                            ->save(['is_del_gift' => 1]);
                        M("gift")->where('store_id', $stoid)
                            ->where('id', $vo['gift_id'])
                            ->setInc('goods_num', $vo['goods_num']);
                        M('gift_receive')->where(["orderGoods_id" => $vo['rec_id'], 'user_id' => $order['user_id']])->delete();
                    }

                }
            }

        }

        if (!$row)
            return array('status' => -1, 'msg' => '操作失败', 'result' => '');
        return array('status' => 1, 'msg' => '操作成功', 'result' => '');
    }

    /**
     * 发送验证码: 该方法只用来发送邮件验证码, 短信验证码不再走该方法
     * @param $sender 接收人
     * @param $type 发送类型
     * @return json
     */
    public function send_validate_code($sender, $type, $stoid = '')
    {
        if (empty($stoid)) {
            $stoid = getMobileStoId();
        }

        $sms_time_out = tpCache('sms.sms_time_out', $stoid);
        $sms_time_out = $sms_time_out ? $sms_time_out : 180;
        //获取上一次的发送时间
        $send = session('validate_code');
        if (!empty($send) && $send['time'] > time() && $send['sender'] == $sender) {
            //在有效期范围内 相同号码不再发送
            $res = array('status' => -1, 'msg' => '规定时间内,不要重复发送验证码');
            return $res;
        }
        $code = mt_rand(1000, 9999);

        //检查是否邮箱格式
        if (!check_email($sender)) {
            $res = array('status' => -1, 'msg' => '邮箱码格式有误');
            return $res;
        }
        $send = send_email($sender, '验证码', '您好,你的验证码是:' . $code);

        if ($send) {
            $info['code'] = $code;
            $info['sender'] = $sender;
            $info['is_check'] = 0;
            $info['time'] = time() + $sms_time_out; //有效验证时间
            session('validate_code', $info);
            $res = array('status' => 1, 'msg' => '验证码已发送,请注意查收');
        } else {
            $res = array('status' => -1, 'msg' => '验证码发送失败,请联系管理员');
        }
        return $res;
    }

    /**
     * 检查短信/邮件验证码验证码
     * @param $code
     * @param $sender
     * @param $session_id
     * @param string $type
     * @param string $stoid
     * @return array
     */
    public function check_validate_code($code, $sender, $session_id, $stoid = '', $type = 'phone')
    {
        //return   array('status'=>1,'msg'=>'验证成功');;
        $timeOut = time();
        $inValid = true;  //验证码失效

        if (empty($stoid)) {
            $stoid = getMobileStoId();
        }

        $scene = session("scene"); //获取发送短信场景
        //短信发送否开启
        // $isSmsEnable = smsConfigValueScene($scene,getMobileStoId());
        $isSmsEnable = true;
        //邮件证码是否开启
        $reg_smtp_enable = tpCache('smtp.regis_smtp_enable', $stoid);
        if ($type == 'email') {
            if (!$reg_smtp_enable) {//发生邮件功能关闭
                $validate_code = session('validate_code');
                $validate_code['sender'] = $sender;
                $validate_code['is_check'] = 1;//标示验证通过
                session('validate_code', $validate_code);
                return array('status' => 1, 'msg' => '邮件验证码功能关闭, 无需校验验证码');
            }
            if (!$code) return array('status' => -1, 'msg' => '请输入邮件验证码');
            //邮件
            $data = session('validate_code');
            $timeOut = $data['time'];
            if ($data['code'] != $code || $data['sender'] != $sender) {
                $inValid = false;
            }
        } else {
            if (!$isSmsEnable) {
                $data['sender'] = $sender;
                $data['is_check'] = 1; //标示验证通过
                session('validate_code', $data);
                return array('status' => 1, 'msg' => '短信验证码功能关闭, 无需校验验证码');
            }

            if (!$code) return array('status' => -1, 'msg' => '请输入短信验证码');
            //短信
//            $sms_time_out = tpCache('sms.sms_time_out',$stoid);
//            $sms_time_out = $sms_time_out ? $sms_time_out : 3600;
            $sms_time_out = 3600;//一个小时过期
            $data = M('sms_log')->where(array('mobile' => $sender, 'session_id' => $session_id, 'status' => 1))->order('id DESC')->find();
            if (is_array($data) && $data['code'] == $code) {
                $data['sender'] = $sender;
                $timeOut = $data['add_time'] + $sms_time_out;
            } else {
                $inValid = false;
            }
        }

        if (empty($data)) {
            $res = array('status' => -1, 'msg' => '请先获取验证码');
        } elseif (!$inValid) {
            $res = array('status' => -1, 'msg' => '验证失败,验证码有误');
        } elseif ($timeOut < time()) {
            $res = array('status' => -1, 'msg' => '验证码已超时失效');
        } else {
            $data['is_check'] = 1; //标示验证通过
            session('validate_code', $data);
            $res = array('status' => 1, 'msg' => '验证成功');
            smsHandle($stoid, "短信发送");
        }
        return $res;
    }

//    public function zs_coupon($userid, $stoid)
//    {
//        $coupon = M("coupon")->where("store_id", $stoid)->where("type",2)->where("send_end_time" ,"<=",time())
//
//
//    }


    // 过滤掉emoji表情
    public function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);

        return $str;
    }

    //生成成长值的单号
    public function  new_number($accdb){
      return  $accdb.date('YmdHis') . rand(10, 99).rand(10, 99);
    }
    public function send_czz($erpvipid,$czz,$accdb,$Remark){
        $data = array(
            'VIPId' => urlencode($erpvipid),//会员id
            'FromType' =>'REWARD',
            'InGrade' => $czz,//积分
            'OrderNo' => $this->new_number($accdb),//积分
            'Remark' => $Remark,
        );
        $add_rs = getApiData_java_p("/api/erp/grade/sum/update", $accdb, $data, 1, 10, null, "PUT");
        mlog("czz".$add_rs,"send_czz/".$accdb);
    }

}