Team.php 60 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
<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司,并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: 当燃
 * 专题管理
 * Date: 2016-03-09
 */

namespace app\admin\controller;
use app\admin\logic\GiftuserLogic;
use think\AjaxPage;
use think\Page;
use app\admin\logic\GoodsLogic;
use think\db;
use think\Cache;

class Team extends Base
{

    //列表
    public function index()
    {

        $id = getAdmStoId();
        $dir=ROOT_PATH.'/public/cert/'.$id.'/apiclient_cert.pem';
        //创建目录失败
        if(!file_exists($dir)){
            $this->error("请先上传微信商户平台API证书",U("admin/Wechat/setting"));
        }
        //没有校验成功
        $wx_user=M('wx_user')->where(array('store_id'=>$id))->field('check_json')->find();
        if (empty($wx_user))
        {
            $this->error("请选配置微信信息",U("admin/Wechat/setting"));
            exit();
        }
        if (empty($wx_user['check_json']))
        {
            $this->error("API证书未校验,请去校验",U("admin/Wechat/setting"));
            exit();
        }
        $getcheck_json=json_decode($wx_user['check_json'],true);
        if ($getcheck_json['code']!=1)
        {
            $this->error("API证书校验不成功,请去更新",U("admin/Wechat/setting"));
            exit();
        }


        $this->updategoodstype();
        $pagenum = 10;//每页显示多少条
        if ((int)I('pagenum/s') > 0) {
            $pagenum = I('pagenum/s');
        }
        $actname = I('actname');
        $begin = strtotime(I('add_time_begin'));
        $end = strtotime(I('add_time_end'));
        $kttype = I('kttype');

        $where="1=1";
        if ($begin) {
            $where.=' and a.start_time>'.$begin;
        }
        if ($end) {
            $where.=' and a.start_time<'.$end;
        }
        if ($kttype) {
            $condition['a.kttype'] = $kttype;
        }
        $condition['a.store_id'] = getAdmStoId();
        if (!empty($actname)) {
            $condition['a.title|c.goods_sn|c.sku'] = array('like', "%$actname%");
        }
        $condition['is_end'] = 0;
        $count = M('teamlist')->alias('a')
            ->join('(select goods_id,goods_sn,sku from wxd_goods where store_id='.getAdmStoId().') c',' c.goods_id=a.goods_id','left')
            ->where($condition)
            ->where($where)
            ->count();
        $Page = new Page($count, $pagenum);
        $show = $Page->show();

        $res = M('teamlist')->alias('a')
            ->join('(select goods_id,goods_sn,sku from wxd_goods where store_id='.getAdmStoId().') c',' c.goods_id=a.goods_id','left')
            ->where($condition)
            ->where($where)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->field('a.*,c.goods_sn,c.sku')
            ->order('a.ordid')->select();


        foreach ($res as $kj=>$vj){
            $w['store_id']=getAdmStoId();
            $w['team_id']=$vj['id'];
            $tu=M('teamgroup')->where($w)->count();
            $res[$kj]['kt_num']=$tu;

            if($vj['start_time']<time()){
                if($vj['end_time']>time())  $res[$kj]['state']='正在进行';
                else  $res[$kj]['state']='已经结束';
            }else{
                $res[$kj]['state']='还未开始';
            }
            if( $res[$kj]['is_show']==0){$res[$kj]['state']='未启用';}
        }
        $this->assign('list', $res);
        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('pager', $Page);
        $this->assign('pagenum', $pagenum);
        return $this->fetch('', getAdmStoId());
    }

    //增加/修改
    public function addinfo()
    {

        $id = getAdmStoId();
        $dir=ROOT_PATH.'/public/cert/'.$id.'/apiclient_cert.pem';
        //创建目录失败
        if(!file_exists($dir)){
            $this->error("请先上传微信商户平台API证书",U("admin/Wechat/setting"));
        }
        //没有校验成功
        $wx_user=M('wx_user')->where(array('store_id'=>$id))->field('check_json')->find();
        if (empty($wx_user))
        {
            $this->error("请选配置微信信息",U("admin/Wechat/setting"));
            exit();
        }
        if (empty($wx_user['check_json']))
        {
            $this->error("API证书未校验,请去校验",U("admin/Wechat/setting"));
            exit();
        }
        $getcheck_json=json_decode($wx_user['check_json'],true);
        if ($getcheck_json['code']!=1)
        {
            $this->error("API证书校验不成功,请去更新",U("admin/Wechat/setting"));
            exit();
        }


        $act = I('GET.act', 'add');
        $infoid = I('get.id');
        $info = array();
        $info['start_time'] = date('Y-m-d H:i:s');
        $info['end_time'] = date('Y-m-d H:i:s', time() + 3600 * 365);
        $info['store_id'] = getAdmStoId();

        $info["kttype"] = 1;
        $info["tz_yhjgtype"] = 1;
        $info["is_show"] = 1;

        if ($infoid) {
            $info = M('teamlist')->where(" store_id=" . getAdmStoId() . " and id=" . $infoid)->find();
            $is_start=$info['start_time']<time()?1:0;
            $this->assign('is_start', $is_start);

            $info['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
            $info['end_time'] = date('Y-m-d H:i:s', $info['end_time']);
            $info['show_time'] = date('Y-m-d H:i:s', $info['show_time']);

            $act = 'edit';

            $rt = M("goods")->where(array('store_id'=>getAdmStoId(),'goods_id'=>$info['goods_id']))->find();
            if ($rt) {
                $info['goods_price']=$rt['shop_price'];
                $this->assign('storecount', $rt['store_count']);
            }


        } else {
            $maxinfo = M('teamlist')->where(" store_id=" . getAdmStoId())->field("IFNULL(max(ordid),0)+1 ordid,IFNULL(max(actno),1000000)+1 actno")->find();
            if ($maxinfo) {
                $info["ordid"] = $maxinfo['ordid'];
                $info["actno"] = $maxinfo['actno'];
            }

        }
        if (IS_POST) {
            $data = I('post.');
            $data_list = $data['data'];

            unset($data['data']);
            if ($data['kttype']==3)  //阶梯团
            {
                $data['ct_rylist']=json_encode($data_list);
                $data['price']=$data_list[0]['price'];
                $data['ct_num']=$data_list[0]['rynum'];

            }
            if ($data['show_time']) {
                $data['show_time'] = strtotime($data['show_time']);
            } else {
                $data['show_time'] = strtotime($data['start_time'] . " -1   day");
            }
            $admid = getAdminId();
            $amdinfo = getAdminInfo($admid);

            $data['end_time'] = strtotime($data['end_time']);
            $data['start_time'] = strtotime($data['start_time']);
            $data['store_id'] = getAdmStoId();
            /*---操作活动总表---*/
            $adata['edit_man'] = $amdinfo['ERPName'];
            $adata['prom_type'] = 6;
            $adata['prom_price'] = $data['price'];
            $adata['goods_listid'] = "," . $data['goods_id'] . ",";
            $adata['is_show'] = 1;
            $adata['is_end'] = 0;
            $adata['warm_uptime'] = $data['show_time'];
            $adata['s_time'] = $data['start_time'];
            $adata['e_time'] = $data['end_time'];
            $adata['prom_integral'] = 0;
            $adata['store_id'] = getAdmStoId();

            $data['remark'] = nl2br($data['remark']);

            if (empty($data['id'])) {

                //--开启事务---
                Db::startTrans();
                try {

                    $data['add_time'] = time();
                    $data['add_ip'] = getIP();

                    $adata['add_time'] = time();
                    $adata['add_ip'] = getIP();
                    $r = M('teamlist')->add($data);

                    M('goods')->where("goods_id=" . $data['goods_id'])->save(array('prom_id' => $r, 'prom_type' => 6));
                    $adata['act_id'] = $r;

                    M('activitylist')->save($adata);

                    /*---
                    $count=M('users')->where('store_id',getAdmStoId())->count();
                    if($count>50000){
                        $email=C('s_email');

                        $sname=tpCache('shop_info.store_name',getAdmStoId());
                        $str_start=date('Y-m-d H:i:s', $data['start_time']);
                        $str_end=date('Y-m-d H:i:s', $data['end_time']);
                        $txt="商家名称:".$sname."<br>会员数量:".$count."<br>
            活动类型:天天拼单<br>活动名称:".$data['title']."<br>活动数量:".$data['goods_num']."件<br>活动时间:".$str_start." 到 ".$str_end;
                        sendmail($email, '活动通知', $txt);

                    }---*/

                    //先建拼单活动就设置队列
                    $redis = get_redis_handle();
                    $name = get_redis_name($r, 6, getAdmStoId());
                    $namec = $name . ":c";
                    $len = $redis->lLen($name);


                    for ($i = 0; $i < ($data['goods_num']); $i++) {
                        $redis->lPush($name, "pt" . $i);
                    }
                    F($namec, 1);
                    Db::commit();

                }catch(\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error('添加活动失败', U('Team/index'));
                    exit();
                }
                $this->success('添加成功', U('Team/index'));
                exit();

            } else {

                //如果保存前是开始时间大于当前时间
                $rrp0 = M('teamlist')->where("id=" . $data['id'])
                    ->where('store_id', getAdmStoId())->field('buy_num,start_time')->find();

                /*---设置活动是秒杀销售量,当活动还没有开始的时候---*/
                if($rrp0['start_time']>time()) {
                    //$redis = new \Redis();
                    //$redis->connect(redisip, 6379);
                    $redis=get_redis_handle();
                    //$name='pind'.$data['id'].'-'.getAdmStoId();
                    //$namec='pind'.$data['id'].'-'.getAdmStoId().'c';
                    $name=get_redis_name($data['id'],6,getAdmStoId());
                    $namec=$name.":c";

                    $len = $redis->lLen($name);

                    if (empty($len)) {
                        for ($i = 0; $i < ($data['goods_num'] - $rrp0['buy_num']); $i++) {
                            $redis->lPush($name, "pt" . $i);
                        }
                        F($namec, 1);

                    } else if ($len != ($data['goods_num'] - $rrp0['buy_num'])) {
                        //$redis->delete($name);
                        del_redis($redis,$name);
                        for ($i = 0; $i < ($data['goods_num'] - $rrp0['buy_num']); $i++) {
                            $redis->lPush($name, "pt" . $i);
                        }
                        F($namec, 1);
                    }
                }


                $data['edit_time'] = time();
                $data['edit_mark'] = "编辑抢购活动";
                $data['edit_ip'] = getIP();
                $adata['edit_time'] = $data['edit_time'];
                $adata['edit_ip'] = $data['edit_ip'];

                M('activitylist')->where('act_id', $data['id'])->where('prom_type', 6)->save($adata);
                $r = M('teamlist')->where("id=" . $data['id'])->save($data);
                M('goods')->where("prom_type=6 and prom_id=" . $data['id'])->save(array('prom_id' => 0, 'prom_type' => 0));
                M('goods')->where("goods_id=" . $data['goods_id'])->save(array('prom_id' => $data['id'], 'prom_type' => 6));

                $this->success('编辑成功', U('Team/index'));
                exit();
            }
        }


        $this->assign('erpid', getERPId());
        $this->assign('info', $info);
        $this->assign('list', json_decode($info['ct_rylist'],true));
        $this->assign('act', $act);
        $this->assign('qclurl', QCLOUD_IMGURL);
        return $this->fetch('', getAdmStoId());
    }

    //删除
    public function info_del()
    {

        $prom_id = I('del_id/d');
        $team0= M('teamlist')->where('id',$prom_id)->field('kttype')->find();

        //--开启事务---
        Db::startTrans();
        try {
            $admid = getAdminId();
            $amdinfo = getAdminInfo($admid);
            $data['edit_man'] = $amdinfo['ERPName'];
            $data['edit_time'] = time();
            $data['edit_ip'] = getIP();
            $data['is_end'] = 1;

            $adata['edit_time'] = $data['edit_time'];
            $adata['edit_man'] = $data['edit_man'];
            $adata['edit_ip'] = $data['edit_ip'];
            $adata['is_end'] = 1;

            M('activitylist')->where(['act_id' => $prom_id, 'prom_type' => 6])->save($adata);
            M("goods")->where("store_id=" . getAdmStoId() . " and  prom_id=$prom_id and prom_type=6")
                ->save(array('prom_id' => 0, 'prom_type' => 0));
            M('teamlist')->where("store_id=" . getAdmStoId() . " and id=$prom_id")->save($data);
            Db::commit();
        }
        catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('删除活动失败', U('Team/index'));
            exit();
        }
        ClearALLCache();
        delFile(TEMP_PATH . "/" . getAdmStoId());
        $name='pind'.$prom_id.'-'.getAdmStoId();
        $namec='pind'.$prom_id.'-'.getAdmStoId().'c';

        /*---删除拼单活动缓存---*/
        //$redis = new \Redis();
        //$redis->connect(redisip, 6379);
        $redis=get_redis_handle();
        //if($redis->exists($name)) $redis->delete($name);
        del_redis($redis,$name);
        m_clearC($namec);

        //会员团要清空团redis
        if($team0['kttype']==2){
            $tg= M('teamgroup')->where('store_id',getAdmStoId())->where('team_id',$prom_id)->select();
            foreach ($tg as $k1=>$v1){
                //$name2 = 'pind'.$prom_id.'-'.$v1['actno'].getAdmStoId();
                $name2 = get_redis_name($prom_id,6,getAdmStoId()).":".$v1['actno'];
                //$redis->delete($name2);
                del_redis($redis,$name2);
            }
        }

        $this->success('删除活动成功', U('Team/index'));
    }

    //开团列表
    public function grouplist()
    {

        $this->updategoodstype();
        $pagenum = 20;//每页显示多少条
        if ((int)I('pagenum/s') > 0) {
            $pagenum = I('pagenum/s');
        }
        $p = I('p', 1);
        $begin = I('add_time_begin');
        $end = I('add_time_end');
        $this->assign('start_time', $begin);
        $this->assign('end_time', $end);
        $actname = I('actname');
        $teamid = I('teamid');

        $state=I('state');
        $where = " a.store_id=" . getAdmStoId();

        $fytype=0;
        $fymoney=0;
        if ($teamid) {
            $where .= " and a.team_id=".$teamid;
            $ac=M("teamlist")->where('id',$teamid)->field('kttype,tz_yhjgtype,tz_yyhjg')->find();
            if($ac){
                $this->assign("ktty",$ac['kttype']);
                $fytype=$ac['tz_yhjgtype'];
                $fymoney=$ac['tz_yyhjg'];
            }

        }
        if ($actname) {
            $condition['a.listno'] =$actname;
        }
        if($state) {
            $condition['a.state'] =$state;
        }
        $qdrecord = M('teamgroup');
        $count = $qdrecord->alias('a')
            ->where($where)
            ->where($condition)
            ->count();
        $Page = $pager = new Page($count, $pagenum);// 实例化分页类 传入总记录数和每页显示的记录数
        $grouplist = $qdrecord->alias('a')
            ->where($where)
            ->where($condition)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->order('a.addtime desc')
            ->select();// 查询满足要求的总记录数

        foreach ($grouplist as $kk=>$vv){
            if($vv['openvipid']){
                $usr=M("users")->where('user_id',$vv['openvipid'])->field('nickname')->find();
                $grouplist[$kk]['openvipname']=$usr['nickname'];
            }
            else{
                $grouplist[$kk]['openvipname']="商家团开团";
            }


            //阶梯团和会员团都要显示
            if($ac['kttype']==2 || $ac['kttype']==3 ){
                $tz_odr = M('order')->alias('a')
                    ->where('user_id',$vv['openvipid'])
                    ->where('a.store_id', getAdmStoId())
                    ->where('a.pt_prom_id', $vv['team_id'])
                    ->where('a.pt_listno', $vv['listno'])
                    ->where('a.is_pt_tz', 1)
                    ->field('a.order_amount,a.user_money,a.is_pt_rebate,a.order_status,a.pt_status,a.shipping_price')
                    ->find();
            }

            if($ac['kttype']==2) {
                if ($tz_odr) {
                    switch ($fytype) {
                        case 0:
                        case 1:
                            $grouplist[$kk]['fymoney'] = "无";
                            $grouplist[$kk]['fystate'] = "无";
                            break;
                        case 2://免单处理
                            if ($tz_odr['order_status'] <> 3 && $tz_odr['order_status'] <> 5 && $tz_odr['order_status'] <> 6) {
                                $grouplist[$kk]['fymoney'] = $tz_odr['order_amount'] + $tz_odr['user_money']-$tz_odr['shipping_price'];
                                if ($tz_odr['is_pt_rebate'])
                                    $grouplist[$kk]['fystate'] = "已返佣";
                                else
                                    $grouplist[$kk]['fystate'] = "待返佣";
                            }
                            break;
                        case 3://返佣
                            if ($tz_odr['order_status'] <> 3 && $tz_odr['order_status'] <> 5 && $tz_odr['order_status'] <> 6) {
                                $grouplist[$kk]['fymoney'] = $fymoney;
                                if ($tz_odr['is_pt_rebate'])
                                    $grouplist[$kk]['fystate'] = "已返佣";
                                else
                                    $grouplist[$kk]['fystate'] = "待返佣";
                            }
                            break;
                    }
                }else{
                    $grouplist[$kk]['fymoney'] = "无";
                    $grouplist[$kk]['fystate'] = "无";
                }
            }else{
                $grouplist[$kk]['fymoney'] = "无";
                $grouplist[$kk]['fystate'] = "无";
            }

            $count=M('order')
                ->where('store_id',getAdmStoId())
                ->where('pt_prom_id',$vv['team_id'])
                ->where('pt_listno',$vv['listno'])
                ->count();
            $grouplist[$kk]['buynum']=$count;
            $str="";
            switch($vv['state']){
                case 1:$str= "拼团失败";break;
                case 2:
                    if($ac['kttype']==1){
                        $str = "拼团进行中";
                    }else {
                        if ($tz_odr['pt_status'] == 0) {
                            $str = "待支付";
                        } else {
                            $str = "拼团进行中";
                        }
                    }
                    break;
                case 3: $str="拼团成功";break;
                case 4: $str="拼团成功";break;
                case 5: $str="拼团成功";break;
            }

            $grouplist[$kk]['statestr']=$str;
        }

        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('pager', $Page);
        $this->assign('pagenum', $pagenum);

        $this->assign('teamid', $teamid);
        $this->assign('grouplist', $grouplist);
        $this->assign('timegap', date('Y-m-d h:m:s', $this->begin) . ' - ' . date('Y-m-d h:m:s', $this->end));
        return $this->fetch('', getAdmStoId());
    }


    //活动到期商品状态还原
    public function updategoodstype()
    {
        $time = time();
        $data = M("teamlist")->where(array('store_id' => getAdmStoId(), 'is_end' => 0, 'end_time' => ['<', $time]))
            ->select();
        if($data) {

            //--开启事务---
            Db::startTrans();
            try {
                $pid = get_arr_column($data, 'id');
                M("teamlist")
                    ->where("id", 'in', $pid)
                    ->where(array('store_id' => getAdmStoId(), 'is_end' => 0))
                    ->save(array('is_end' => 1));

                M("activitylist")->where(array('store_id' => getAdmStoId(), 'prom_type' => 6))
                    ->where("act_id", 'in', $pid)->save(array('is_end' => 1));
                if (!empty($data)) {
                    foreach ($data as $val) {
                        M('goods')->where(array('store_id' => getAdmStoId(), 'prom_type' => 6, 'prom_id' => $val['id']))
                            ->save(array('prom_type' => 0, 'prom_id' => 0));

                        //$name = 'pind' . $val['id'] . '-' . getAdmStoId();
                        //$namec = 'pind' . $val['id'] . '-' . getAdmStoId() . 'c';
                        $name = get_redis_name($val['id'], 6, getAdmStoId());
                        $namec = $name . ":c";

                        /*---删除秒杀活动缓存---*/
                        //$redis = new \Redis();
                        //$redis->connect(redisip, 6379);
                        $redis = get_redis_handle();
                        //if ($redis->exists($name)) $redis->delete($name);
                        del_redis($redis, $name);
                        m_clearC($namec);

                        //会员团要清空团redis
                        if ($val['kttype'] == 2) {
                            $tg = M('teamgroup')->where('store_id', getAdmStoId())->where('team_id', $val['id'])->select();
                            foreach ($tg as $k1 => $v1) {
                                //$name2 = 'pind' . $val['id'] . '-' . $v1['actno'] . getAdmStoId();
                                $name2 = get_redis_name($val['id'], 6, getAdmStoId()) . ":" . $v1['actno'];
                                //$redis->delete($name2);
                                del_redis($redis, $name2);
                            }
                        }
                    }
                }
                Db::commit();
            }
            catch (\Exception $e) {
                mlog("错误".$e->getMessage(),"updategoodstype/".getAdmStoId());
                // 回滚事务
                Db::rollback();
            }
        }
    }

    //拼单购买列表
    public function buylist(){
        $pid=I("pid");
        $qh=I("qh");
        $olist=M('order')->alias('a')->join('order_goods b','a.order_id=b.order_id')
            ->join('users c','a.user_id=c.user_id')
            ->where('a.store_id',getAdmStoId())
            ->where('a.pt_prom_id',$pid)
            ->where('a.pt_listno',$qh)
            ->field('c.nickname,c.mobile,c.head_pic,a.order_sn,a.pay_sn,a.order_amount,a.user_money,a.tail_pay_type,a.pt_tail_money,
               a.pickup_id,a.address,a.province,a.city,a.district,a.twon,a.order_status,a.shipping_status,a.pay_status,a.pt_status,a.exp_type,a.order_id,a.pt_status,a.is_zsorder,a.pt_pay_time')
            ->select();

        if($olist){

            /*---获取地区---*/
            $region_list = get_region_list();
            foreach ($olist as $k=>$v){
                $pk=M("pick_up")->where('store_id',getAdmStoId())->where('pickup_id',$v['pickup_id'])
                    ->field('pickup_name')->find();
                $olist[$k]['pickup_name']=$pk['pickup_name'];

                if($v['exp_type']==0){
                    $v['provicename'] = $region_list[$v['province']]['name'];
                    $v['cityname'] = $region_list[$v['city']]['name'];
                    $v['districtname'] = $region_list[$v['district']]['name'];
                    $v['twonname'] = $region_list[$v['twon']]['name'];
                    $olist[$k]['address']= $v['provicename']. $v['cityname'].$v['districtname'].$v['twonname'].$v['address'];
                }

                $u=M('return_goods')->where('order_id',$v['order_id'])->where('store_id',getAdmStoId())->find();
                if($u){
                    $olist[$k]['rt']=$u;
                    $olist[$k]['rt_state']=$u['status'];
                }

            }
            $this->assign('olist',$olist);
        }

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


    //门店汇总
    public function storecount(){

        $pagenum = 20;//每页显示多少条
        if ((int)I('pagenum/s') > 0) {
            $pagenum = I('pagenum/s');
        }
        $p = I('p', 1);
        $begin = I('add_time_begin');
        $end = I('add_time_end');
        $getisend=I('isend');

        $this->assign('start_time', $begin);
        $this->assign('end_time', $end);

        $flashsaleid = I('teamid');//ID
        //$picksle=trim(I('picksle'));
        //$pstype=I('picksle_type');
        $pickup_id=I("pickup_id");

        $where = " a.store_id=" . getAdmStoId();
        $where .= " and  a.prom_type=6 and a.prom_id=" . $flashsaleid;

        $team=M('teamlist')->where('id',$flashsaleid)->where('store_id',getAdmStoId())
            ->field('kttype')->find();

        if($team){
           $this->assign("kttype",$team['kttype']);
        }

        /*---
        if($picksle){
            if($pstype)
                $where .= " AND c.pickup_name='".$picksle."'";
            else
                $where .= " AND c.pickup_no='".$picksle."'";
        }---*/
        if($pickup_id){
            $where .= " AND c.pickup_id='".$pickup_id."'";
        }

        if ($begin) {
            $where.=" and b.add_time>=".strtotime($begin);

        }
        if ($end) {
            $where.=" and b.add_time<=".strtotime($end);
        }
        $order_status=I('order_status');

        if($order_status!="")
        {
            switch ($order_status)
            {
                case 12:      //待付款
                    $condition['b.order_status'] = 0;
                    $condition['b.pay_status'] =0;
                    break;
                case 1:      //待发货
                    $condition['b.pay_status'] =1;
                    $condition['b.order_status'] = ['in','0,1'];
                    $condition['b.shipping_status'] =0;
                    break;
                case 11:     //待收货
                    $condition['b.order_status'] = 1;
                    I('shipping_status') != '' ? $condition['b.shipping_status'] = I('shipping_status') : $condition['shipping_status'] = ['in','1,2']; //是否发货
                    break;
                case 2:     //已收货
                    $condition['b.order_status'] = 2;
                    break;
                case 3:      //已取消
                    $condition['b.order_status'] = I('order_status');
                    break;
                case 4:      //已完成
                    $condition['b.order_status'] = I('order_status');
                    break;
                case 5:      //已作废
                    $condition['b.order_status'] = I('order_status');
                    break;
                case 6:      //已退款
                    $where.=" and (b.is_back=1 or b.order_status=6)";
                    break;
                case 13:      //已付款
                    $where.=" and b.pay_time>0 and b.order_status<>3 and b.order_status<>5";
                    break;
                case 7:      //待成团
                    $condition['b.pt_status'] =1;
                    $condition['b.order_status'] = ['in','0,1'];
                    break;

                case 8:      //待支付尾款
                    $condition['b.pt_status'] =2;
                    $condition['b.order_status'] = ['in','0,1'];
                    $condition['b.is_zsorder'] = 4;
                    break;
            }
        }

        $qdrecord = M('order_goods');


        $count = $qdrecord->alias('a')
            ->join('order b',' a.order_id=b.order_id','left')
            ->join('(select pickup_id,pickup_name,pickup_no from  wxd_pick_up where store_id='.getAdmStoId().') c','c.pickup_id=b.pickup_id','left')
            ->where($where)
            ->where($condition)
            ->count('distinct b.pickup_id');


        $sumcount = $qdrecord->alias('a')
            ->join('order b',' a.order_id=b.order_id','left')
            ->join('(select pickup_id,pickup_name,pickup_no from  wxd_pick_up where store_id='.getAdmStoId().') c','c.pickup_id=b.pickup_id','left')
            ->where($where)
            ->where($condition)
            ->sum('a.goods_num');

        $Page = $pager = new Page($count, $pagenum);// 实例化分页类 传入总记录数和每页显示的记录数

        $redmoneylist = $qdrecord->alias('a')
            ->join('order b',' a.order_id=b.order_id','left')
            ->join('(select pickup_id,pickup_name,pickup_no from  wxd_pick_up where store_id='.getAdmStoId().') c','c.pickup_id=b.pickup_id','left')
            ->where($where)
            ->where($condition)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->order('c.pickup_no asc')
            ->field('count(b.order_id) as ordernum,sum(a.goods_num) as warenum,b.pickup_id,c.pickup_name,c.pickup_no,sum(b.total_amount)all_total_amount,sum(order_amount+user_money)all_order_amount')
            ->group('b.pickup_id')
            ->select();// 查询满足要求的总记录数

        if ($p==1 && $getisend==1)
        {
            $falshinfo=M('teamlist')->where(array('store_id'=>getAdmStoId(),'id'=>$flashsaleid,'is_end'=>1))->find();
            if ($falshinfo)
            {
                if ($falshinfo['buy_num']!=$sumcount)
                {
                    $updatedata['buy_num']=$sumcount;
                }
                if ($falshinfo['order_num']!=$count)
                {
                    $updatedata['order_num']=$count;
                }
                if ($updatedata) {
                    M('teamlist')->where(array('store_id' => getAdmStoId(), 'id' => $flashsaleid, 'is_end' => 1))->save($updatedata);
                }
            }

        }
        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('sumcount', $sumcount);
        $this->assign('total', $count);
        $this->assign('flashsaleid', $flashsaleid);
        //$this->assign('picksle', $picksle);
        //$this->assign('pstype', $pstype);
        $this->assign('getorder_status', $order_status);
        $this->assign('redmoneylist', $redmoneylist);
        $this->assign('pagenum', $pagenum);
        $this->assign('timegap', date('Y-m-d h:m:s', $this->begin) . ' - ' . date('Y-m-d h:m:s', $this->end));


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

    public function historylist(){
        $this->updategoodstype();
        $condition = array();
        $pagenum = 10;//每页显示多少条
        if ((int)I('pagenum/s') > 0) {
            $pagenum = I('pagenum/s');
        }
        $actname = I('actname');
        $begin = strtotime(I('add_time_begin'));
        $end = strtotime(I('add_time_end'));

        if ($begin) {
            $condition['a.start_time'] = array('egt', $begin);
        }
        if ($end) {
            $condition['a.end_time'] = array('elt', $end);
        }

        $condition['a.store_id'] = getAdmStoId();
        if (!empty($actname)) {
            $condition['a.title|c.goods_sn|c.sku'] = array('like', "%$actname%");
        }
        $condition['a.is_end'] = 1;
        $condition['a.is_his_end'] = 0;
        $model = M('teamlist');
        $count = $model->alias('a')
            ->join('(select goods_id,goods_sn,sku from wxd_goods where store_id='.getAdmStoId().') c',' c.goods_id=a.goods_id','left')
            ->where($condition)->count();

        $Page = new Page($count, $pagenum);
        $show = $Page->show();
        $prom_list = $model
            ->alias('a')
            ->join('(select goods_id,goods_sn,sku from wxd_goods where store_id='.getAdmStoId().') c',' c.goods_id=a.goods_id','left')
            ->join('(select sum(a.goods_num) as sum_goods_num,a.prom_id from wxd_order_goods a left join wxd_order b on a.order_id=b.order_id where a.store_id='.getAdmStoId().' and a.prom_type=1 and b.pay_status=1 group by a.prom_id) b','a.id=b.prom_id','left')
            ->where($condition)->order("id desc")->limit($Page->firstRow . ',' . $Page->listRows)
            ->field('a.*,b.sum_goods_num,c.goods_sn,c.sku')
            ->select();
        $this->assign('prom_list', $prom_list);
        $this->assign('page', $show);// 赋值分页输出
        $this->assign('pager', $Page);
        $this->assign('pagenum', $pagenum);
        //upload_ylp_log('历史');
        return $this->fetch('', getAdmStoId());
    }

    public function search_goods()
    {
        $GoodsLogic = new GoodsLogic;
        $brandList = $GoodsLogic->getSortBrands();
        $this->assign('brandList', $brandList);
        $categoryList = $GoodsLogic->getSortCategory();
        $this->assign('categoryList', $categoryList);

        $where="";
        $type = I('type', '');

        if (!empty($type)) {
            $gift_list=M('gift')->where('is_end',0)->getfield('goods_id',true);
            if($gift_list)
                $where = 'is_on_sale = 1 and  is_mainshow=1 and prom_type not in (1,2,4) and store_count>0 and store_id=' . getAdmStoId() . ' and goods_id not in ('.implode(',',$gift_list).')';//赠品的搜索条件
            else
                $where = 'is_on_sale = 1 and is_mainshow=1 and prom_type not in (1,2,4) and store_count>0 and store_id=' . getAdmStoId();//赠品的搜索条件
        } else {
            $where = 'is_on_sale = 1 and is_mainshow=1 and prom_type=0 and store_count>0 and store_id=' . getAdmStoId() . '';//搜索条件
        }

        $intro = I('intro');
        if (!empty($intro)) {
            $where = "$where and " . I('intro') . " = 1";
            $this->assign('intro', $intro);
        }

        if (I('cat_id')) {
            $this->assign('cat_id', I('cat_id'));
            $grandson_ids = getCatGrandson(I('cat_id'));
            $where = " $where  and cat_id in(" . implode(',', $grandson_ids) . ") "; // 初始化搜索条件
        }

        if (I('brand_id')) {
            $this->assign('brand_id', I('brand_id'));
            $where = "$where and brand_id = " . I('brand_id');
        }

        $kword = urldecode(urldecode(I('keywords/s')));
        if (!empty($kword)) {
            $this->assign('keywords', $kword);
            $where = "$where and (goods_sn like '%" . $kword . "%' or goods_name like '%" . $kword . "%' or keywords like '%" . $kword . "%' or sku = '" . $kword . "')";
        }

        $t=time();
        $where.=" and on_time<".$t." and (down_time>".$t." or down_time=0 or down_time='' or down_time is null)";

        $count = M('goods')->where($where)->count();
        $Page = new Page($count, 10);
        $goodsList = M('goods')->where($where)->order('goods_id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $show = $Page->show();//分页显示输出
        $this->assign('page', $show);//赋值分页输出
        $this->assign('goodsList', $goodsList);
        $this->assign('pager', $Page);//赋值分页输出
        $tpl = "select_goods";

        return $this->fetch($tpl, getAdmStoId());
    }

    //拼单失败记录
    public function fail_list(){
        return $this->fetch("", getAdmStoId());
    }

    public function ajax_fail_list(){
        $stoid=getAdmStoId();
        $where="1=1";
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        if (I('add_time_begin') && I('add_time_end')) {
            //@new 新后台UI参数
            $begin = strtotime(I('add_time_begin'));
            $end = strtotime(I('add_time_end'));
        }
        if($begin && $end){
            $condition['a.add_time'] = array('between',"$begin,$end");
        }
        $condition['a.store_id']= $stoid;
        $condition['a.order_status']= 3;  //都是拼单失败的单
        $where.=" and a.is_zsorder>1"; //是拼单订单的
        $where.=" and a.pay_time>0";   //有支付的

        $keywords = I('keywords','','trim');
        if($keywords){
            $where.=" and (a.order_sn like '%".$keywords."%' or b.mobile like '%".$keywords."%' or b.nickname like '%".$keywords."%')";
        }

        $team_name=I("team_name");
        if($team_name){$where.=" and (c.title like '%".$team_name."%')";}
        $qh=I("qh");
        if($qh){ $condition['a.pt_listno']= $qh;}
        $money=I("money");
        if($money){ $where.=" and (a.pt_tail_money+a.order_amount+a.user_money)=".$money; }
        $team_type=I("team_type");
        if($team_type){ $where.=" and a.is_zsorder=".($team_type+1); }

        $pay_type=I("pay_type");
        if($pay_type==1){$where.=" and a.order_amount>0";}
        if($pay_type==2){$where.=" and a.user_money>0";}

        $back_status=I('back_status');
        if($back_status==1){
            $where.=" and a.is_zsorder=4 and a.is_back=0 and back_err_json=''";
        }
        if($back_status==2){
            $where.=" and ((a.is_zsorder<4 and a.order_status=3) or a.is_back=1) and back_err_json=''";
        }
        if($back_status==3){
            $where.=" and back_err_json<>''";
        }
        $count = M('order')->alias('a')
            ->join('(select nickname,mobile,head_pic,user_id from wxd_users where store_id='.$stoid.') b','a.user_id=b.user_id','left')
            ->join('(select id,title,actno from wxd_teamlist where store_id='.$stoid.') c','a.pt_prom_id=c.id','left')
            ->where($condition)->where($where)->count('a.order_id');

        $Page  = new AjaxPage($count,10);
        $sort_order="a.order_id desc";
        //获取订单列表
        $show = $Page->show();
        $start=$Page->firstRow;
        $page_size=$Page->listRows;

        $orderList=  M('order')->alias('a')
            ->join('(select nickname,mobile,head_pic,user_id from wxd_users where store_id='.$stoid.') b','a.user_id=b.user_id','left')
            ->join('(select id,title,actno from wxd_teamlist where store_id='.$stoid.') c','a.pt_prom_id=c.id','left')
            ->where($condition)->where($where)
            ->limit("$start,$page_size")
            ->order($sort_order)
            ->field('a.order_sn,a.add_time,a.order_amount,a.user_money,(a.order_amount+a.user_money+a.pt_tail_money) as buy_num,a.pay_status,a.order_status,a.is_zsorder,a.pt_status,a.pt_listno,a.is_back,a.back_err_json,b.mobile,b.nickname,b.head_pic,c.title,c.actno')
            ->select();

        foreach ($orderList as $k=>$v){
            $count=M('order_goods')->where('order_sn',$v['order_sn'])->sum('goods_num');
            $orderList[$k]['goods_num']= $count;
        }

        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);

        return $this->fetch("", getAdmStoId());
    }

    //给未支付尾款的退钱
    function return_order(){
        $odr_sn=I('order_sn');
        $od=M("order")->where('store_id',getAdmStoId())
            ->where('order_sn',$odr_sn)->find();
        if($od){
             if($od['is_back']==1){
                 return json(['code'=>-1,'msg'=>'该订单已退过款']);
             }
             //如果是退款失败的订单
             if($od['back_err_json']){
                 return $this->back_err_order($od,$od['back_err_json']);
             }

             //以下是拼单退款处理
             include_once "plugins/payment/weixin/weixin.class.php";
             $wx=new \weixin();
             $uy=M("order")->where('store_id',getAdmStoId())
                 ->where('order_sn',$odr_sn)
                 ->where('is_back<>1')->save(['is_back'=>1]);
             if($uy){
                 $v = $od;
                 $stoid = $od['store_id'];
                 $refund_type = tpCache('basic.refund_type', $stoid);
                 $dd=null;
                 //退到余额
                 if ($refund_type == 0) {
                     $user_money = $v['order_amount'] + $v['user_money'];
                     $sql = "update wxd_users set user_money=user_money+" . $user_money . " where user_id=" . $v['user_id'];
                     $rs1 = Db::execute($sql);
                     if ($rs1) {
                         if ($user_money > 0) {
                             $odata['user_id'] = $v['user_id'];
                             $odata['create_time'] = time();
                             $odata['money'] = $user_money;
                             $odata['remark'] = "退款";
                             $odata['store_id'] = $v['store_id'];
                             $odata['order_sn'] = $v['order_sn'];
                             $odata['status'] = 1;
                             $odata['type'] = 1;
                             M('withdrawals')->save($odata);
                         }
                     } else {
                         mlog($v['order_sn']."退款到余额失败,", 'refund/' . $stoid);
                         $dd['user_money']=$user_money;
                     }

                 } //原路返回
                 else if ($refund_type == 1) {
                     if ($v['order_amount'] > 0) {
                         $ordno = $v['order_sn'];
                         $total_fee = $v['order_amount'];
                         $refund_fee = $total_fee;
                         //$erpid = tpCache('shop_info.ERPId', $stoid);
                         $path = BASE_PATH . 'public/cert/' . $stoid . '/';
                             try {
                                 $rs = $wx->refund2($ordno, $total_fee, $refund_fee, $path,$v['store_id'],null,$v['source_type']);
                             if ($rs['return_code'] == 'FAIL') {
                                 $dd['weixin_err']=$rs['return_msg'];
                                 $dd['weixin']=$v['order_amount'];
                             }
                         } catch (\Exception $e) {
                                 mlog($v['order_sn']."退款签名失败," . $e->getMessage(), 'refund/' . $stoid);
                                 $dd['weixin_err']=$e->getMessage();
                                 $dd['weixin']=$v['order_amount'];
                         }
                     }
                     if ($v['user_money'] > 0) {
                         $user_money = $v['user_money'];
                         $sql = "update wxd_users set user_money=user_money+" . $user_money . " where user_id=" . $v['user_id'];
                         $rs1 = Db::execute($sql);
                         if ($rs1) {
                             if ($user_money > 0) {
                                 $odata['user_id'] = $v['user_id'];
                                 $odata['create_time'] = time();
                                 $odata['money'] = $user_money;
                                 $odata['remark'] = "退款";
                                 $odata['store_id'] = $v['store_id'];
                                 $odata['order_sn'] = $v['order_sn'];
                                 $odata['status'] = 1;
                                 $odata['type'] = 1;
                                 M('withdrawals')->save($odata);
                             }
                         } else {
                             mlog($v['order_sn']."退款到余额失败,", 'refund/' . $stoid);
                             $dd['user_money']=$v['user_money'];
                         }
                     }
                 }
                 if($dd) {
                     $jsontxt=json_encode($dd);
                     M("order")->where('order_id',$v['order_id'])->save(['back_err_json'=>$jsontxt]);
                     $msg="退款失败";
                     if($dd['weixin_err']) $msg=$msg.$dd['weixin_err'];
                     return json(['code'=>-1,'msg'=>$msg]);

                 }else{
                     return json(['code'=>1,'msg'=>'退款成功']);
                 }
             }else{
                 return json(['code'=>-1,'msg'=>'退款失败']);
             }

        }else{
             return json(['code'=>-1,'msg'=>'未找到订单']);
        }
    }

    //拼单失败记录导出
    public function fail_export(){
            $stoid=getAdmStoId();
            $where="1=1";
            $timegap = I('timegap');
            if($timegap){
                $gap = explode('-', $timegap);
                $begin = strtotime($gap[0]);
                $end = strtotime($gap[1]);
            }
            if (I('add_time_begin') && I('add_time_end')) {
                //@new 新后台UI参数
                $begin = strtotime(I('add_time_begin'));
                $end = strtotime(I('add_time_end'));
            }
            if($begin && $end){
                $condition['a.add_time'] = array('between',"$begin,$end");
            }
            $condition['a.store_id']= $stoid;
            $condition['a.order_status']= 3;  //都是拼单失败的单
            $where.=" and a.is_zsorder>1"; //是拼单订单的
            $where.=" and a.pay_time>0";   //有支付的

            $keywords = I('keywords','','trim');
            if($keywords){
                $where.=" and (a.order_sn like '%".$keywords."%' or b.mobile like '%".$keywords."%' or b.nickname like '%".$keywords."%')";
            }

            $team_name=I("team_name");
            if($team_name){$where.=" and (c.title like '%".$team_name."%')";}
            $qh=I("qh");
            if($qh){ $condition['a.pt_listno']= $qh;}
            $money=I("money");
            if($money){ $where.=" and (a.pt_tail_money+a.order_amount+a.user_money)=".$money; }
            $team_type=I("team_type");
            if($team_type){ $where.=" and a.is_zsorder=".($team_type+1); }

            $pay_type=I("pay_type");
            if($pay_type==1){$where.=" and a.order_amount>0";}
            if($pay_type==2){$where.=" and a.user_money>0";}

            $back_status=I('back_status');
            if($back_status==1){
                $where.=" and a.is_zsorder=4 and a.is_back=0";
            }
            if($back_status==2){
                $where.=" and ((a.is_zsorder<4 and a.order_status=3) or a.is_back=1)";
            }

            $count = M('order')->alias('a')
                ->join('(select nickname,mobile,head_pic,user_id from wxd_users where store_id='.$stoid.') b','a.user_id=b.user_id','left')
                ->join('(select id,title,actno from wxd_teamlist where store_id='.$stoid.') c','a.pt_prom_id=c.id','left')
                ->where($condition)->where($where)->count('a.order_id');

            $Page  = new AjaxPage($count,10);
            $sort_order="a.order_id desc";
            //获取订单列表
            $show = $Page->show();
            $start=$Page->firstRow;
            $page_size=$Page->listRows;

            $orderList=  M('order')->alias('a')
                ->join('(select nickname,mobile,head_pic,user_id from wxd_users where store_id='.$stoid.') b','a.user_id=b.user_id','left')
                ->join('(select id,title,actno from wxd_teamlist where store_id='.$stoid.') c','a.pt_prom_id=c.id','left')
                ->where($condition)->where($where)
                ->limit("$start,$page_size")
                ->order($sort_order)
                ->field('a.order_sn,a.add_time,a.order_amount,a.user_money,(a.order_amount+a.user_money+a.pt_tail_money) as buy_num,a.pay_status,a.order_status,a.is_zsorder,a.pt_status,a.pt_listno,a.is_back,b.mobile,b.nickname,b.head_pic,c.title,c.actno')
                ->select();

            foreach ($orderList as $k=>$v){
                $count=M('order_goods')->where('order_sn',$v['order_sn'])->sum('goods_num');
                $orderList[$k]['goods_num']= $count;
            }

            $strTable = '<table  border="1">';
            $strTable .= '<tr style="font-weight: bold;">';
            $strTable .= '<td style="text-align:center;" width="100">会员</td>';
            $strTable .= '<td style="text-align:center;" width="100" >活动名称/编号</td>';
            $strTable .= '<td style="text-align:center;" width="100">团期编号</td>';
            $strTable .= '<td style="text-align:center;" width="100" >订单号/微流水号</td>';
            $strTable .= '<td style="text-align:center;" width="100" >金额/数量</td>';
            $strTable .= '<td style="text-align:center;" width="100" >支付类型</td>';
            $strTable .= '<td style="text-align:center;" width="100" >付款时间</td>';
            $strTable .= '<td style="text-align:center;" width="100" >处理状态</td>';
            $strTable .= '</tr>';
            if (is_array($orderList)) {

                foreach ($orderList as $k => $val) {

                    $strTable .= '<tr>';
                    $strTable .= '<td style="text-align:left;" >' . $val['nickname'] . '<br>'. $val['mobile'].'</td>';
                    $strTable .= '<td style="text-align:left;" >' . $val['title'] . '<br>'. $val['actno'].' </td>';
                    $strTable .= '<td style="text-align:center;" >' . $val['pt_listno'] .  '</td>';
                    $strTable .= '<td style="text-align:center;" >' . $val['order_sn'] . '<br>'. $val['pay_sn'].'</td>';
                    $strTable .= '<td style="text-align:center;" >' . $val['buy_num'] . '<br>('. $val['goods_num'].'件)</td>';
                    $ptye="";
                    if($val['order_amount']>0 && $val['user_money']> 0){
                        $ptye="微支付+余额";
                    }

                    if($val['order_amount']>0 && $val['user_money']<=0){
                        $ptye="微支付";
                    }
                    if($val['order_amount']<=0 && $val['user_money']> 0){
                        $ptye="余额";
                    }
                    $strTable .= '<td style="text-align:center;" >' . $ptye . '</td>';
                    $strTable .= '<td style="text-align:center;" >' . date('Y-m-d H:i:s',$val['add_time']) . '</td>';

                    $dtype="已退款";
                    if($val['is_back']==0 && $val['is_zsorder']==4){
                        $dtype="未支付尾款";
                    }
                    $strTable .= '<td style="text-align:center;" >' . $dtype . '</td>';
                    $strTable .= '</tr>';
                }
            }
            $strTable .= '</table>';
            echo $strTable;
            unset($goodsList);
            downloadExcel($strTable, 'order');
            exit();
    }


    //拼单失败记录导出
    public function export_storecount(){
        $pagenum = 20;//每页显示多少条
        if ((int)I('pagenum/s') > 0) {
            $pagenum = I('pagenum/s');
        }
        $p = I('p', 1);
        $begin = I('add_time_begin');
        $end = I('add_time_end');
        $getisend=I('isend');

        $this->assign('start_time', $begin);
        $this->assign('end_time', $end);

        $flashsaleid = I('teamid');//ID
        $picksle=trim(I('picksle'));
        $pstype=I('picksle_type');

        $where = " a.store_id=" . getAdmStoId();
        $where .= " and  a.prom_type=6 and a.prom_id=" . $flashsaleid;

        if($picksle){
            if($pstype)
                $where .= " AND c.pickup_name='".$picksle."'";
            else
                $where .= " AND c.pickup_no='".$picksle."'";
        }
        if ($begin) {
            $where.=" and b.add_time>=".strtotime($begin);

        }
        if ($end) {
            $where.=" and b.add_time<=".strtotime($end);
        }
        $order_status=I('order_status');

        if($order_status!="")
        {

            switch ($order_status)
            {
                case 12:      //待付款
                    $condition['b.order_status'] = 0;
                    $condition['b.pay_status'] =0;

                    break;
                case 1:      //待发货
                    $condition['b.pay_status'] =1;
                    $condition['b.order_status'] = ['in','0,1'];
                    $condition['b.shipping_status'] =0;
                    break;
                case 11:     //待收货
                    $condition['b.order_status'] = 1;
                    I('shipping_status') != '' ? $condition['b.shipping_status'] = I('shipping_status') : $condition['shipping_status'] = ['in','1,2']; //是否发货


                    break;
                case 2:     //已收货
                    $condition['b.order_status'] = 2;

                    break;
                case 3:      //已取消
                    $condition['b.order_status'] = I('order_status');
                    break;
                case 4:      //已完成
                    $condition['b.order_status'] = I('order_status');

                    break;
                case 5:      //已作废
                    $condition['b.order_status'] = I('order_status');
                    break;
                case 6:      //已作废
                    $condition['b.order_status'] = I('order_status');
                    break;
                case 13:      //已付款
                    $condition['b.pay_status'] =1;
                    break;
            }
        }

        $qdrecord = M('order_goods');

//        $count = $qdrecord->alias('a')
//            ->join('order b',' a.order_id=b.order_id','left')
//            ->join('(select pickup_id,pickup_name,pickup_no from  wxd_pick_up where store_id='.getAdmStoId().') c','c.pickup_id=b.pickup_id','left')
//            ->where($where)
//            ->where($condition)
//            ->count('distinct b.pickup_id');

//        $sumcount = $qdrecord->alias('a')
//            ->join('order b',' a.order_id=b.order_id','left')
//            ->join('(select pickup_id,pickup_name,pickup_no from  wxd_pick_up where store_id='.getAdmStoId().') c','c.pickup_id=b.pickup_id','left')
//            ->where($where)
//            ->where($condition)
//            ->sum('a.goods_num');

        //  $Page = $pager = new Page($count, $pagenum);// 实例化分页类 传入总记录数和每页显示的记录数

        $redmoneylist = $qdrecord->alias('a')
            ->join('order b',' a.order_id=b.order_id','left')
            ->join('(select pickup_id,pickup_name,pickup_no from  wxd_pick_up where store_id='.getAdmStoId().') c','c.pickup_id=b.pickup_id','left')
            ->where($where)
            ->where($condition)
//            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->order('c.pickup_no asc')
            ->field('count(b.order_id) as ordernum,sum(a.goods_num) as warenum,b.pickup_id,c.pickup_name,c.pickup_no,sum(b.total_amount)all_total_amount,sum(order_amount+user_money)all_order_amount')
            ->group('b.pickup_id')
            ->select();// 查询满足要求的总记录数

        $strTable = '<table  border="1">';
        $strTable .= '<tr style="font-weight: bold;">';
        $strTable .= '<td style="text-align:center;" width="100">门店编号</td>';
        $strTable .= '<td style="text-align:center;" width="100" >门店名称</td>';
        $strTable .= '<td style="text-align:center;" width="100">订单数(笔)</td>';
        $strTable .= '<td style="text-align:center;" width="100" >购买总件数(件)</td>';
        $strTable .= '<td style="text-align:center;" width="100" >应收总金额</td>';
        $strTable .= '<td style="text-align:center;" width="100" >实收总金额</td>';
        $strTable .= '</tr>';
        if (is_array($redmoneylist)) {
            foreach ($redmoneylist as $k => $val) {
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:left;" >$nbsp;' .$val['pickup_no'].'</td>';
                $strTable .= '<td style="text-align:left;" >' . $val['pickup_name'] .' </td>';
                $strTable .= '<td style="text-align:center;" >' . $val['ordernum'] .  '</td>';
                $strTable .= '<td style="text-align:center;" >' . $val['warenum'] .'</td>';
                $strTable .= '<td style="text-align:center;" >' . $val['all_total_amount']. '</td>';
                $strTable .= '<td style="text-align:center;" >' . $val['all_order_amount']. '</td>';
                $strTable .= '</tr>';
            }
        }
        $strTable .= '</table>';
        echo $strTable;
        unset($goodsList);
        downloadExcel($strTable, 'order');
        exit();
    }

    //重新再退那些订单退款失败的订单
    public function  back_err_order($od,$back_err_json){
        $uy=M("order")->where('store_id',getAdmStoId())
            ->where('order_id',$od['order_id'])
            ->where("back_err_json<>''")->save(['back_err_json'=>'']);
        if($uy) {
            $v = $od;
            $ddstr = json_decode($back_err_json, true);
            $stoid = $v['store_id'];
            if ($ddstr['weixin']) {
                include_once "plugins/payment/weixin/weixin.class.php";
                $wx = new \weixin();
                $ordno = $v['order_sn'];
                $total_fee = $ddstr['weixin'];
                $refund_fee = $total_fee;
                $path = BASE_PATH . 'public/cert/' . $stoid . '/';
                try {
                    $rs = $wx->refund2($ordno, $total_fee, $refund_fee, $path, $stoid,null,$v['source_type']);
                    if ($rs['return_code'] == 'FAIL') {
                        $dd['weixin_err'] = $rs['return_msg'];
                        $dd['weixin'] = $ddstr['weixin'];
                    }
                } catch (\Exception $e) {
                    mlog($v['order_sn'] . "退款签名失败," . $e->getMessage(), 'refund/' . $stoid);
                    $dd['weixin_err'] = $e->getMessage();
                    $dd['weixin'] = $ddstr['weixin'];
                }
            }

            if ($ddstr['user_money']) {
                $user_money = $ddstr['user_money'];
                $sql = "update wxd_users set user_money=user_money+" . $user_money . " where user_id=" . $v['user_id'];
                $rs1 = Db::execute($sql);
                if ($rs1) {
                    if ($user_money > 0) {
                        $odata['user_id'] = $v['user_id'];
                        $odata['create_time'] = time();
                        $odata['money'] = $user_money;
                        $odata['remark'] = "退款";
                        $odata['store_id'] = $v['store_id'];
                        $odata['order_sn'] = $v['order_sn'];
                        $odata['status'] = 1;
                        $odata['type'] = 1;
                        M('withdrawals')->save($odata);
                    }
                } else {
                    mlog($v['order_sn'] . "退款到余额失败,", 'refund/' . $stoid);
                    $dd['user_money'] = $user_money;
                }
            }
            //如果退款失败要进行记录
            if($dd) {
                M("order")->where('order_id', $v['order_id'])->save(['back_err_json' => json_encode($dd)]);
                $msg="退款失败";
                if($dd['weixin_err']) $msg=$msg.$dd['weixin_err'];
                return json(['code'=>-1,'msg'=>$msg]);
            }else{
                return json(['code'=>1,'msg'=>"退款成功"]);
            }
        }
    }

    //秒杀历史记录删除按钮
    public function his_pt_buy_del()
    {
        $id = I('del_id');
        if ($id) {
            $data['is_his_end'] = 1;
            $admid = getAdminId();
            $amdinfo = getAdminInfo($admid);
            $data['edit_man'] = $amdinfo['ERPName'];
            $data['edit_time'] = time();
            $data['edit_mark'] = "删除历史团购活动";
            $data['edit_ip'] = getIP();

            M('teamlist')->where("id", $id)->where('store_id',getAdmStoId())->save($data);
            ClearALLCache();
            delFile(TEMP_PATH . "/" . getAdmStoId());
//            upload_ylp_log('团购删除');
            exit(json_encode(1));
        } else {
            exit(json_encode(0));
        }
    }
}