Distribut.php 76.8 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
<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司,并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 2015-11-21
 */
namespace app\mobile\controller;
use app\home\logic\UsersLogic;
use think\Page;
use think\Verify;
use think\Db;
use think\Cookie;
use think\AjaxPage;

class Distribut extends MobileBase {
    public $user;
    public $user_id;
        /*
        * 初始化操作
        */
    public function _initialize() {
        parent::_initialize();
        $sid = I('stoid');

        $distribut =  tpCache('distribut',$sid);
        $this->assign('distribut_sharetitle', $distribut['distribut_sharetitle']);  //分销标题
        $this->assign('distribut_shareremark', $distribut['distribut_shareremark']);//分销备注
        $this->assign('distribut_name', $distribut['name']);//分销备注

        if (session('?user')) {
            $user = session('user');
            $user = M('users')->where("user_id",$user['user_id'])->where("store_id", $sid)->find();
            /*---当会员不是分销商且 可以直接成为分销商不用购买---*/
            if ($distribut && $distribut['switch']==1 && $distribut['condition']==0){
                if ($user['is_distribut']!= 1 && !empty($user['mobile']) && !empty($user['erpvipid'])){

                    $ty= M('store_distribut')->where('store_id',$sid)->field('distribut_num')->find();
                    $count1=M("users")->where('store_id',getMobileStoId())->where('is_distribut',1)->count();
                    //是否有购买
                    $is_out=M("store_module_endtime")
                        ->where('store_id',getMobileStoId())
                        ->where('type',2)->find();
                    if($is_out){
                        if($ty['distribut_num']>$count1) {
                            M('users')->where('store_id', $sid)->where('user_id', $user['user_id'])
                                ->save(['is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => "直接成为分销商"]);
                            //M('store_distribut')->where('store_id',$sid)->setDec('distribut_num');
                            $user['is_distribut']=1;
                        }
                    }else{
                        //看体验人数是否到了
                        $yy=M('distri_price')->where('type',0)->where('money',0)->find();
                        $allnum=$yy['user_num'];
                        if($allnum>$count1){
                            M('users')->where('store_id', $sid)->where('user_id', $user['user_id'])
                                ->save(['is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => "直接成为分销商"]);
                            //M('store_distribut')->where('store_id',$sid)->setDec('distribut_num');
                            $user['is_distribut']=1;
                        }
                    }
                }
            }
            session('user', $user);  //覆盖session 中的 user
            $this->user = $user;
            $this->user_id = $user['user_id'];
            $this->assign('user', $user); //存储用户信息
        }else{
            $uid=Cookie::get('user_id');
            if($uid){
                $user = M('users')->where("user_id", $uid)->where("store_id", $sid)->find();
                /***当会员不是分销商且 可以直接成为分销商不用购买***/
                if ($user['is_distribut']!= 1 && !empty($user['mobile']) && !empty($user['erpvipid'])){

                    $ty= M('store_distribut')->where('store_id',$sid)->field('distribut_num')->find();
                    $count1=M("users")->where('store_id',getMobileStoId())->where('is_distribut',1)->count();
                    //是否有购买
                    $is_out=M("store_module_endtime")
                        ->where('store_id',getMobileStoId())
                        ->where('type',2)->find();
                    if($is_out){
                        if($ty['distribut_num']>$count1) {
                            M('users')->where('store_id', $sid)->where('user_id', $user['user_id'])
                                ->save(['is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => "直接成为分销商"]);
                            //M('store_distribut')->where('store_id',$sid)->setDec('distribut_num');
                            $user['is_distribut']=1;
                        }
                    }else{
                        //看体验人数是否到了
                        $yy=M('distri_price')->where('type',0)->where('money',0)->find();
                        $allnum=$yy['user_num'];
                        if($allnum>$count1){
                            M('users')->where('store_id', $sid)->where('user_id', $user['user_id'])
                                ->save(['is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => "直接成为分销商"]);
                            //M('store_distribut')->where('store_id',$sid)->setDec('distribut_num');
                            $user['is_distribut']=1;
                        }
                    }
                }

                session('user', $user);  //覆盖session 中的 user
                $this->user = $user;
                $this->user_id = $user['user_id'];
                $this->assign('user', $user); //存储用户信息
            }
        }
        $nologin = array(
        	'login','pop_login','do_login','logout','verify','set_pwd','finished',
        	'verifyHandle','reg','send_sms_reg_code','find_pwd','check_validate_code',
        	'forget_pwd','check_captcha','check_username','send_validate_code',
        );

        if(!$this->user_id && !in_array(ACTION_NAME,$nologin)){
            header("location:" . U('Mobile/User/login', array('stoid' => getMobileStoId())));
        	exit;
        }
        if (!in_array(ACTION_NAME, $nologin)) {
            if (($this->pm_erpid && (!$user || !$user['erpvipid'])) || (empty($this->pm_erpid) && !$user ||  !$user['mobile']))
            {
                $this->redirect(U('mobile/User/login', array('stoid' => getMobileStoId())));
                exit;
            }
        }

//        $order_count = M('order')->where("user_id", $this->user_id)->count(); // 我的订单数
//        $goods_collect_count = M('goods_collect')->where("user_id", $this->user_id)->count(); // 我的商品收藏
//        $comment_count = M('comment')->where("user_id", $this->user_id)->count();//  我的评论数
//        $this->assign('order_count',$order_count);
//        $this->assign('goods_collect_count',$goods_collect_count);
//        $this->assign('comment_count',$comment_count);
    }
  
    /**
     * 分销用户中心首页
     */
    public function index(){
        $user = $user_info = M('users')->where('user_id',$this->user_id)->find();
        if(!$user){
            $this->redirect(U('mobile/User/login', array('stoid' => getMobileStoId())));
            exit;
        }
        //我的余额
        $current_money=$user['user_money'];
        $locking_money=M('withdrawals')->where(array('user_id' => $this->user_id, 'status' => 0))->sum('money');
        $lcmon=$user['frozen_money'];
        $liudong_money=number_format($current_money-$locking_money-$lcmon,2); //流动资金
        $this->assign('liudong_money',$liudong_money);
        //累计获得佣金
        //$money['achieve_money'] = Db::name('rebate_log')->where(['user_id'=>$this->user_id,'status'=>3])->sum('money');
        $time=time();

        $dy=date('Y-m-d');
        $start=$dy.' 00:00:00';
        $end=$dy.' 23:59:59';
        $start = strtotime($start);
        $end = strtotime($end);

        $money['today_money'] = Db::name('rebate_log')->where("user_id=$this->user_id and status=3 and confirm_time>=".$start." and confirm_time<=".$end)->sum('money'); //今日收入
        // 销售额 和 我的奖励
        $result = DB::query("select sum(goods_price) as goods_price, sum(money) as money from __PREFIX__rebate_log where user_id = {$this->user_id} and status>0 and status<4");
        $result = $result[0];
        $result['goods_price'] = $result['goods_price'] ? $result['goods_price'] : 0;
        $result['money'] = $result['money'] ? $result['money'] : 0;

//         $lower_count[1] = M('users')->where("first_leader", $this->user_id)->count();
//         $lower_count[2] = M('users')->where("second_leader", $this->user_id)->count();
//         $lower_count[3] = M('users')->where("third_leader", $this->user_id)->count();

        // 我的下线 订单数
        /*----
        $result2 = DB::query("select status,count(1) as c , sum(goods_price) as goods_price from `__PREFIX__rebate_log` where user_id = :user_id group by status",['user_id'=>$this->user_id]);
        $level_order = convert_arr_key($result2, 'status');
        for($i = 0; $i <= 5; $i++)
        {
            $level_order[$i]['c'] = $level_order[$i]['c'] ? $level_order[$i]['c'] : 0;
            $level_order[$i]['goods_price'] = $level_order[$i]['goods_price'] ? $level_order[$i]['goods_price'] : 0;
        }
        $withdrawals_money = M('withdrawals')->where(['user_id'=>$this->user_id,'status'=>1])->sum('money');--*/
        //print_r($level_order);
        $this->assign('user_id',$this->user_id);
        //$this->assign('level_order',$level_order); // 下线订单
        //$this->assign('lower_count',$lower_count); // 下线人数
        $this->assign('sales_volume',$result['goods_price']); // 销售额
        //$this->assign('reward',$result['money']);// 奖励
        //$this->assign('withdrawals_money',$withdrawals_money);// 已提现财富
        $this->assign('money',$money);
        upload_ylp_log('分销用户中心');
        return $this->fetch('',getMobileStoId());
    }
    
    /**
     * 下线列表
     */
    public function lower_list(){
        $level = I('get.level',1);         
        $q = I('post.q','','trim');
        $condition = array(1=>'first_leader',2=>'second_leader',3=>'third_leader');

        $where = "{$condition[$level]} = {$this->user_id}";
        $bind = array();
        if($q){
            $where .= " and (nickname like :q1 or user_id = :q2 or mobile = :q3)";
            $bind['q1'] = "%$q%";
            $bind['q2'] = $q;
            $bind['q3'] = $q;
        }

        $count = M('users')->where($where)->bind($bind)->count();
        $page = new Page($count,10);
        $list = M('users')->where($where)->bind($bind)->limit("{$page->firstRow},{$page->listRows}")->order('user_id desc')->select();
        
        $this->assign('count', $count);// 总人数
        $this->assign('page', $page->show());// 赋值分页输出
        $this->assign('list',$list); // 下线
        if($_GET['is_ajax'])
        {
            return $this->fetch('ajax_lower_list',getMobileStoId());
            exit;
        }
        upload_ylp_log('下线列表');
        return $this->fetch('',getMobileStoId());
    }    
    
    /**
     * 下线订单列表
     */
    public function order_list(){
        $status = I('get.status',0);        
        $where = ['user_id'=>$this->user_id,'status'=>['in',$status]];
        $count = M('rebate_log')->where($where)->count();
        $page = new Page($count,10);
        $list = M('rebate_log')->where($where)->order('id desc')->limit("{$page->firstRow},{$page->listRows}")->select();


        foreach ($list as $k=>$v){
             $jsonarr=null;
             if($v['commission_json'])
                $jsonarr=json_decode($v['commission_json'],true);

             $ordid=$v['order_id'];
             $goodlist=M('order_goods')->alias('a')->join('goods b','a.goods_id=b.goods_id','left')->where('a.order_id='.$ordid)->field('a.goods_num,b.goods_name,b.original_img,b.goods_id,a.goods_price,b.goods_spec,b.goods_color,b.commission,a.prom_type,b.shop_price')->select();

            foreach($goodlist as $kk=>$vv){
                $promt=$vv['prom_type'];
                $goods_id=$vv['goods_id'];
                //给积分购的
                if(doubleval($vv['goods_price'])<=0) $goodlist[$kk]['goods_price']=$vv['shop_price'];
                //如果是还没有记录
                if(empty($jsonarr)){
                    $now0 = $v['create_time'];
                    switch ($promt) {
                        case "1":
                            $where0 = [
                                'end_time' => ['>=', $now0],
                                'start_time' => ['<=', $now0],
                                'goods_id' => $goods_id,
                            ];
                            $ry = M('flash_sale')->where($where0)->find();
                            if ($ry) {
                                $goodlist[$kk]['commission'] = $ry['commission'];
                            }
                            break;
                        case "2":
                            $where0 = [
                                'end_time' => ['>=', $now0],
                                'start_time' => ['<=', $now0],
                                'goods_id' => $goods_id,
                            ];
                            $ry = M('group_buy')->where($where0)->find();
                            if ($ry) {
                                $goodlist[$kk]['commission'] = $ry['commission'];
                            }
                            break;
                        case "4":
                            $where0 = [
                                'end_time' => ['>=', $now0],
                                'start_time' => ['<=', $now0],
                                'goods_id' => $goods_id,
                            ];
                            $ry = M('integral_buy')->where($where0)->find();
                            if ($ry) {
                                $goodlist[$kk]['commission'] = $ry['commission'];
                            }
                            break;
                    }
                }else{
                   //分销模式
                   if($v['dis_moshi']==1){
                       $goodlist[$kk]['commission']=0;
                       foreach ($jsonarr as $k1=>$v1) {
                           switch ($v['level']) {
                               case 1:$goodlist[$kk]['commission'] = $v1['fir']; break;
                               case 2:$goodlist[$kk]['commission'] = $v1['sec']; break;
                               case 3:$goodlist[$kk]['commission'] = $v1['thi']; break;
                           }
                       }
                   }else{
                       $goodlist[$kk]['commission']=0;
                       foreach ($jsonarr as $k1=>$v1){
                          if($goods_id==$v1['goods_id']){
                              $goodlist[$kk]['commission']=$v1['commission']/$vv['goods_num'];
                              break;
                          }
                       }
                   }
                }
            }
            $list[$k]['goods']=$goodlist;
        }

        $user_id_list = get_arr_column($list, 'buy_user_id');

        if(!empty($user_id_list))
            $userList = M('users')->where("user_id", "in", implode(',', $user_id_list))->getField('user_id,nickname,mobile,head_pic');


        $p=I("p/d",1);
        if($count<=$p*10){
            $this->assign('mshow',0);
        }else{
            $this->assign('mshow',1);
        }
        
        $this->assign('count', $count);// 总人数
        $this->assign('page', $page->show());// 赋值分页输出        
        $this->assign('userList',$userList); // 
        $this->assign('list',$list); // 下线
        if($_GET['is_ajax'])
        {
            return $this->fetch('ajax_order_list',getMobileStoId());
            exit;
        }
        upload_ylp_log('下线订单列表');
        return $this->fetch('',getMobileStoId());
    } 

    
    /**
     * 验证码验证
     * $id 验证码标示
     */
    private function verifyHandle($id)
    {
        $verify = new Verify();
        if (!$verify->check(I('post.verify_code'), $id ? $id : 'user_login')) {
            $this->error("验证码错误");
        }
    }

    /**
     * 验证码获取
     */
    public function verify()
    {
        //验证码类型
        $type = I('get.type') ? I('get.type') : 'user_login';
        $config = array(
            'fontSize' => 40,
            'length' => 4,
            'useCurve' => true,
            'useNoise' => false,
        );
        $Verify = new Verify($config);
        $Verify->entry($type);
    }    
    
    /*
     *个人推广二维码 
     */
    public function qr_code(){
        //$ShareLink = urlencode("http://{$_SERVER[HTTP_HOST]}/Mobile/Index/index/stoid/".getMobileStoId()."/first_leader/{$this->user_id}"); //默认分享链接

        $url=curHostURL()."/Mobile/Distribut/myshop/stoid/".getMobileStoId()."/user/{$this->user_id}/first_leader/{$this->user_id}";

        $msg=base64EncodeImage($this->user['head_pic'],3);
        if($msg['status']=='success') {
            $this->assign('imgsrc', $msg['data']);
        }


        $ShareLink = urlencode($url); //默认分享链接
        if($this->user['is_distribut'] == 1)
            $this->assign('ShareLink',$ShareLink);
        upload_ylp_log('个人推广二维码');
        return $this->fetch('',getMobileStoId());
    }  

    /**
     * 分类列表显示
     */
    public function categoryList(){
        $zmsql="select zm  from __PREFIX__brand where store_id=".getMobileStoId()." group by zm";
        $brand_zm=DB::query($zmsql);
        // var_dump($brand_zm);
        foreach ($brand_zm as $val) {

            $zmsql1="select id,name,logo from __PREFIX__brand where store_id=".getMobileStoId()."  and zm='".$val['zm']."'";//
            $brand_zm1=DB::query($zmsql1);
            $arr[]=['zm'=>$val['zm'],'tmenu'=>$brand_zm1];
        }
//      var_dump($brand_zm);
//      die();
        $this->assign('brand_list',$arr);
        $this->assign('brand_zm',$brand_zm);

        $ad=M('ad')->where('store_id',getMobileStoId())->where('pid=400')
            ->cache("categoryList_ad_".getMobileStoId(),TPSHOP_CACHE_TIME)->find();
        $this->assign('ad',$ad);
        $nationlist=M('nation')->where('store_id='.getMobileStoId())->select();
        $this->assign('nation_list',$nationlist);
        upload_ylp_log('分类列表显示');
        return $this->fetch("",getMobileStoId());
    }

    /**
 * 商品列表页
 */
    public function goodsList(){
        $filter_param = array(); // 帅选数组
        $id = I('id/d',0); // 当前分类id
        $brand_id = I('brand_id/d',0);
        $nation_id = I('nation_id/d',0);

        $spec = I('spec',0); // 规格
        $attr = I('attr',''); // 属性
        $sort = I('sort','goods_id'); // 排序
        $sort_asc = I('sort_asc','desc'); // 排序
        $price = I('price',''); // 价钱
        $start_price = trim(I('start_price','0')); // 输入框价钱
        $end_price = trim(I('end_price','0')); // 输入框价钱
        if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱
        $filter_param['id'] = $id; //加入帅选条件中
        $brand_id  && ($filter_param['brand_id'] = $brand_id); //加入筛选条件中
        $nation_id && ($filter_param['nation_id'] =$nation_id); //加入筛选条件中

        $spec  && ($filter_param['spec'] = $spec); //加入筛选条件中
        $attr  && ($filter_param['attr'] = $attr); //加入筛选条件中
        $price  && ($filter_param['price'] = $price); //加入筛选条件中

        $goodsLogic = new \app\home\logic\DistributLogic(); // 前台商品操作逻辑类
        // 分类菜单显示
        $goodsCate = M('GoodsCategory')->where("id", $id)->find();// 当前分类
        //($goodsCate['level'] == 1) && header('Location:'.U('Home/Channel/index',array('cat_id'=>$id))); //一级分类跳转至大分类馆
        //$cateArr = $goodsLogic->get_goods_cate($goodsCate);

        // 帅选 品牌 规格 属性 价格
        $filter_goods_id=null;
        if(!empty($id)) {
            $cat_id_arr = getCatGrandson($id);
            /*--商品修改。store_id筛选条件--*/
            $filter_goods_id = M('goods')->where('store_id', getMobileStoId())->where("is_on_sale=1")->where("cat_id", "in", implode(',', $cat_id_arr))->getField("goods_id", true);
    }else{
$filter_goods_id = M('goods')->where('store_id', getMobileStoId())->where("is_on_sale=1")->getField("goods_id", true);
}

        // 过滤帅选的结果集里面找商品
        if($brand_id || $price || $nation_id )// 品牌或者价格
        {
            $goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price,$nation_id); // 根据 品牌 或者 价格范围 查找所有商品id
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
        }
        if($spec)// 规格
        {
            $goods_id_2 = $goodsLogic->getGoodsIdBySpec($spec); // 根据 规格 查找当所有商品id
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_2); // 获取多个帅选条件的结果 的交集
        }
        if($attr)// 属性
        {
            $goods_id_3 = $goodsLogic->getGoodsIdByAttr($attr); // 根据 规格 查找当所有商品id
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_3); // 获取多个帅选条件的结果 的交集
        }

        //筛选网站自营,入驻商家,货到付款,仅看有货,促销商品
        $sel =I('sel');
        if($sel)
        {
            $goods_id_4 = $goodsLogic->get_filter_selected($sel,$cat_id_arr);
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_4);
        }

        $filter_menu  = $goodsLogic->get_filter_menu($filter_param,'goodsList'); // 获取显示的帅选菜单
        $filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'goodsList'); // 帅选的价格期间
        $filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选品牌
        $filter_spec  = $goodsLogic->get_filter_spec($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选规格
        $filter_attr  = $goodsLogic->get_filter_attr($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选属性

        $count = count($filter_goods_id);
        $page = new Page($count,2);
        if($count > 0)
        {
            $goods_list = M('goods')->where("goods_id","in", implode(',', $filter_goods_id))->order("$sort $sort_asc")->limit($page->firstRow.','.$page->listRows)->select();
            $filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
            if($filter_goods_id2)
                $goods_images = M('goods_images')->where("goods_id", "in", implode(',', $filter_goods_id2))
                    ->cache("goods_list_goods_images_".getMobileStoId())->select();
        }
        $goods_category = M('goods_category')->where('is_show=1')
            ->cache("good_list_goods_category_".getMobileStoId())->getField('id,name,parent_id,level'); // 键值分类数组
        $this->assign('goods_list',$goods_list);
        $this->assign('goods_category',$goods_category);
        $this->assign('goods_images',$goods_images);  // 相册图片
        $this->assign('filter_menu',$filter_menu);  // 帅选菜单
        $this->assign('filter_spec',$filter_spec);  // 帅选规格
        $this->assign('filter_attr',$filter_attr);  // 帅选属性
        $this->assign('filter_brand',$filter_brand);// 列表页帅选属性 - 商品品牌
        $this->assign('filter_price',$filter_price);// 帅选的价格期间
        $this->assign('goodsCate',$goodsCate);
        //$this->assign('cateArr',$cateArr);
        $this->assign('filter_param',$filter_param); // 帅选条件
        $this->assign('cat_id',$id);
        $this->assign('page',$page);// 赋值分页输出
        $this->assign('sort_asc', $sort_asc == 'asc' ? 'desc' : 'asc');
        C('TOKEN_ON',false);
        upload_ylp_log('分销商品列表');
        if(input('is_ajax'))
           return $this->fetch('ajaxGoodsList',getMobileStoId());
        //return $this->fetch();
        else
           // return $this->fetch('',getMobileStoId());
            return $this->fetch();
    }

    /**
     * 商品列表页 ajax 翻页请求 搜索
     */
    public function ajaxGoodsList() {
        $where ='';
        $cat_id  = I("id",0); // 所选择的商品分类id
        if($cat_id > 0)
        {
            $grandson_ids = getCatGrandson($cat_id);
            $where .= " WHERE cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
        }

        /*--商品修改,store_id筛选条件--*/
        $where.=' and store_id='.getMobileStoId();

        $result = DB::query("select count(1) as count from __PREFIX__goods $where ");
        $count = $result[0]['count'];
        $page = new AjaxPage($count,10);

        $order = " order by goods_id desc"; // 排序
        $limit = " limit ".$page->firstRow.','.$page->listRows;
        $list = DB::query("select *  from __PREFIX__goods $where $order $limit");

        $this->assign('lists',$list);
        $html = $this->fetch('ajaxGoodsList',getMobileStoId()); //return $this->fetch('ajax_goods_list');
        upload_ylp_log('分销商品分页列表');
       exit($html);
    }

    /**
     * 商品详情页
     */
    public function goodsInfo(){
        C('TOKEN_ON',true);        
        $goodsLogic = new \app\home\logic\DistributLogic();
        $goods_id = I("get.id");
        $goods = M('Goods')->where("goods_id", $goods_id)->where('is_on_sale',1)->find();
        if(empty($goods)){
            $this->tp404('此商品不存在或者已下架');
        }
        if($goods['brand_id']){
            $brnad = M('brand')->where("id", $goods['brand_id'])->find();
            $goods['brand_name'] = $brnad['name'];
        }
        if($goods['nation_id']){
            $nation = M('nation')->where("id", $goods['nation_id'])->find();
            $goods['nation_name'] = $nation['name'];
        }
        if($goods['cat_id']){
            $cat = M('goods_category')->where("id", $goods['cat_id'])->find();
            $goods['cat_name'] = $cat['name'];
        }
        $goods_images_list = M('GoodsImages')->where("goods_id", $goods_id)->select(); // 商品 图册
    //    $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
       // $goods_attr_list = M('GoodsAttr')->where("goods_id", $goods_id)->select(); // 查询商品属性表

        //$filter_spec = $goodsLogic->get_spec($goods_id);
        $filter_spec=M('goods')->where('sku',$goods['sku'])->where("is_on_sale",1)->select();
         
       // $spec_goods_price  = M('spec_goods_price')->where("goods_id", $goods_id)->getField("key,price,store_count"); // 规格 对应 价格 库存表
        M('Goods')->where("goods_id=$goods_id")->save(array('click_count'=>$goods['click_count']+1 )); //统计点击数
        $commentStatistics = $goodsLogic->commentStatistics($goods_id);// 获取某个商品的评论统计     
     //   $this->assign('spec_goods_price', json_encode($spec_goods_price,true)); // 规格 对应 价格 库存表
        $goods['sale_num'] = M('order_goods')->where(['goods_id'=>$goods_id,'is_send'=>1])->count();

        //商品促销
        if($goods['prom_type'] == 1)
        {
            $prom_goods = M('prom_goods')->where(['id'=>$goods['prom_id'],'is_close'=>0])->find();
            $this->assign('prom_goods',$prom_goods);// 商品促销
            $goods['flash_sale'] = get_goods_promotion($goods['goods_id']);                        
            $flash_sale = M('flash_sale')->where("id", $goods['prom_id'])->find();
            $this->assign('flash_sale',$flash_sale);
            $goods['discount'] = round($goods['flash_sale']['price']/$goods['shop_price'],2)*10;
        }else{
            $goods['discount'] = round($goods['shop_price']/$goods['market_price'],2)*10;
        }

        //当前用户收藏
        $user_id = cookie('user_id');
        //$collect = M('goods_collect')->where("goods_id=$goods_id and user_id=$user_id")->count();
        $collect = M('goods_collect')->where(array("goods_id"=>$goods_id ,"user_id"=>$user_id))->count();
        $goods_collect_count = M('goods_collect')->where(array("goods_id"=>$goods_id))->count(); //商品收藏数
        $this->assign('collect',$collect);
        $this->assign('commentStatistics',$commentStatistics);//评论概览
      //  $this->assign('goods_attribute',$goods_attribute);//属性值
      //  $this->assign('goods_attr_list',$goods_attr_list);//属性列表
        $this->assign('filter_spec',$filter_spec);//规格参数
        $this->assign('goods_images_list',$goods_images_list);//商品缩略图
        $this->assign('goods',$goods);
        $this->assign('goods_collect_count',$goods_collect_count); //商品收藏人数
        upload_ylp_log('分销商品详情');
        return $this->fetch('',getMobileStoId());
    }


    /**
     * 商品详情页
     */
    public function detail(){
        //  form表单提交
        C('TOKEN_ON',true);
        $goods_id = I("get.id/d");
        $goods = M('Goods')->where("goods_id", $goods_id)->find();
        $this->assign('goods',$goods);
        upload_ylp_log('分销商品详情');
        return $this->fetch('',getMobileStoId());
    }

    /*
     * 商品评论
     */
    public function comment(){
        $goods_id = I("goods_id/d",0);
        $this->assign('goods_id',$goods_id);
        upload_ylp_log('分销商品评论');
        return $this->fetch('',getMobileStoId());
    }

    /*
     * ajax获取商品评论
     */
    public function ajaxComment(){        
        $goods_id = I("goods_id/d",0);
        $commentType = I('commentType','1'); // 1 全部 2好评 3 中评 4差评
        if($commentType==5){
            $where = "goods_id = :goods_id and parent_id = 0 and img !='' ";
        }else{
            $typeArr = array('1'=>'0,1,2,3,4,5','2'=>'4,5','3'=>'3','4'=>'0,1,2');
            $where = "goods_id = :goods_id and parent_id = 0 and ceil((deliver_rank + goods_rank + service_rank) / 3) in($typeArr[$commentType])";
        }

        $where.=' and store_id='.getMobileStoId();

        $count = M('Comment')->where($where)->bind(['goods_id'=>$goods_id])->count();
        $page_count = 5;
        $page = new AjaxPage($count,$page_count);
        $list = M('Comment')
                ->alias('c')
                ->join('__USERS__ u','u.user_id = c.user_id','LEFT')
                ->where($where)
                ->bind(['goods_id'=>$goods_id])
                ->order("add_time desc")
                ->limit($page->firstRow.','.$page->listRows)
                ->select();
        $replyList = M('Comment')->where(['goods_id'=>$goods_id,'parent_id'=>['>',0]])->order("add_time desc")->select();
        foreach($list as $k => $v){
            $list[$k]['img'] = unserialize($v['img']); // 晒单图片            
        }
        $this->assign('goods_id',$goods_id);//商品id
        $this->assign('commentlist',$list);// 商品评论
        $this->assign('commentType',$commentType);// 1 全部 2好评 3 中评 4差评 5晒图
        $this->assign('replyList',$replyList); // 管理员回复
        $this->assign('count', $count);//总条数
        $this->assign('page_count', $page_count);//页数
        $this->assign('current_count', $page_count*I('p'));//当前条
        $this->assign('p', I('p'));//页数
        upload_ylp_log('ajax获取商品评论');
        return $this->fetch('',getMobileStoId());
    }
    
    /*
     * 获取商品规格
     */
    public function goodsAttr(){
        $goods_id = I("get.goods_id/d",0);
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id", $goods_id)->select(); // 查询商品属性表
        $this->assign('goods_attr_list',$goods_attr_list);
        $this->assign('goods_attribute',$goods_attribute);
        upload_ylp_log('获取商品规格');
        return $this->fetch('',getMobileStoId());
    }

    /**
     * 积分商城
     */
    public function integralMall()
    {
        $rank= I('get.rank');
        //以兑换量(购买量)排序
        if($rank == 'num'){
            $ranktype = 'sales_sum';
            $order = 'desc';
        }
        //以需要积分排序
        if($rank == 'integral'){
            $ranktype = 'exchange_integral';
            $order = 'desc';
        }
        $point_rate = tpCache('shopping.point_rate',getMobileStoId());
        $goods_where = array(
            'is_on_sale' => 1,  //是否上架
        );
        //积分兑换筛选
        $exchange_integral_where_array = array(array('gt',0));

        // 分类id
        if (!empty($cat_id)) {
            $goods_where['cat_id'] = array('in', getCatGrandson($cat_id));
        }
        //我能兑换
        $user_id = cookie('user_id');
        if (!empty($user_id)) {
            //获取用户积分
            $user_pay_points = intval(M('users')->where(array('user_id' => $user_id))->getField('pay_points'));
            if ($user_pay_points !== false) {
                array_push($exchange_integral_where_array, array('lt', $user_pay_points));
            }
        }
        $goods_where['exchange_integral'] =  $exchange_integral_where_array;  //拼装条件
        $goods_list_count = M('goods')->where($goods_where)->count();   //总页数
        $page = new Page($goods_list_count, 15);
        $goods_list = M('goods')->where($goods_where)->order($ranktype ,$order)->limit($page->firstRow . ',' . $page->listRows)->select();
        $goods_category = M('goods_category')->where(array('level' => 1))->select();

        $this->assign('goods_list', $goods_list);
        $this->assign('page', $page->show());
        $this->assign('goods_list_count',$goods_list_count);
        $this->assign('goods_category', $goods_category);//商品1级分类
        $this->assign('point_rate', $point_rate);//兑换率
        $this->assign('totalPages',$page->totalPages);//总页数
        if(IS_AJAX){
            return $this->fetch('ajaxIntegralMall',getMobileStoId()); //获取更多
        }
        upload_ylp_log('积分商城');
        return $this->fetch('',getMobileStoId());
    }
	/**
     * 我的小店
     */
    public function myshop(){
        $stoid=I('stoid/d');
        $time=time();
//        $filter_param = array(); // 帅选数组
//        $id = I('get.id/d',0); // 当前分类id
//        $brand_id = I('brand_id',0);
//        $nation_id = I('nation_id',0);
//        $price = I('price',''); // 价钱

        $sort = I('sort','on_time'); // 排序
        $sort_asc = I('sort_asc','desc'); // 排序

//        $start_price = trim(I('start_price','0')); // 输入框价钱
//        $end_price = trim(I('end_price','0')); // 输入框价钱
//        if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱

//        $id && $filter_param['id'] = $id; //加入帅选条件中
//        $brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中
//        $price  && ($filter_param['price'] = $price); //加入帅选条件中
//        $nation_id  && ($filter_param['nation_id'] = $nation_id); //加入帅选条件中

        $key = urldecode(trim(I('key',''))); // 关键字搜索
//        $key  && ($filter_param['key'] = $key); //加入帅选条件中
//        $qtype = I('qtype','');
//        if($qtype){
//            //$where  = array('is_on_sale' => 1);
//            $filter_param['qtype'] = $qtype;
//            $where[$qtype] = 1;
//        }
        if($key) $where['keywords|goods_sn|goods_name|sku'] = array('like','%'.$key.'%');
        $where['store_id']=$stoid;
        $where['is_on_sale']=1;

        $type=I('type/d',1);
        if($type==2){
            $where['is_new']=1;
        }

        $first_leader=I("first_leader");
        $userid=$first_leader;
        if(empty($userid)){
            $userid=$this->user_id;
        }else{
           $luser=M('users')->where('user_id',$first_leader)->find();
           $this->assign('luser',$luser);
        }

        $goodsarr=[];
        /*--个人上架商品--*/
        $disgoods=M("distribut_usergoods")->where("store_id",getMobileStoId())
             ->where("user_id",$userid)->where("isup",1)->getField('good_id',true);
        $goodsarr= array_merge($goodsarr, $disgoods);  /*--数组合并--*/
        /*--主营商品--*/
        $zhugoods=M('goods')->where("dis_type=0")->where("store_id",getMobileStoId())->getField('goods_id',true);
        $goodsarr= array_merge($goodsarr, $zhugoods); /*--数组合并--*/

        /*--筛选的商品集合--*/
        $filter_goods_id=$goodsarr;
        if($goodsarr) {
            $ms=tpCache('distribut.pattern',$stoid);
            $where1='on_time<'.$time.' and down_time>'.$time.' or down_time=0 or down_time is null or down_time=""';
            $where2="1=1";
            if($ms==0) $where2.=' and commission>0';
            if($ms==1) $where2.=' and (fir_rate+sec_rate+thi_rate>0)';

            /*--全部商品--*/
            $allcount = M("goods")->where("is_on_sale", 1)->where($where1)->where($where2)->where('goods_id', "in", $goodsarr)->count();
            $this->assign('allcount', $allcount);
            /*--新品品--*/
            $newcount =  M("goods")->where("is_on_sale", 1)->where($where1)->where($where2)->where('goods_id', "in", $goodsarr)->where('is_new=1')->count();
            $this->assign('newcount', $newcount);

//            $goodsLogic = new \app\home\logic\DistributLogic(); // 前台商品操作逻辑类
            // 过滤帅选的结果集里面找商品
//            if ($brand_id || $nation_id)// 品牌或者国别
//            {
//                $goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice2($brand_id, $nation_id); // 根据 品牌 或者 价格范围 查找所有商品id
//                $filter_goods_id = array_intersect($filter_goods_id, $goods_id_1); // 获取多个帅选条件的结果 的交集
//            }

            //筛选网站自营,入驻商家,货到付款,仅看有货,促销商品
//            $sel = I('sel');
//            if ($sel) {
//                $goods_id_4 = $goodsLogic->get_filter_selected($sel);
//                $filter_goods_id = array_intersect($filter_goods_id, $goods_id_4);
//            }
            //$filter_menu = $goodsLogic->get_filter_menu($filter_param, 'search'); // 获取显示的帅选菜单

            /*--如果有价格条件--*/
//            $where1="";
//            if($price) {
//                $pricearr = explode('-', $price);
//                $where1=" having final_price>=".$pricearr[0]." and final_price<=".$pricearr[1];
//            }
            /*--算出总数--*/
            $cm = M('goods')->where("goods_id", "in", implode(',', $filter_goods_id))
                ->where($where2)
                ->where($where)->where($where1)->getField("goods_id", true);

            $cm=implode(',',$cm);
            if (empty($cm)) $cm=0;
            $str="select a.goods_name,a.goods_id,a.original_img, a.sales_sum,a.commission,a.is_new,a.mz_price,a.prom_type,a.prom_id,a.cardprice1,a.cardprice2,a.cardprice3,CAST(case when (a.prom_type>0 and a.prom_type<3 and b.id<>'') 
                  or (a.prom_type=4 and b.is_show=1 and b.id<>'') or (a.prom_type=6 and b.id<>'') then b.prom_price else  a.shop_price end as decimal(9,2)) 
                  as final_price,b.prom_integral from __PREFIX__goods a left join (select id,commission,is_show,prom_price,type,expression,prom_integral,goods_listid,good_object,prom_type from __PREFIX__activitylist  where is_end=0 and (s_time<=" . $time . " or (warm_uptime<=" . $time . " and warm_uptime<>0)) and e_time>=" . $time . " and store_id=" . $stoid . ") as b  on locate(CONCAT(',',a.goods_id,','),
                  b.goods_listid)>0 and (b.good_object=1 or b.prom_type<>3) where a.goods_id in(".$cm.") order by ".$sort." ".$sort_asc;

            $arr=Db::query($str);
            $count = count($arr);
            //$pricearr=get_arr_column($arr,'final_price');
            //$filter_price = $goodsLogic->get_filter_price2($pricearr, $filter_param, 'search',1);        // 帅选的价格期间
            //$filter_nation = $goodsLogic->get_filter_nation($filter_goods_id, $filter_param, 'search');    // 帅选的价格期间
            //$filter_brand = $goodsLogic->get_filter_brand($filter_goods_id, $filter_param, 'search', 1); // 获取指定分类下的帅选品牌
            /*--计算分页--*/
            $end=I('p/d',1)*10;
//          $mshow=0;
            if ($count > 0) {
                $fir=I('p/d',1)*10-10;
                if($count<$end) $end=$count;
                for($i=$fir;$i<$end;$i++){
                    $arr[$i]['final_price']= number_format($arr[$i]['final_price'],2);
                    $goods_list[]=$arr[$i];
                }
            }

            if ($count > I('p/d', 1) * 10) {
                $this->assign('mshow', 1);
            } else {
                $this->assign('mshow', 0);
            }
            $rank_switch = tpCache('shopping.rank_switch',$stoid);//等级价格
            if ($rank_switch){
                //$this->assign('rank_field',session('user')['card_field']);
                $user=session('user');
                $rand_end= empty($user['card_expiredate'])?0:strtotime($user['card_expiredate']);
                $card_field=$rand_end>time()?$user['card_field']:0;
                $this->assign('rank_field',$card_field);
            }

            $this->assign('mz_vip',session('user')['is_mzvip']);
            $this->assign('stoid', getMobileStoId());
            $this->assign('goods_list', $goods_list);
            //$this->assign('goods_category', $goods_category);
            //$this->assign('goods_images', $goods_images);  // 相册图片
           // $this->assign('filter_menu', $filter_menu);  // 帅选菜单
//            $this->assign('filter_brand', $filter_brand);// 列表页帅选属性 - 商品品牌
//            $this->assign('filter_price', $filter_price);// 帅选的价格期间
//            $this->assign('filter_nation', $filter_price);// 帅选的价格期间
//            $this->assign('filter_param', $filter_param); // 帅选条件
            $this->assign('key',$key);
            //$this->assign('page', $page);// 赋值分页输出
            $this->assign('sort_asc', $sort_asc == 'asc' ? 'desc' : 'asc');
            C('TOKEN_ON', false);
            upload_ylp_log('我的小店');
            if (input('is_ajax'))
                return $this->fetch('ajaxGoodsList', getMobileStoId());
            else
                return $this->fetch('', getMobileStoId());
        }
    }
     /**
     * 我的分销商品
     */
    public function search(){

        $filter_param = array(); // 帅选数组
        $id = I('get.id/d',0); // 当前分类id
        $brand_id = I('brand_id',0);                
        $sort = I('sort','is_new'); // 排序
        $sort_asc = I('sort_asc','desc'); // 排序
        $price = I('price',''); // 价钱

        $start_price = trim(I('start_price','0')); // 输入框价钱
        $end_price = trim(I('end_price','0')); // 输入框价钱
        if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱       
        $filter_param['id'] = $id; //加入帅选条件中
        $brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中                
        $price  && ($filter_param['price'] = $price); //加入帅选条件中
        $q = urldecode(trim(I('q',''))); // 关键字搜索
        $q  && ($_GET['q'] = $filter_param['q'] = $q); //加入帅选条件中
        $qtype = I('qtype','');

        if($qtype){
            //$where  = array('is_on_sale' => 1);
            $filter_param['qtype'] = $qtype;
            $where[$qtype] = 1;
        }
        if($q) $where['goods_name'] = array('like','%'.$q.'%');

        $where['store_id']=getMobileStoId();
        $where['is_on_sale']=1;
        
        $goodsLogic = new \app\home\logic\DistributLogic(); // 前台商品操作逻辑类
        $filter_goods_id = M('goods')->where($where)->getField("goods_id",true);

        // 过滤帅选的结果集里面找商品
        if($brand_id || $price)// 品牌或者价格
        {
            $goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price); // 根据 品牌 或者 价格范围 查找所有商品id
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
        }

        //筛选网站自营,入驻商家,货到付款,仅看有货,促销商品
        $sel = I('sel');
        if($sel)
        {
            $goods_id_4 = $goodsLogic->get_filter_selected($sel);
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_4);
        }

        $filter_menu  = $goodsLogic->get_filter_menu($filter_param,'search'); // 获取显示的帅选菜单
        $filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'search'); // 帅选的价格期间
        $filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'search',1); // 获取指定分类下的帅选品牌        
        
        $count = count($filter_goods_id);
        $page = new Page($count,10);
        if($count > 0)
        {
             $goods_list = M('goods')->where("goods_id", "in", implode(',', $filter_goods_id))->order("$sort $sort_asc")->alias('a')
->join('wxd_distribut_usergoods w',"a.goods_id = w.good_id and a.store_id = w.store_id and user_id=".$this->user_id,'LEFT')->where("a.dis_type=0 OR w.isup=1")->limit($page->firstRow.','.$page->listRows)->select();
            $filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
            if($filter_goods_id2)
                $goods_images = M('goods_images')
                    ->where("goods_id", "in", implode(',', $filter_goods_id2))->select();
        }
        $goods_category = M('goods_category')->where('is_show=1')->getField('id,name,parent_id,level'); // 键值分类数组


        if($count>I('p/d',0)*10){
            $this->assign('mshow', 1);
        }else{
            $this->assign('mshow', 0);
        }


        $this->assign('stoid',getMobileStoId());

        $this->assign('goods_list',$goods_list);
        $this->assign('goods_category',$goods_category);
        $this->assign('goods_images',$goods_images);  // 相册图片
        $this->assign('filter_menu',$filter_menu);  // 帅选菜单     
        $this->assign('filter_brand',$filter_brand);// 列表页帅选属性 - 商品品牌
        $this->assign('filter_price',$filter_price);// 帅选的价格期间      
        $this->assign('filter_param',$filter_param); // 帅选条件        
        $this->assign('page',$page);// 赋值分页输出
        $this->assign('sort_asc', $sort_asc == 'asc' ? 'desc' : 'asc');
        C('TOKEN_ON',false);
        upload_ylp_log('我的分销商品');
        if(input('is_ajax'))
            return $this->fetch('ajaxGoodsList',getMobileStoId());
        else
            return $this->fetch('',getMobileStoId());
    }

  /**
     * 分销商品搜索列表页
     */
    public function searchdistribution(){

        $uid = Cookie::get('user_id');
        $this->assign('uid', $uid);

        $stoid=I('stoid/d');
        $filter_param = array(); // 帅选数组

        $id = I('get.id/d',0); // 当前分类id
        $brand_id = I('brand_id',0);
        $nation_id = I('nation_id',0);
        $price = I('price',''); // 价钱

        $sort = I('sort','on_time'); // 排序
        $sort_asc = I('sort_asc','desc'); // 排序
        $start_price = trim(I('start_price','0')); // 输入框价钱
        $end_price = trim(I('end_price','0')); // 输入框价钱
        if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱
        $id && $filter_param['id'] = $id; //加入帅选条件中
        $brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中                
        $nation_id  && ($filter_param['nation_id'] = $nation_id); //加入帅选条件中
        $price  && ($filter_param['price'] = $price); //加入帅选条件中
        $q = urldecode(trim(I('q',''))); // 关键字搜索
        $q  && ($_GET['q'] = $filter_param['q'] = $q); //加入帅选条件中
        $qtype = I('qtype','');
        $time = time();

        $pattern=tpCache('distribut.pattern',$stoid);
        $this->assign('pattern',$pattern);

        if($qtype){
            $filter_param['qtype'] = $qtype;
            $where[$qtype] = 1;
        }

        if($q) $where['keywords|goods_sn|goods_name'] = array('like','%'.$q.'%');
        $where['store_id']=getMobileStoId();
        $where['is_on_sale']= 1;
        $where['dis_type']= 1;
        $where['on_time']=['<',$time];
        if($sort=='select') $sort='on_time';
        if ($sort=='dis_type') {
            $sort='on_time';$where['dis_type']=0;
        }else{
            if($pattern==0)
                $where['commission']=['>',0];
            if($pattern==1)
                $where['fir_rate|sec_rate|thi_rate']=['>',0];
        }
        
        $goodsLogic = new \app\home\logic\DistributLogic(); // 前台商品操作逻辑类
        $filter_goods_id = M('goods')->where($where)->where('down_time>'.$time.' or down_time=0 or down_time is null')->getField("goods_id",true);

        // 过滤帅选的结果集里面找商品
        if($brand_id || $nation_id)// 品牌或者国别
        {
            $goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice2($brand_id,$nation_id); // 根据 品牌 或者 国别 查找所有商品id
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
        }

        //筛选网站自营,入驻商家,货到付款,仅看有货,促销商品
        $sel = I('sel');
        if($sel)
        {
            $goods_id_4 = $goodsLogic->get_filter_selected($sel);
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_4);
        }
        $is_up=I('up',0);
        $filter_param['up']=$is_up;

        $distribut_goods=M('distribut_usergoods')->where(['store_id'=>$stoid,'user_id'=>$this->user_id,'isup'=>1])->getField('good_id',true);
        if(!empty($is_up)){
            if (I('sort') !='dis_type')
                $filter_goods_id = array_intersect($filter_goods_id,$distribut_goods); // 获取多个帅选条件的结果 的交集
        }else{
            $filter_goods_id = array_diff($filter_goods_id,$distribut_goods);
        }

        $filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'searchdistribution',1); // 获取指定分类下的帅选品牌
        $filter_nation = $goodsLogic->get_filter_nation($filter_goods_id,$filter_param,'searchdistribution',1); // 获取指定分类下的帅选品牌

        $this->assign('filter_param', $filter_param); // 帅选条件
        $this->assign('filter_brand',$filter_brand);// 列表页帅选属性 - 商品品牌
        $this->assign('filter_nation',$filter_nation);// 列表页帅选属性 - 商品国别
        $this->assign('sort_asc', $sort_asc == 'asc' ? 'desc' : 'asc');
        $this->assign('stoid', getMobileStoId());

        $this->assign('up',$is_up);
        $upmaxnum=tpCache('shop_info.distribut_goodsqty',$stoid);
        $isupnum=count($distribut_goods);
        $canupnum=$upmaxnum-$isupnum;

        $this->assign('canupnum',$canupnum);
        $this->assign('isupnum',$isupnum);

        if (input('is_ajax')) {
            /*--如果有价格条件--*/
            $where = "";
            if ($price) {
                $pricearr = explode('-', $price);
                $where = " having fcommission>=" . $pricearr[0] . " and fcommission<=" . $pricearr[1];
            }

            if (empty($filter_goods_id)) {
                $filter_goods_id = [-1];
            }

            $str = "select a.prom_type,a.mz_price,a.cardprice1,a.cardprice2,a.cardprice3,a.prom_id,a.prom_type,a.goods_name,a.goods_id,a.original_img,a.sales_sum,a.dis_type,a.fir_rate,a.sec_rate,a.thi_rate,CAST(case when (a.prom_type=1 or a.prom_type=2 or a.prom_type=4) 
                    and b.id<>'' then b.commission else a.commission end as decimal(9,2)) as fcommission,CAST(case when (a.prom_type>0 and a.prom_type<3 and b.id<>'') 
                    or (a.prom_type=4 and b.is_show=1 and b.id<>'') or (a.prom_type=6 and b.id<>'') then b.prom_price else  a.shop_price end as decimal(9,2)) 
                    as final_price,b.prom_integral,c.isup from __PREFIX__goods a left join 
                    (select id,commission,is_show,prom_price,type,expression,prom_integral,goods_listid,good_object,prom_type from __PREFIX__activitylist 
                    where is_end=0 and (s_time<=" . $time . " or warm_uptime<=" . $time . ") and e_time>=" . $time . " and store_id=" . $stoid . ") as b 
                    on locate(CONCAT(',',a.goods_id,','),b.goods_listid)>0 and (b.good_object=1 or b.prom_type<>3) left join 
                    (select good_id,isup,store_id from __PREFIX__distribut_usergoods where user_id=" . $this->user_id ." ) c 
                    on a.goods_id=c.good_id and a.store_id=c.store_id where a.goods_id in(" . implode(',', $filter_goods_id) . ") and on_time<".$time." and (a.down_time>".$time." or a.down_time=0 or a.down_time is null or a.down_time='' ) order by " . $sort . " " . $sort_asc;

            //mlog($str,'searchdistribution/'.$stoid);					
			$arr = Db::query($str);
            $count = count($arr);
//            $pricearr = get_arr_column($arr, 'fcommission');
            $pricearr0 = get_arr_column($arr, 'final_price');
            //$filter_menu  = $goodsLogic->get_filter_menu($filter_param,'searchdistribution'); // 获取显示的帅选菜单
            $filter_price = $goodsLogic->get_filter_price($pricearr0,$filter_param,'searchdistribution'); // 帅选的价格期间

            $end = I('p/d', 1) * 10;
//            $mshow = 0;

            if ($count > 0) {
                $fir = I('p/d', 1) * 10 - 10;
                if ($count < $end) $end = $count;
                for ($i = $fir; $i < $end; $i++) {
                    $prom_type=$arr[$i]['prom_type'];
                    if($pattern==1) {
                        if ($prom_type == 1) {
                            $fb=M('flash_sale')->where('id',$arr[$i]['prom_id'])
                                ->where('is_end',0)->where('edit_time>'.time())->find();
                            $arr[$i]['fir_rate']=$fb['fir_rate'];
                            $arr[$i]['sec_rate']=$fb['sec_rate'];
                            $arr[$i]['thi_rate']=$fb['thi_rate'];
                        }
                        if ($prom_type == 2) {
                            $fb=M('group_buy')->where('id',$arr[$i]['prom_id'])
                                ->where('is_end',0)->where('edit_time>'.time())->find();
                            $arr[$i]['fir_rate']=$fb['fir_rate'];
                            $arr[$i]['sec_rate']=$fb['sec_rate'];
                            $arr[$i]['thi_rate']=$fb['thi_rate'];
                        }
                        if ($prom_type == 4) {
                            $fb=M('integral_buy')->where('id',$arr[$i]['prom_id'])->where('is_show',1)
                                ->where('is_end',0)->where('edit_time>'.time())->find();
                            $arr[$i]['fir_rate']=$fb['fir_rate'];
                            $arr[$i]['sec_rate']=$fb['sec_rate'];
                            $arr[$i]['thi_rate']=$fb['thi_rate'];
                        }
                    }
                    $arr[$i]['final_price'] = number_format($arr[$i]['final_price'], 2);
                    $goods_list[] = $arr[$i];
                }
            }
            //$goods_category = M('goods_category')->where('is_show=1')->getField('id,name,parent_id,level'); // 键值分类数组
            if ($count > I('p/d', 1) * 10) {
                $this->assign('mshow', 1);
            } else {
                $this->assign('mshow', 0);
            }

            $this->assign('user_id', $this->user_id);
            $this->assign('goods_list', $goods_list);
            //$this->assign('goods_category',$goods_category);
            //$this->assign('goods_images',$goods_images);  // 相册图片
            //$this->assign('filter_menu',$filter_menu);  // 帅选菜单
            if($filter_price)
               $this->assign('filter_price', json_encode($filter_price));// 帅选的价格期间
            $rank_switch = tpCache('shopping.rank_switch',$stoid);//等级价格
            $mz_switch = tpCache('shopping.is_beauty',$stoid);//美妆价格
            if ($rank_switch){
                //$this->assign('rank_field',session('user')['card_field']);
                $user=session('user');
                $rand_end= empty($user['card_expiredate'])?0:strtotime($user['card_expiredate']);
                $card_field=$rand_end>time()?$user['card_field']:0;
                $this->assign('rank_field',$card_field);
            }
            if ($mz_switch){
                $this->assign('mz_vip',session('user')['is_mzvip']);
            }
            //$this->assign('page',$page);// 赋值分页输出
            C('TOKEN_ON', false);
            upload_ylp_log('分销商品列表');
            return $this->fetch('ajaxdistribution', $stoid);
        }
        return $this->fetch('',$stoid);
    }

    /**
     * 商品搜索列表页
     */
    public function ajaxSearch()
    {
        return $this->fetch('',getMobileStoId());
    }

    /**
     * 品牌街
     */
    public function brandstreet()
    {
        $getnum = 9;   //取出数量
        $goods=M('goods')->where(array('is_recommend'=>1,'is_on_sale'=>1))
            ->page(1,$getnum)->cache("brandstreet_".getMobileStoId(),TPSHOP_CACHE_TIME)->select(); //推荐商品
        for($i=0;$i<($getnum/3);$i++){
            //3条记录为一组
            $recommend_goods[] = array_slice($goods,$i*3,3);
        }
        $where = array(
            'is_hot' => 1,  //1为推荐品牌
        );
        $count = M('brand')->where($where)->count(); // 查询满足要求的总记录数
        $Page = new Page($count,20);
        $show = $Page->show();// 分页显示输出
        $brand_list = M('brand')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('sort desc')->select();
        $this->assign('Page',$show);  //赋值分页输出
        $this->assign('recommend_goods',$recommend_goods);  //品牌列表
        $this->assign('brand_list',$brand_list);            //推荐商品
        upload_ylp_log('品牌街');
        if(I('is_ajax')){
            return $this->fetch('ajaxBrandstreet',getMobileStoId());
        }
        return $this->fetch('',getMobileStoId());
    }
     /**
     * 商品列表—分销商上下架  增加   20170321
     */
    public function goodsList_distribution()
    {
        $filter_param = array(); // 帅选数组
        $id = I('id/d',0); // 当前分类id
        $brand_id = I('brand_id/d',0);
        $spec = I('spec',0); // 规格
        $attr = I('attr',''); // 属性
        $sort = I('sort','is_new'); // 排序
        $sort_asc = I('sort_asc','desc'); // 排序
        $price = I('price',''); // 价钱
        $start_price = trim(I('start_price','0')); // 输入框价钱
        $end_price = trim(I('end_price','0')); // 输入框价钱
        if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱       
        $filter_param['id'] = $id; //加入帅选条件中
        $brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中
        $spec  && ($filter_param['spec'] = $spec); //加入帅选条件中
        $attr  && ($filter_param['attr'] = $attr); //加入帅选条件中
        $price  && ($filter_param['price'] = $price); //加入帅选条件中
         
        $goodsLogic = new \app\home\logic\DistributLogic(); // 前台商品操作逻辑类
        // 分类菜单显示
        $goodsCate = M('GoodsCategory')->where("id", $id)->find();// 当前分类
        //($goodsCate['level'] == 1) && header('Location:'.U('Home/Channel/index',array('cat_id'=>$id))); //一级分类跳转至大分类馆
        $cateArr = $goodsLogic->get_goods_cate($goodsCate);
         
        // 帅选 品牌 规格 属性 价格
        $cat_id_arr = getCatGrandson ($id);
        
        $filter_goods_id = M('goods')->where("is_on_sale=1")->where("cat_id", "in" ,implode(',', $cat_id_arr))->getField("goods_id",true);
        
        // 过滤帅选的结果集里面找商品
        if($brand_id || $price)// 品牌或者价格
        {
            $goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price); // 根据 品牌 或者 价格范围 查找所有商品id
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
        }
        if($spec)// 规格
        {
            $goods_id_2 = $goodsLogic->getGoodsIdBySpec($spec); // 根据 规格 查找当所有商品id
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_2); // 获取多个帅选条件的结果 的交集
        }
        if($attr)// 属性
        {
            $goods_id_3 = $goodsLogic->getGoodsIdByAttr($attr); // 根据 规格 查找当所有商品id
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_3); // 获取多个帅选条件的结果 的交集
        }

        //筛选网站自营,入驻商家,货到付款,仅看有货,促销商品
        $sel =I('sel');
        if($sel)
        {
            $goods_id_4 = $goodsLogic->get_filter_selected($sel,$cat_id_arr);
            $filter_goods_id = array_intersect($filter_goods_id,$goods_id_4);
        }
         
        $filter_menu  = $goodsLogic->get_filter_menu($filter_param,'goodsList'); // 获取显示的帅选菜单
        $filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'goodsList'); // 帅选的价格期间
        $filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选品牌
        $filter_spec  = $goodsLogic->get_filter_spec($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选规格
        $filter_attr  = $goodsLogic->get_filter_attr($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选属性
        
        $count = count($filter_goods_id);
        $page = new Page($count,2);
        if($count > 0)
        {
            $goods_list = M('goods')->where("goods_id","in", implode(',', $filter_goods_id))->order("$sort $sort_asc")->limit($page->firstRow.','.$page->listRows)->select();
            $filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
            if($filter_goods_id2)
                $goods_images = M('goods_images')->where("goods_id", "in", implode(',', $filter_goods_id2))->select();
        }
        $goods_category = M('goods_category')->where('is_show=1')->getField('id,name,parent_id,level'); // 键值分类数组
        $this->assign('goods_list',$goods_list);
        $this->assign('goods_category',$goods_category);
        $this->assign('goods_images',$goods_images);  // 相册图片
        $this->assign('filter_menu',$filter_menu);  // 帅选菜单
        $this->assign('filter_spec',$filter_spec);  // 帅选规格
        $this->assign('filter_attr',$filter_attr);  // 帅选属性
        $this->assign('filter_brand',$filter_brand);// 列表页帅选属性 - 商品品牌
        $this->assign('filter_price',$filter_price);// 帅选的价格期间
        $this->assign('goodsCate',$goodsCate);
        $this->assign('cateArr',$cateArr);
        $this->assign('filter_param',$filter_param); // 帅选条件
        $this->assign('cat_id',$id);
        $this->assign('page',$page);// 赋值分页输出
        $this->assign('sort_asc', $sort_asc == 'asc' ? 'desc' : 'asc');
        C('TOKEN_ON',false);
        if(input('is_ajax'))
            return $this->fetch('ajaxGoodsList');
        else
            return $this->fetch();
    }


    public function ajax_distribution_addapi()
    {
        $store_id = I('stoid');
        $user_id = I('user_id');
        $type = I('type/d');
        $time = time();
        $data = array();
        $data['user_id'] = $user_id;
        $data['store_id'] = $store_id;
        if ($type == 0){
            $goods = json_decode(I('goods'),true);
            foreach ($goods as $k => $v){
                $data['good_id'] = $v;
                $add=M('distribut_usergoods')->where($data)->find();
                if (!empty($add)){
                    $dataup['add_time'] = $time;
                    $dataup['isup'] = 1;
                    M('distribut_usergoods')->where($data)->update($dataup);
                }else{
                    $data['add_time'] = $time;
                    $data['isup'] = 1;
                    M('distribut_usergoods')->insert($data);
                }
            }
        }else{
            $dis_goods=M('distribut_usergoods')->where(['user_id'=>$user_id,'store_id'=>$store_id])->getField("good_id",true);
            $goods = M('goods')->where(['commission' => ['>',0],'dis_type' => 1,'store_id' =>$store_id,'is_on_sale' =>1,'on_time'=>['<',$time],'goods_id'=>['not in',$dis_goods]])
                ->where('down_time>'.$time.' or down_time=0 or down_time is null')->getField("goods_id",true);
            M('distribut_usergoods')->where(['user_id'=>$user_id,'store_id'=>$store_id])->save(['isup'=>1,'add_time'=>$time]);
            foreach ($goods as $k => $v){
                $data['good_id'] = $v;
                $data['add_time'] = $time;
                $data['isup'] = 1;
                M('distribut_usergoods')->insert($data);
            }
        }

        $data=['msg'=>"上架成功"];
        return json($data);
    }

    public function ajax_distribution_delapi()
    {
        $store_id = I('stoid');
        $user_id = I('user_id');
        $type = I('type/d');
        $time = time();
        $data = array();
        $data['user_id'] = $user_id;
        $data['store_id'] = $store_id;
        if ($type == 0){
            $goods = json_decode(I('goods'),true);
            foreach ($goods as $k => $v){
                $data['good_id'] = $v;
                $datadel['del_time'] = $time;
                $datadel['isup'] = 0;
                M('distribut_usergoods')->where($data)->update($datadel);
            }
        }else{
            M('distribut_usergoods')->where(['user_id'=>$user_id,'store_id'=>$store_id])->save(['isup'=>0,'del_time'=>$time]);
        }
        $data=['msg'=>"下架成功"];
        return json($data);
    }
	//排行榜
    public function ranking_list(){

        $sort = I('get.sort', '0');
        $p= I('get.p/d', 1);
        $pagenum=10;
        $where['a.store_id'] =getMobileStoId();
        $where['a.is_distribut'] = 1;
        $linenum=0;
        $place="无";
        $lists=null;
        if($sort=="0"){
            $sort="distribut_money";
            $where['a.distribut_money'] =array('neq',0);
            $count = M('users')->alias('a')->where($where)->count('user_id'); //总用户量
            $Page = $pager = new AjaxPage($count,$pagenum);
            $show = $Page->show();
            //如果大于0
            if ($count) {
                $lists = M('users')->alias('a')->field('a.user_id,a.head_pic,a.nickname,a.distribut_money,a.underling_number')
                    ->where($where)->order("a.distribut_money desc,a.user_id desc")->limit($Page->firstRow.','.$Page->listRows)->select(); //获排行列表

                if ($p==1) {

                    $getdistribut_money = $this->user['distribut_money'];
                    if ($getdistribut_money) {
                        $cur_num = "SELECT b.* FROM (SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r,(SELECT user_id FROM wxd_users a where a.store_id=" . getMobileStoId() . " and a.is_distribut=1 order by a.distribut_money desc,a.user_id desc) AS t) AS b WHERE b.user_id=" . $this->user['user_id'];
                        $place_res = DB::query($cur_num);
                        if ($place_res) {
                            $place = $place_res[0]['rownum'];
                        }
                    }
                    if ($place>1) {
                        //查询
                        $sql2 = "SELECT min(distribut_money) as mindistribut_money FROM wxd_users a where a.store_id=" . getMobileStoId() . " and   a.is_distribut=1 and a.distribut_money>" . $getdistribut_money . "";
                        $sql2_res = DB::query($sql2);
                        if ($sql2_res) {

                            $need = $sql2_res[0]['mindistribut_money'] - $getdistribut_money;

                        }
                    }
                }
            }



        }else{
            $sort="underling_number";

            $count = M('users')->alias('a')->where($where)->count('user_id'); //总用户量
            $Page = $pager = new AjaxPage($count,$pagenum);
            $show = $Page->show();




            if ($count) {
                $lists=M('users')->alias('a')->field('a.user_id,IFNULL(b.c,0)+IFNULL(c.c,0)+1 as underling_number,a.head_pic,a.nickname,a.distribut_money')
                    ->join('(select third_leader,COUNT(1) as c from wxd_users where store_id='.getMobileStoId().' and  is_distribut=1 group by third_leader ) b',' a.user_id=b.third_leader','left')
                    ->join('(select first_leader,COUNT(1) as c from wxd_users where store_id='.getMobileStoId().' and  is_distribut=1 group by first_leader ) c',' a.user_id=c.first_leader','left')
                    ->where($where)
                    ->order("underling_number desc,a.user_id desc")
                    ->limit($Page->firstRow.','.$Page->listRows)->select(); //获排行列表

                if ($p==1) {

                    $sql_userorder = "SELECT a.user_id,IFNULL(b.c,0)+IFNULL(c.c,0)+1 as underling_number FROM wxd_users a LEFT JOIN (select first_leader,COUNT(1) as c from wxd_users where store_id=" . getMobileStoId() . " and is_distribut=1 group by first_leader ) b ON a.user_id=b.first_leader LEFT JOIN (select second_leader,COUNT(1) as c from wxd_users where store_id=" . getMobileStoId() . " and is_distribut=1 group by second_leader ) c ON a.user_id=c.second_leader WHERE a.store_id=" . getMobileStoId() . " AND a.is_distribut = 1 ORDER BY underling_number desc,a.user_id desc";
                    $cur_num = "SELECT b.* FROM (SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r,(" . $sql_userorder . ") AS t) AS b WHERE b.user_id=" . $this->user['user_id'];
                    $place_res = DB::query($cur_num);
                    if ($place_res) {
                        $place = $place_res[0]['rownum'];
                        $getunderling_number = $place_res[0]['underling_number'];
                        $linenum = $getunderling_number;
                    }
                    if ($place>1) {
                        //查询
                        $sql2 = "SELECT a.user_id,min(IFNULL(b.c,0)+IFNULL(c.c,0)+1) as minunderling_number  FROM wxd_users a LEFT JOIN (select first_leader,COUNT(1) as c from wxd_users where store_id=" . getMobileStoId() . " and is_distribut=1 group by first_leader ) b ON a.user_id=b.first_leader LEFT JOIN (select second_leader,COUNT(1) as c from wxd_users where store_id=" . getMobileStoId() . " and is_distribut=1 group by second_leader ) c ON a.user_id=c.second_leader WHERE a.store_id=" . getMobileStoId() . " AND a.is_distribut = 1 and (IFNULL(b.c,0)+IFNULL(c.c,0)+1)>" . $getunderling_number . "";
                        $sql2_res = DB::query($sql2);
                        if ($sql2_res) {


                            $need = $sql2_res[0]['minunderling_number'] - $getunderling_number;

                        }
                    }
                }
            }

        }




        $this->assign('need', $need);//还需要
        if($count>$p*$pagenum){
            $this->assign('mshow', 1);
        }else{
            $this->assign('mshow', 0);
        }


        $this->assign('lists', $lists);
        $this->assign('place', $place);
        $this->assign('linenum', $linenum);
        if(I('is_ajax')){
            return $this->fetch('ajax_rankings',getMobileStoId());
        }
        return $this->fetch('',getMobileStoId());
    }

	 //新手必看
	 public function rule(){
        $stoid=getMobileStoId();
        $content=tpCache('distribut.distri_rule',$stoid);
        $this->assign('content', $content);
	 	return $this->fetch('',getMobileStoId());
	 }

	 //我的团队
	  public function team(){
          $user =$this->user;
          if($user['is_distribut'] != 1) {
              $this->error('您还不是分销商');
          }
          $level = I('get.level',1);
          $where=" is_distribut=1 and store_id=".getMobileStoId();

          $lev1=tpCache('distribut.first_name',getMobileStoId());
          $lev2=tpCache('distribut.second_name',getMobileStoId());
          $lev3=tpCache('distribut.third_name',getMobileStoId());

          $this->assign('lev1', $lev1);
          $this->assign('lev2', $lev2);
          $this->assign('lev3', $lev3);

          switch ($level) {
              case "1":
                  $where .= " and user_id=" . $this->user_id;
                  break;
              case "2":
                  $where .= " and first_leader=" . $this->user_id;
                  break;
              case "3":
                  $where .= " and second_leader=" . $this->user_id;
                  break;
          }

          $count = M('users')->where($where)->count();
          $page = new \think\Page($count, 10);
          $lists = M('users')
              ->field('nickname,user_id,distribut_money,reg_time,head_pic')
              ->where($where)
              ->limit("{$page->firstRow},{$page->listRows}")
              ->order('user_id desc')
              ->select();

          foreach ($lists as &$user_v) {
              if ($user_v['nickname'] === null) {
                  $user_v['nickname'] = '匿名';
              }
          }
          $this->assign('count',$count); // 总人数
          $this->assign('lists', $lists);// 下线

          if($count>I('p/d',1)*10){
              $this->assign('mshow', 1);
          }else{
              $this->assign('mshow', 0);
          }

          if(I('is_ajax')){
              return $this->fetch('ajax_team',getMobileStoId());
          }
	      return $this->fetch('',getMobileStoId());
	 }

	 //佣金明细
	 public function commission(){
         if ($this->user['is_distribut'] != 1) {
             $this->error('您还不是分销商');
         }
         $status = I('status',''); //日志状态
         $order = I('sort_asc','desc');  //排序
         $sort  = I('sort','create_time'); //排序条件
         $key= I('key'); //搜索条件

         $where ='a.user_id='.$this->user_id;
         $where.= ' and a.store_id='.getMobileStoId();
         if ($status != '') {
             $where.= '  and a.status='.$status;
         }
         if ($key != '') {
             $where.= " and (a.nickname like '%".$key."%' or b.mobile like '%".$key."%')";
         }

         $count = Db::name('rebate_log')->alias('a')->join('users b','a.buy_user_id=b.user_id')->where($where)->count();
         $page = new \think\Page($count,10);
         $list = Db::name('rebate_log')->alias('a')->join('users b','a.buy_user_id=b.user_id')->where($where)->order($sort, $order)
             ->limit($page->firstRow, $page->listRows)
             ->select();

         if($count>I('p/d',1)*10){
             $this->assign('mshow', 1);
         }else{
             $this->assign('mshow', 0);
         }
         $this->assign('count',$count); // 总人数
         $this->assign('lists', $list);// 下线
         if(I('is_ajax')){
             return $this->fetch('ajax_commission',getMobileStoId());
         }

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

    //佣金明细
    public function commissionsear(){
        $status = I('status',''); //日志状态
        $order = I('sort_asc','desc');  //排序
        $sort  = I('sort','create_time'); //排序条件
        $key= I('key'); //搜索条件

        $where ='a.user_id='.$this->user_id;
        $where.= ' and a.store_id='.getMobileStoId();
        if ($status != '') {
            $where.= '  and a.status='.$status;
        }
        if ($key != '') {
            $where.= " and (a.nickname like '%".$key."%' or b.mobile like '%".$key."%')";
        }

        $count = Db::name('rebate_log')->alias('a')->join('users b','a.buy_user_id=b.user_id')->where($where)->count();
        $page = new \think\Page($count,10);
        $list = Db::name('rebate_log')->alias('a')->join('users b','a.buy_user_id=b.user_id')->where($where)->order($sort, $order)
            ->limit($page->firstRow, $page->listRows)
            ->select();

        if($count>I('p/d',1)*10){
            $this->assign('mshow', 1);
        }else{
            $this->assign('mshow', 0);
        }
        $this->assign('count',$count); // 总人数
        $this->assign('lists', $list);// 下线

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

    }
}