User.php 73.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司,并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: 当燃      
 * Date: 2015-09-09
 */

namespace app\admin\controller;
use think\AjaxPage;
use think\Cache;
use think\Page;
use think\Verify;
use think\Db;
use app\admin\logic\UsersLogic;

class User extends Base {

    public function index(){

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

    /**
     * 会员列表withdrawals
     */
    public function ajaxindex(){
        // 搜索条件
        $condition = array();
        /*--添加会员ID--*/
        $pagenum=20;//每页显示多少条
        if ((int)I('pagenum/s')>0)
        {
            $pagenum=I('pagenum/s');
        }

        $olrurl=U("User/index",$condition);
        $where =" and 1=1 and is_distribut=1";
        I('first_leader') && $where.= ' and a.first_leader='.I('first_leader'); // 查看一级下线人有哪些
        I('second_leader') && $where.= ' and a.second_leader='.I('second_leader'); // 查看一级下线人有哪些
        I('third_leader') && $where.= ' and a.third_leader='.I('third_leader'); // 查看一级下线人有哪些
        I('user_id') && $where.= ' and a.user_id='.I('user_id');
        I('mobile') &&  $where.= ' and a.mobile='.I('mobile');
        I('email') && $where.= ' and a.email='.I('email');

        //$sort_order = I('order_by','user_id').' '.I('sort','desc');
        $sort_order = ' reg_time desc';
        $strsql='select a.user_id,a.mobile,a.nickname,a.reg_time,a.is_distribut,
1 as first_leader_num,
IFNULL(b.c,0) as second_leader_num,
IFNULL(c.c,0) as third_leader_num 
from wxd_users a 
LEFT JOIN (select first_leader,COUNT(1) as c from wxd_users where is_distribut=1 and store_id='.getAdmStoId().' 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 is_distribut=1 and store_id='.getAdmStoId().' group by second_leader ) c on a.user_id=c.second_leader 
where a.is_distribut=1 and a.store_id='.getAdmStoId().$where.' ORDER BY '.$sort_order;

        $sqllist=Db::query($strsql);
        $count = count($sqllist);
        $Page  = new AjaxPage($count,$pagenum);

        //分页实现
        $p=I('p/d');
        $fir=($p-1)*$pagenum;$end=$p*$pagenum;
        $lists2=null;
        if($end>$count){$end=$count; }
        for($i=$fir;$i<$end;$i++){ $lists2[]=$sqllist[$i];}

        $show = $Page->show();
        $this->assign('userList',$lists2);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        $this->assign('olrurl', urlencode($olrurl));

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

    //分销会员导出
    public function exportuser(){
        // 搜索条件

        $where =" and 1=1";
        I('first_leader') && $where.= ' and a.first_leader='.I('first_leader'); // 查看一级下线人有哪些
        I('second_leader') && $where.= ' and a.second_leader='.I('second_leader'); // 查看一级下线人有哪些
        I('third_leader') && $where.= ' and a.third_leader='.I('third_leader'); // 查看一级下线人有哪些
        I('user_id') && $where.= ' and a.user_id='.I('user_id');
        I('mobile') &&  $where.= ' and a.mobile='.I('mobile');
        I('email') && $where.= ' and a.email='.I('email');
        $sort_order = I('order_by','user_id').' '.I('sort','desc');

        $strsql='select a.user_id,a.mobile,a.nickname,a.reg_time,a.is_distribut,
1 as fisrt_leader,
IFNULL(b.c,0) as second_leader,
IFNULL(c.c,0) as third_leader 
from wxd_users a 
LEFT JOIN (select first_leader,COUNT(1) as c from wxd_users where is_distribut=1 and store_id='.getAdmStoId().' 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 is_distribut=1 and store_id='.getAdmStoId().' group by second_leader ) c on a.user_id=c.second_leader 
where a.is_distribut=1 and a.store_id='.getAdmStoId().$where.' ORDER BY '.$sort_order;


        $userList = Db::query($strsql);
//$is_setdistri_first=tpCache('distribut.is_setdistri_first',getAdmStoId());
//        foreach ($userList as $k=>$val){
//                $user_list[$k]['fisrt_leader'] = 1;
//                if($user_list[$k]['is_distribut']!=1){
//                    $user['first_lower'] = 0;
//                }
//                $user_list[$k]['second_leader'] = M('users')
//                    ->where("is_distribut=1")
//                    ->where(array('first_leader'=>$val['user_id'],'store_id'=>getAdmStoId()))->count();
//                $user_list[$k]['third_leader'] = M('users')
//                    ->where("is_distribut=1")
//                    ->where(array('second_leader'=>$val['user_id'],'store_id'=>getAdmStoId()))->count();
//            }


        $strTable ='<table  border="1">';
        $strTable .= '<tr style="font-weight: bold;">';
        $strTable .= '<td style="text-align:center;width:100px;">手机号码</td>';
        $strTable .= '<td style="text-align:center;" width="100">会员昵称</td>';
        $strTable .= '<td style="text-align:center;" width="80">一级下线数</td>';
        $strTable .= '<td style="text-align:center;" width="80">二级下线数</td>';
        $strTable .= '<td style="text-align:center;" width="80">三级下线数</td>';
        $strTable .= '<td style="text-align:center;" width="150">注册日期</td>';
        $strTable .= '</tr>';

        if(is_array($userList)){
            foreach($userList as $k=>$val){
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:center;">&nbsp;'.$val['mobile'].'</td>';
                $strTable .= '<td style="text-align:center;">'.$val['nickname'].' </td>';
                $strTable .= '<td style="text-align:center;">'.($val['fisrt_leader']==''?'0':$val['fisrt_leader']).'</td>';
                $strTable .= '<td style="text-align:center;">'.($val['second_leader']==''?'0':$val['second_leader']).' </td>';
                $strTable .= '<td style="text-align:center;">'.($val['third_leader']==''?'0':$val['third_leader']).'</td>';
                $strTable .= '<td style="text-align:center;">'.date('Y-m-d H:i:s', $val['reg_time']).'</td>';

                $strTable .= '</tr>';
            }
        }
        $strTable .='</table>';
        echo  $strTable;

        unset($userList);
        downloadExcel($strTable,'distributuser');
        exit();

    }
    /**
     * 会员详细信息查看
     */
    public function detail(){
        $uid = I('get.id');
        $url=urldecode(I('get.oldurl'));

        $user = D('users')->where(array('user_id'=>$uid,'is_distribut'=>1))->find();
        if(!$user)
            exit($this->error('该分销会员不存在'));
        if(IS_POST){

            ClearALLCache();
            delFile(TEMP_PATH."/".getAdmStoId());

            //  会员信息编辑
            $password = I('post.password');
            $password2 = I('post.password2');
            if($password != '' && $password != $password2){
                exit($this->error('两次输入密码不同'));
            }
            if($password == '' && $password2 == ''){
                unset($_POST['password']);
            }else{
                $_POST['password'] = encrypt($_POST['password']);
            }

            $_POST["is_lock"]=(int)$_POST["is_lock"];
            $_POST["is_distribut"]=(int)$_POST["is_distribut"];
            $_POST["sex"]=(int)$_POST["sex"];

            $row = M('users')->where(array('user_id'=>$uid))->save($_POST);
            if($row){
                upload_ylp_log('B26分销商编辑/确认提交');
                $this->success('修改成功');
                exit();
            }else{
                $this->error('未作内容修改或修改失败');
                exit();
            }
        }

            $user['first_lower'] = 1;
            if($user['is_distribut']!=1){
                $user['first_lower'] = 0;
            }
            $user['second_lower'] = M('users')
                ->where("is_distribut=1")
                ->where("first_leader = {$user['user_id']}")->count();
            $user['third_lower'] = M('users')
                ->where("is_distribut=1")
                ->where("second_leader = {$user['user_id']}")->count();


        $this->assign('user',$user);
        $this->assign('url',$url);
        return $this->fetch('',getAdmStoId());
    }
    
    public function add_user(){
    	if(IS_POST){
    		$data = I('post.');
			$data['store_id']=getAdmStoId();
			
			$user_obj = new UsersLogic();
			$res = $user_obj->addUser($data,getAdmStoId());
			if($res['status'] == 1){
//			    upload_ylp_log('添加会员');
				$this->success('添加成功',U('User/index'));exit;
			}else{
				$this->error('添加失败,'.$res['msg']);
			}
    	}
    	return $this->fetch('',getAdmStoId());
    }

    /**
     * 用户收货地址查看
     */
    public function address(){
        $uid = I('get.id');
        $url=urldecode(I('get.oldurl'));
        $lists = D('user_address')->where(array('user_id'=>$uid))->select();
        $regionList = M('Region')->getField('id,name');
        $this->assign('regionList',$regionList);
        $this->assign('lists',$lists);
        $this->assign('uid',$uid);
        $this->assign('url',$url);
//        upload_ylp_log('收货地址');
        return $this->fetch('',getAdmStoId());
    }

    /**
     * 删除会员
     */
    public function delete(){
        $uid = I('get.id');
        $row = M('users')->where(array('user_id'=>$uid))->delete();
        if($row){
//            upload_ylp_log('删除会员');
            $this->success('成功删除会员');
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 账户资金记录
     */
    public function account_log(){
        $user_id = I('get.id');
        $url=urldecode(I('get.oldurl'));
        //获取类型
        $type = I('get.type');
        //获取记录总数
        $count = M('account_log')->where(array('user_id'=>$user_id))->count();
        $page = new Page($count);
        $lists  = M('account_log')->where(array('user_id'=>$user_id))->order('change_time desc')->limit($page->firstRow.','.$page->listRows)->select();

        $this->assign('user_id',$user_id);
        $this->assign('page',$page->show());
        $this->assign('lists',$lists);
        $this->assign('url',$url);
        return $this->fetch('',getAdmStoId());
    }

    /**
     * 账户资金调节
     */
    public function account_edit(){
        $user_id = I('get.id');
        $url=urldecode(I('get.oldurl'));
        if(!$user_id > 0)
            $this->error("参数有误");
        if(IS_POST){
            //获取操作类型
            $m_op_type = I('post.money_act_type');
            $user_money = I('post.user_money');
            $user_money =  $m_op_type ? $user_money : 0-$user_money;

            $p_op_type = I('post.point_act_type');
            $pay_points = I('post.pay_points');
            $pay_points =  $p_op_type ? $pay_points : 0-$pay_points;

            $f_op_type = I('post.frozen_act_type');
            $frozen_money = I('post.frozen_money');
            $frozen_money =  $f_op_type ? $frozen_money : 0-$frozen_money;

            $desc = I('post.desc');
            if(!$desc)
                $this->error("请填写操作说明");
            if(accountLog($user_id,$user_money,$pay_points,$desc)){
                $this->success("操作成功",U("Admin/User/account_log",array('id'=>$user_id)));
            }else{
                $this->error("操作失败");
            }
            exit;
        }
        $this->assign('user_id',$user_id);
        $this->assign('url',$url);
        return $this->fetch('',getAdmStoId());
    }

    /**
     *退款,退货
     */
    public function account_edit_return(){
        $return_id=I('return_id');
        /*--查找退货信息--*/
        $rs=M('return_goods')->alias('a')
            ->join('order_goods b','a.order_id=b.order_id and a.goods_id=b.goods_id','left')
            ->where('id',$return_id)
            ->where('status<>2 and status<>3')//完成和拒绝不参与退款
            ->where('type<>1')//换货不参与退款
            ->field('a.*,b.member_goods_price,b.goods_num')
            ->find();

        $ord=M("order")->where("order_id",$rs['order_id'])->find();
        $orgoods=M("order_goods")->where("order_id",$rs['order_id'])->select();

        /*---当是整单退款,当订单商品只有一件,当是积分购买的时候---*/
        if(!empty($rs['goods_id_list']) || count($orgoods)<2 || !empty($ord['integral'])){
            $MaxB=$ord['order_amount']+$ord['user_money'];
        }else{
            $MaxB=$rs['member_goods_price']*$rs['goods_num'];
        }
        $this->assign('MaxB', $MaxB);
        if(!empty($ord['integral'])){
            $this->assign('integral', $ord['integral']);
        }

        if($rs) {
            $this->assign('type', $rs['type']);//退款类型判断
            $user_id=$rs['user_id'];
            if ($user_id <=0)
                $this->error("参数有误");
            if (IS_POST) {
                //获取操作类型
                $user_money = I('user_money');
                $integral = I('integral/d',0);
                $desc = I('post.desc');

                if (!$desc)
                    $this->error("请填写操作说明");

                if(!empty($user_money)) {
                    if ($user_money > $MaxB) {
                        $this->error("退款金额大于支付金额");
                    }
                    $sql = "update wxd_users set user_money=user_money+" . $user_money . " where user_id=" . $user_id;
                    $rs1 = Db::execute($sql);
                    if($rs1) {
                        if ($user_money > 0) {
                            $odata['user_id'] = $rs['user_id'];
                            $odata['create_time'] = time();
                            $odata['money'] = $user_money;
                            $odata['remark'] = "退款";
                            $odata['store_id'] = getAdmStoId();
                            $odata['order_sn'] = $rs['order_sn'];
                            $odata['status'] = 1;
                            $odata['type'] = 1;
                            M('withdrawals')->save($odata);
                        }
                    }else{
                        $this->error("操作失败");
                        exit;
                    }
                }

                /*---调用线下接口增加积分---*/
                if(!empty($integral)){

                    $user = M("users")->where('user_id',$rs['user_id'])->field('erpvipid')->find();
                    /*---$user['api_token']=tpCache('shop_info.api_token',$rs['store_id']);
                   $vipid = $user['erpvipid'];
                   $data=['Id'=> $vipid,
                       'Integral'=>$integral,
                       'Remark'=>"退款返回积分",
                   ];
                   $res=getApiData("wxd.vip.addreduce",$user['api_token'],array($data));
                   $res=json_decode($res,true);
                   mlog($rs['user_id']. $res[0].'积分退款', 'Integral');--*/

                   $accdb=tpCache("shop_info.ERPId",$user['store_id']);
                   com_update_integral($accdb,$user,$integral,"退款返回积分",$module="会员中心",$rs['order_sn']."_tui");
                }
                /* 插入帐户变动记录 */
                $account_log = array(
                    'user_id' => $user_id,
                    'user_money' => $user_money,
                    'pay_points' => 0,
                    'change_time' => time(),
                    'desc' => $desc,
                    'store_id' => $rs['store_id'],
                    'integral' => $integral,
                );
                M('account_log')->add($account_log);
                /* 退货单的修改 */
                $data1['status']=2;
                $data1['back_money']=$user_money;
                if(!empty($integral)){
                    $data1['back_integral']=$integral;
                }
                if(empty($rs['handle_time']))
                    $data1['handle_time']= time();

                $data1['ok_time']= time();
                $aa=M('return_goods')->where('id',$return_id)->save($data1);
                $dd=null;
                switch ($rs['type']){
                    case 0://退货
                        $dd=['is_send'=>3];
                        break;
                    case 1://换货
                        $dd=['is_send'=>2];
                        break;
                    case 2://退款
                        $dd=['is_send'=>4];
                        break;
                }
                /*订单商品的修改*/
                M('order_goods')
                    ->where('order_id',$rs['order_id'])
                    ->where('goods_id',$rs['goods_id'])
                    ->save($dd);

                $rule=tpCache('basic.sales_rules',getAdmStoId());
                $ord_g=M("order_goods")->where('order_id',$rs['order_id'])->field('is_send,goods_id,goods_num,goods_price')->select();
                /*---当一单里面有多个商品的时候,且不是整单退款---*/
                if(count($ord_g)>1){
                    if(empty($rs['goods_id_list'])) {//且不是整单退款
                        $ucut = 0;//余额减量
                        $ocut = 0;//应付减量

                        $ucut = $ord['user_money'] > $user_money ? $user_money : $ord['user_money'];
                        if ($user_money > $ord['user_money']) {
                            $ocut = round($user_money - $ord['user_money'], 2);
                        }

                        $sql = "update wxd_order set order_amount=order_amount-" . $ocut . ",goods_price=goods_price-" . $user_money . ",total_amount=total_amount-" . $user_money . ",user_money=user_money-" . $ucut . "  where order_id=" . $rs['order_id'];
                        $rs1 = Db::execute($sql);

                        /*--判断商品里面所有的商品是否都退款--*/
                        $isallreturn=1;
                        foreach($ord_g as $kl=>$vl){
                           if($vl['is_send']<2){
                               $isallreturn=0;
                           } else{
                               M('Goods')->where('goods_id', $vl['goods_id'])->setDec('sales_sum', $vl['goods_num']); // 减少商品销售量
                               if ($rule==1){
                                   //M('Goods')->where('goods_id', $vl['goods_id'])->setDec('sales_sum', $vl['goods_num']); // 减少商品销售量
                                   M('Goods')->where('goods_id', $vl['goods_id'])->setInc('store_count', $vl['goods_num']); // 增加商品库存
                               }
                           }
                        }
                        if($isallreturn==1){
                            $orddata1=['order_status'=>6];
                            M("order")->where('order_id',$rs['order_id'])->save($orddata1);
                        }
                    }else{
                        $orddata1=['order_status'=>6];
                        M("order")->where('order_id',$rs['order_id'])->save($orddata1);
                        foreach ($ord_g as $kk=>$vv){
                            M('Goods')->where('goods_id', $vv['goods_id'])->setDec('sales_sum', $vv['goods_num']); // 减少商品销售量
                            if ($rule==1 && $vv['goods_price']>0){
                                M('Goods')->where('goods_id', $vv['goods_id'])->setInc('store_count', $vv['goods_num']);
                            }
                            if ($vv['goods_price'] == 0) {//增加赠品库存
                                M('Gift')->where(['goods_id'=>$vv['goods_id'],'is_end'=>0])->setInc('goods_num', $vv['goods_num']);
                                M('gift_receive')->where(['id'=>['in',$ord['gift_receive_id']]])->delete();
                            }

                        }
                    }
                }else{
                    $orddata=['order_status'=>6];
                    if ($rule==1){
                        M('Goods')->where('goods_id', $ord_g[0]['goods_id'])->setInc('store_count', $ord_g[0]['goods_num']); // 增加商品库存
                    }
                    M('Goods')->where('goods_id', $ord_g[0]['goods_id'])->setDec('sales_sum', $ord_g[0]['goods_num']); // 减少商品销售量
                    M("order")->where('order_id',$rs['order_id'])->save($orddata);
                }


//                upload_ylp_log('退款');
                $this->success("操作成功", U("Admin/order/return_info", array('id' => $return_id)));
                exit;
            }

            $url="";
            $this->assign('user_id', $user_id);
            $this->assign('return_id', $return_id);
            $this->assign('url', $url);

        }
        return $this->fetch('',getAdmStoId());
    }
    
    public function recharge(){
    	$timegap = I('timegap');
    	$nickname = I('nickname');
    	$map = array();
    	/*--添加查询字段--*/
    	$map["store_id"]=getAdmStoId();
    	if($timegap){
    		$gap = explode(' - ', $timegap);
    		$begin = $gap[0];
    		$end = $gap[1];
    		$map['ctime'] = array('between',array(strtotime($begin),strtotime($end)));
    	}
    	if($nickname){
    		$map['nickname'] = array('like',"%$nickname%");
    	}  	
    	$count = M('recharge')->where($map)->count();
    	$page = new Page($count);
    	$lists  = M('recharge')->where($map)->order('ctime desc')->limit($page->firstRow.','.$page->listRows)->select();
    	$this->assign('page',$page->show());
        $this->assign('pager',$page);
    	$this->assign('lists',$lists);
    	return $this->fetch('',getAdmStoId());
    }

    /*--添加修改等级--*/
    public function level(){
    	$act = I('GET.act','add');
    	$this->assign('act',$act);
    	$level_id = I('GET.level_id');
    	$level_info = array();
    	if($level_id){
    		$level_info = D('user_level')->where('level_id='.$level_id)->find();
    		$this->assign('info',$level_info);
    	}
    	return $this->fetch('',getAdmStoId());
    }

    /*---等级列表---*/
    public function levelList(){
    	$Ad =  M('user_level');
        $p = $this->request->param('p');
    	$res = $Ad->where('1=1 '.getStoWhere())->order('level_id')->page($p.',10')->select();
    	if($res){
    		foreach ($res as $val){
    			$list[] = $val;
    		}
    	}
    	$this->assign('list',$list);
    	$count = $Ad->where('1=1 '.getStoWhere())->count();
    	$Page = new Page($count,10);
    	$show = $Page->show();
    	$this->assign('page',$show);
    	return $this->fetch('',getAdmStoId());
    }
    /*---等级处理---*/
    public function levelHandle(){
    	$data = I('post.');
    	if($data['act'] == 'add'){
            $data["store_id"]=getAdmStoId();
    		$r = D('user_level')->add($data);
    	}
    	if($data['act'] == 'edit'){
            unset($data['act']);
            $q=D('user_level')->where('level_id='.$data['level_id'])->where($data)->find();
            if($q){
                $this->error("未做修改",U('Admin/User/levelList'));
                exit;
            }
    		$r = D('user_level')->where('level_id='.$data['level_id'])->save($data);
    	}
    	 
    	if($data['act'] == 'del'){
    		$r = D('user_level')->where('level_id='.$data['level_id'])->delete();
    		if($r) exit(json_encode(1));
    	}
    	 
    	if($r){
    		$this->success("操作成功",U('Admin/User/levelList'));
    	}else{
    		$this->error("操作失败",U('Admin/User/levelList'));
    	}
    }

    /**
     * 搜索用户名
     */
    public function search_user()
    {
        $search_key = trim(I('search_key'));        
        if(strstr($search_key,'@'))    
        {
            $list = M('users')->where(" email like '%$search_key%' ")->select();        
            foreach($list as $key => $val)
            {
                echo "<option value='{$val['user_id']}'>{$val['email']}</option>";
            }                        
        }
        else
        {
            $list = M('users')->where(" mobile like '%$search_key%' ")->select();        
            foreach($list as $key => $val)
            {
                echo "<option value='{$val['user_id']}'>{$val['mobile']}</option>";
            }            
        } 
        exit;
    }
    
    /**
     * 分销树状关系
     */
    public function ajax_distribut_tree()
    {
          $list = M('users')->where("first_leader = 1")->select();
          return $this->fetch('',getAdmStoId());
    }

    /**
     *
     * @time 2016/08/31
     * @author dyr
     * 发送站内信
     */
    public function sendMessage()
    {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $users = M('users')->field('user_id,nickname')->where(array('user_id' => array('IN', $user_id_array)))->select();
        }
        $this->assign('users',$users);
        return $this->fetch('',getAdmStoId());
    }

    /**
     * 发送系统消息
     * @author dyr
     * @time  2016/09/01
     */
    public function doSendMessage()
    {
        $call_back = I('call_back');//回调方法
        $text= I('post.text');//内容
        $type = I('post.type', 0);//个体or全体
        $admin_id = getAdminId();
        $users = I('post.user/a');//个体id
        $message = array(
            'admin_id' => $admin_id,
            'store_id' => getAdmStoId(),
            'message' => $text,
            'category' => 0,
            'send_time' => time()
        );

        if ($type == 1) {
            //全体用户系统消息
            $message['type'] = 1;
            M('Message')->add($message);
        } else {
            //个体消息
            $message['type'] = 0;
            if (!empty($users)) {
                $create_message_id = M('Message')->add($message);
                foreach ($users as $key) {
                    M('user_message')->add(array('user_id' => $key, 'message_id' => $create_message_id, 'status' => 0, 'category' => 0));
                }
            }
        }
        echo "<script>parent.{$call_back}(1);</script>";
        exit();
    }

    /**
     *
     * @time 2016/09/03
     * @author dyr
     * 发送邮件
     */
    public function sendMail()
    {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $user_where = array(
                'user_id' => array('IN', $user_id_array),
                'email' => array('neq', '')
            );
            $users = M('users')->field('user_id,nickname,email')->where($user_where)->select();
        }
        $this->assign('smtp', tpCache('smtp',getAdmStoId()));
        $this->assign('users', $users);
        return $this->fetch('',getAdmStoId());
    }

    /**
     * 发送邮箱
     * @author dyr
     * @time  2016/09/03
     */
    public function doSendMail()
    {
        $call_back = I('call_back');//回调方法
        $message = I('post.text');//内容
        $title = I('post.title');//标题
        $users = I('post.user/a');
        if (!empty($users)) {
            $user_id_array = implode(',', $users);
            $users = M('users')->field('email')->where(array('user_id' => array('IN', $user_id_array)))->select();
            $to = array();
            foreach ($users as $user) {
                if (check_email($user['email'])) {
                    $to[] = $user['email'];
                }
            }
            $res = send_email($to, $title, $message);
            echo "<script>parent.{$call_back}({$res});</script>";
            exit();
        }
    }

    /**
     * 提现申请记录
     */
    public function withdrawals()
    {
        $pagenum=20;//每页显示多少条
        if ((int)I('pagenum/s')>0)
        {
            $pagenum=I('pagenum/s');
        }
        $_GET = array_merge($_GET,$_POST);
        //unset($_GET['create_time']);

        $status =  trim(I('status'));
        $user_mob = trim(I('mobile'));
        $account_bank = trim(I('account_bank'));
        $account_name = trim(I('account_name'));
        $stime = trim(I('stime'));
        $endtime= trim(I('endtime'));


        $where='a.store_id='.getAdmStoId().' and  type=0';
        $stime && $where .= "  and a.create_time >=".strtotime($stime);
        $endtime && $where.= " and a.create_time <=".strtotime($endtime);

        $this->assign('add_time_begin',$stime);
        $this->assign('add_time_end',$endtime);

        if($status === '0' || $status > 0) {
            $where .= " and a.status = $status ";
        }
        else
        {
            $status=-1;
        }
        $user_mob && $where .= " and b.mobile = $user_mob ";
        $account_bank && $where .= " and a.account_bank like '%$account_bank%' ";
        $account_name && $where .= " and a.account_name like '%$account_name%' ";

        $count = M("withdrawals")->alias('a')->join('users b','a.user_id=b.user_id','left')->field('a.*,b.mobile')
               ->where($where)->count();
        $Page = new Page($count,$pagenum);
        $list = M("withdrawals")->alias('a')->join('users b','a.user_id=b.user_id','left')->field('a.*,b.mobile')
             ->where($where)->order("a.id desc")->limit($Page->firstRow.','.$Page->listRows)->select();

//        $this->assign('create_time',$create_time);
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('status',$status);

        $this->assign('page',$show);
        $this->assign('pager',$Page);
        $this->assign('list',$list);
        $this->assign('pagenum',$pagenum);
        $this->assign('oldurl',urlencode(curPageURL()));
        C('TOKEN_ON',false);
        upload_ylp_log('B18提现申请查询/搜索');
        return $this->fetch('',getAdmStoId());
    }

    /**
     * 提现申请记录数据导出
     */
    public function exportwithdrawals()
    {
        $pagenum=20;//每页显示多少条
        if ((int)I('pagenum/s')>0)
        {
            $pagenum=I('pagenum/s');
        }
        $_GET = array_merge($_GET,$_POST);
        //unset($_GET['create_time']);

        $status =  trim(I('status'));
        $user_mob = trim(I('mobile'));
        $account_bank = trim(I('account_bank'));
        $account_name = trim(I('account_name'));
        $stime = trim(I('stime'));
        $endtime= trim(I('endtime'));


        $where='a.store_id='.getAdmStoId().' and  type=0';
        $stime && $where .= "  and a.create_time >=".strtotime($stime);
        $endtime && $where.= " and a.create_time <=".strtotime($endtime);

        $this->assign('add_time_begin',$stime);
        $this->assign('add_time_end',$endtime);

        if($status === '0' || $status > 0) {
            $where .= " and a.status = $status ";
        }
        else
        {
            $status=-1;
        }
        $user_mob && $where .= " and b.mobile = $user_mob ";
        $account_bank && $where .= " and a.account_bank like '%$account_bank%' ";
        $account_name && $where .= " and a.account_name like '%$account_name%' ";


        $list = M("withdrawals")->alias('a')->join('users b','a.user_id=b.user_id')->field('a.*,b.mobile')
            ->where($where)->order("a.id desc")->select();

        $strTable ='<table  border="1">';
        $strTable .= '<tr style="font-weight: bold;">';
        $strTable .= '<td style="text-align:center;width:100px;">申请单号</td>';
        $strTable .= '<td style="text-align:center;width:100px;">用户手机</td>';
        $strTable .= '<td style="text-align:center;" width="140">申请时间</td>';
        $strTable .= '<td style="text-align:center;" width="80">申请金额</td>';
        $strTable .= '<td style="text-align:center;" width="120">银行名称</td>';
        $strTable .= '<td style="text-align:center;" width="120">银行账号</td>';
        $strTable .= '<td style="text-align:center;" width="80">银行账户</td>';
        $strTable .= '<td style="text-align:center;" width="80">状态</td>';
        $strTable .= '</tr>';
        if(is_array($list)){

            foreach($list as $k=>$val){
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:left;">'.$val['order_sn'].'</td>';
                $strTable .= '<td style="text-align:left;">'.$val['mobile'].'</td>';
                $strTable .= '<td style="text-align:center;">'.date('Y-m-d H:i:s',$val['create_time']).'</td>';
                $strTable .= '<td style="text-align:center;">&yen;'.$val['money'].'</td>';
                $strTable .= '<td style="text-align:left;">'.$val['bank_name'].' </td>';
                $strTable .= '<td style="text-align:center;">'.$val['account_bank'].' </td>';
                $strTable .= '<td style="text-align:center;">'.$val['account_name'].'</td>';
                $strTable .= '<td style="text-align:center;">'.($val['status']=='0'?'申请中':$val['status']=='1'?'申请成功':'申请失败').'</td>';

                $strTable .= '</tr>';
            }
        }
        $strTable .='</table>';
        echo  $strTable;
        unset($list);
        downloadExcel($strTable,'withdrawals');
        exit();


    }
    /**
     * 删除申请记录
     */
    public function delWithdrawals()
    {

        ClearALLCache();
        delFile(TEMP_PATH."/".getAdmStoId());
        $getid=$_GET['id'];
        if (empty($getid))
        {
            $return_arr = array('status' => -1,'msg' => '删除失败,请选择要删除的记录','data'  =>'',);
            $this->ajaxReturn($return_arr);
        }
        $model = M("withdrawals");
        $findinfo=$model->where(array('store_id'=>getAdmStoId(),'id'=>$getid,'status'=>array('neq',1)))->find();
        if (empty($findinfo))
        {
            $return_arr = array('status' => -1,'msg' => '删除失败,记录不存在或记录不可删除','data'  =>'');
            $this->ajaxReturn($return_arr);
        }
        $model->where('id ='.$findinfo['id'])->delete();
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
        $this->ajaxReturn($return_arr);
    }

    /**
     * 修改编辑 申请提现
     */
    public function editWithdrawals()
    {
        ClearALLCache();
        delFile(TEMP_PATH."/".getAdmStoId());
        $id = I('id');
        $url=I('oldurl');
        $withdrawals = DB::name('withdrawals')->where('id',$id)->find();
        $user = M('users')->where("user_id = {$withdrawals[user_id]}")->find();

        if (IS_POST) {
            $data = I('post.');
            // 如果是已经给用户转账 则生成转账流水记录
            if ($data['status'] == 1 && $withdrawals['status'] != 1) {
                if($user['user_money'] < $withdrawals['money']) {
                    $this->error("用户余额不足{$withdrawals['money']},不够提现");
                    exit;
                }

                //$rs=accountLog($withdrawals['user_id'], ($withdrawals['money'] * -1), 0, "平台提现");
                //if(!$rs) $this->error("提现失败");
                //exit;

                //启动事务
                Db::startTrans();
                try {
                    $user_money= ($withdrawals['money'] * -1);
                    $user_id=$withdrawals['user_id'];

                    /* 插入帐户变动记录 */
                    $account_log = array(
                        'user_id' => $user_id,
                        'user_money' => $user_money,
                        'pay_points' => 0,
                        'change_time' => time(),
                        'desc' => "平台提现",
                        'store_id' => getAdmStoId()
                    );
                    //先插入日志
                    M('account_log')->add($account_log);
                    /* 更新用户信息 */
                    $sql = "UPDATE __PREFIX__users SET user_money = user_money + "
                        .$user_money." WHERE user_id =" .$user_id;
                    DB::execute($sql);

                    $remittance = array(
                        'user_id' => $withdrawals['user_id'],
                        'bank_name' => $withdrawals['bank_name'],
                        'account_bank' => $withdrawals['account_bank'],
                        'account_name' => $withdrawals['account_name'],
                        'money' => $withdrawals['money'],
                        'status' => 1,
                        'create_time' => time(),
                        'admin_id' => session('admin_id'),
                        'withdrawals_id' => $withdrawals['id'],
                        'remark' => $data['remark'],
                        'store_id' => getAdmStoId()
                    );
                    M('remittance')->add($remittance);

                    //如果是退款到微信余额
                    if ($withdrawals['bank_type']==2) {
                        //以下是拼单退款处理
                        include_once "plugins/payment/weixin/wx_tx_class.php";
                        $wx = new \wx_tx();
                        $path = $path = BASE_PATH . 'public/cert/' . getAdmStoId() . '/';
                        $no = 'tx' . time() . rand(10000, 99999);
                        //$ordno,$openid,$money,$name,$path,$stoid
                        $rs = $wx->tixian($no, $user['openid'], $withdrawals['money'],
                            $withdrawals['account_name'], $path, getAdmStoId(), $withdrawals['source_type']);

                        $return_code = $rs['return_code'];
                        $result_code = $rs['result_code'];
                        if ($return_code != 'SUCCESS' || $result_code != 'SUCCESS') {
                            $returnmsg = $rs['err_code_des'];
                            //$this->error("提现失败,".$returnmsg);
                            mlog("提现失败,t_id" . $withdrawals['id'] . "-" . $withdrawals['money'].$returnmsg,
                                "editWithdrawals/" . getAdmStoId());
                            //$this->error("提现失败,".$returnmsg);
                            //exit;
                            throw new \think\Exception($returnmsg, 10006);
                        }
                    }


                    DB::name('withdrawals')->update($data);
                    Db::commit();

                }
                catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error("提现失败".$e->getMessage());
                }

                $this->success("操作成功!", U('Admin/User/withdrawals'), 3);
                exit;
            }
            //upload_ylp_log('申请提现');
            $this->success("操作成功!", U('Admin/User/withdrawals'), 3);
            exit;
        }

        if ($user['nickname'])
            $withdrawals['user_name'] = $user['nickname'];
        elseif ($user['email'])
            $withdrawals['user_name'] = $user['email'];
        elseif ($user['mobile'])
            $withdrawals['user_name'] = $user['mobile'];
        $this->assign('user', $user);
        $this->assign('data', $withdrawals);
        return $this->fetch('',getAdmStoId());
    }

    public function withdrawals_update(){

        ClearALLCache();
        delFile(TEMP_PATH."/".getAdmStoId());

        $id = I('id/a');
        $status = I('status');
        $withdrawals = M('withdrawals')->where(array('store_id'=>getAdmStoId(),'status'=>0))->where('id','in', $id)->select();
        $r=null;
        if($status == 1){
            foreach($withdrawals as $v){
                $user = M('users')->where('user_id', $v['user_id'])->find();
                if ($v['status'] != 1) {
                    if ($user['user_money'] < $v['money']) {
                        $this->ajaxReturn(array('status' => 0, 'msg' => $v['order_sn']."提现失败,用户余额不足"), 'JSON');
                        exit;
                    }
                    //如果是退款到微信余额
                    if($v['bank_type']==2){
                        if($v['money']<1){
                            $this->ajaxReturn(array('status' => 0, 'msg' => $v['order_sn']."提现失败,提现金额不能小于1"), 'JSON');
                            exit;
                        }
                        //以下是拼单退款处理
                        include_once "plugins/payment/weixin/wx_tx_class.php";
                        $wx=new \wx_tx();
                        $path=$path = BASE_PATH . 'public/cert/'.getAdmStoId().'/';
                        $no='tx'.time().rand(10000, 99999);
                        //$ordno,$openid,$money,$name,$path,$stoid
                        $rs= $wx->tixian($no,$user['openid'],$v['money'],
                            $v['account_name'],$path,getAdmStoId());
                        $return_code = $rs['return_code'];
                        $result_code = $rs['result_code'];
                        if ($return_code != 'SUCCESS' || $result_code != 'SUCCESS') {
                            $returnmsg = $rs['err_code_des'];
                            $this->ajaxReturn(array('status' => 0, 'msg' =>$v['order_sn']."提现到微信余额失败,". $returnmsg), 'JSON');
                            exit;
                        }
                    }

                    accountLog($v['user_id'], ($v['money'] * -1), 0, "平台提现");
                    $remittance = array(
                        'user_id' => $v['user_id'],
                        'bank_name' => $v['bank_name'],
                        'account_bank' => $v['account_bank'],
                        'account_name' => $v['account_name'],
                        'money' => $v['money'],
                        'status' => 1,
                        'create_time' => time(),
                        'admin_id' => session('admin_id'),
                        'withdrawals_id' => $v['id'],
                        'remark' => "批量提现",
                        'store_id' => getAdmStoId()
                    );
                    M('remittance')->add($remittance);
                    $r = M('withdrawals')->where(array('store_id'=>getAdmStoId(),'status'=>0))->where('id', $v['id'])->save(array('status'=>$status,'check_time'=>time()));
                }
            }
//            upload_ylp_log('通过申请提现');

        }else if($status == 2){
//            upload_ylp_log('拒绝申请提现');
            $r = M('withdrawals')->where(array('store_id'=>getAdmStoId(),'status'=>0))->where('id','in', $id)->save(array('status'=>$status,'refuse_time'=>time()));
        }else if($status == 3) {
//            upload_ylp_log('删除提现记录');
            $r = M('withdrawals')->where(array('store_id'=>getAdmStoId(),'status'=>array('neq',1)))->where('id', 'in', $id)->delete();
        }
        if($r){
            $this->ajaxReturn(array('status'=>1,'msg'=>"操作成功"),'JSON');
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>"操作失败"),'JSON');
        }
    }

    /*--批量转账--*/
    public function transfer($atype,$data){

        ClearALLCache();
        delFile(TEMP_PATH."/".getAdmStoId());

        if($atype == 'weixin'){
            include_once  PLUGIN_PATH."payment/weixin/weixin.class.php";
            $wxpay_obj = new \weixin();
            return $wxpay_obj->transfer($data);
        }else{
            //支付宝在线批量付款
            include_once  PLUGIN_PATH."payment/alipay/alipay.class.php";
            $alipay_obj = new \alipay();
            return $alipay_obj->transfer($data);
        }
    }
    /**
     *  转账汇款记录
     */
    public function remittance(){

        $_GET = array_merge($_GET,$_POST);
        unset($_GET['create_time']);
        $pagenum=20;//每页显示多少条
        if ((int)I('pagenum/s')>0)
        {
            $pagenum=I('pagenum/s');
        }

        $user_mob = trim(I('mobile'));
        $account_bank = trim(I('account_bank'));
        $account_name = trim(I('account_name'));
        $stime = trim(I('stime'));
        $endtime= trim(I('endtime'));

        $where='a.store_id='.getAdmStoId().' ';
        $stime && $where .= "  and a.create_time >=".strtotime($stime);
        $endtime && $where.= " and a.create_time <=".strtotime($endtime);

        $this->assign('add_time_begin',urldecode($stime));
        $this->assign('add_time_end',urldecode($endtime));
        $user_mob && $where .= " and b.mobile = $user_mob ";
        $account_bank && $where .= " and a.account_bank like '%$account_bank%' ";
        $account_name && $where .= " and a.account_name like '%$account_name%' ";

        $count = M("remittance")->alias('a')->join('users b','a.user_id=b.user_id')->field('a.*,b.mobile')->where($where)->count();
        $Page  = new Page($count,$pagenum);
        $list = M("remittance")->alias('a')->join('users b','a.user_id=b.user_id')->field('a.*,b.mobile')
              ->where($where)->order("`id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('pager',$Page);
        //$this->assign('create_time',$create_time);
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('list',$list);
        $this->assign('pagenum',$pagenum);
        $this->assign('oldurl',urlencode(curPageURL()));
        C('TOKEN_ON',false);
        upload_ylp_log('B19汇款记录查询/搜索');
        return $this->fetch('',getAdmStoId());
    }


    /**
     *  转账汇款记录数据导出
     */
    public function exportremittance(){
        $_GET = array_merge($_GET,$_POST);
        unset($_GET['create_time']);
        $pagenum=20;//每页显示多少条
        if ((int)I('pagenum/s')>0)
        {
           $pagenum=I('pagenum/s');
        }

        $user_mob = trim(I('mobile'));
        $account_bank = trim(I('account_bank'));
        $account_name = trim(I('account_name'));
        $stime = trim(I('stime'));
        $endtime= trim(I('endtime'));
        $where='a.store_id='.getAdmStoId().' ';
        $stime && $where .= "  and a.create_time >=".strtotime($stime);
        $endtime && $where.= " and a.create_time <=".strtotime($endtime);

        $this->assign('add_time_begin',urldecode($stime));
        $this->assign('add_time_end',urldecode($endtime));
        $user_mob && $where .= " and b.mobile = $user_mob ";
        $account_bank && $where .= " and a.account_bank like '%$account_bank%' ";
        $account_name && $where .= " and a.account_name like '%$account_name%' ";

        $list = M("remittance")->alias('a')->join('users b','a.user_id=b.user_id')->field('a.*,b.mobile')
            ->where($where)->order("`id` desc")->select();
        $strTable ='<table  border="1">';
        $strTable .= '<tr style="font-weight: bold;">';
        $strTable .= '<td style="text-align:center;width:100px;">用户手机</td>';
        $strTable .= '<td style="text-align:center;" width="120">银行名称</td>';
        $strTable .= '<td style="text-align:center;" width="120">银行账号</td>';
        $strTable .= '<td style="text-align:center;" width="80">申请金额</td>';
        $strTable .= '<td style="text-align:center;" width="50">状态</td>';
        $strTable .= '<td style="text-align:center;" width="140">操作时间</td>';
        $strTable .= '<td style="text-align:center;" width="80">备注</td>';
        $strTable .= '</tr>';
        if(is_array($list)){
            foreach($list as $k=>$val){
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:left;">'.$val['mobile'].'</td>';
                $strTable .= '<td style="text-align:left;">'.$val['bank_name'].' </td>';
                $strTable .= '<td style="text-align:center;">'.$val['account_bank'].' </td>';
                $strTable .= '<td style="text-align:center;">&yen;'.$val['money'].'</td>';
                $strTable .= '<td style="text-align:center;">已处理</td>';
                $strTable .= '<td style="text-align:center;">'.date('Y-m-d H:i:s',$val['create_time']).'</td>';
                $strTable .= '<td style="text-align:center;">'.$val['remark'].'</td>';

                $strTable .= '</tr>';
            }
        }
        $strTable .='</table>';
        echo  $strTable;
        unset($list);
        downloadExcel($strTable,'emittance');
        exit();

    }

    //  ajax退款
    public function return_money()
    {
        $return_id = I('id/d');
        //1手工退款  2自动退到零钱
        $return_type = I('return_type',1);

        $rg = M('return_goods')->alias('a')->join('order b','a.order_id=b.order_id and b.is_bedistri=0 and b.pay_status=1 and b.order_status=1')->where('a.id', $return_id)->where('a.type<>1')
            ->field('a.*,b.user_money,b.coupon_no,b.order_amount,
                  b.tail_pay_type,b.pt_tail_money,b.is_zsorder,b.exp_type,b.order_sn,b.parent_sn,b.pt_pay_sn,b.source_type')->find();

        if (empty($rg)) return json(['code' => 0, 'msg' => '没有此单']);

        //season 2018-09-30  退款加ERP有没有销售单
        $pm_erpid=getERPId();
        if ($pm_erpid ) {
            $order_sn=$rg['order_sn'];
            if ($rg['goods_id'])
            {
                $getgoods_id=$rg['goods_id'];
            }
            else
            {
                $getgoods_id1=explode(',',$rg['goods_id_list']);
                $getgoods_id=$getgoods_id1[0];
            }
            $goodsinfo=M('goods')->where(array('store_id'=>getAdmStoId(),'goods_id'=>$getgoods_id))->field('goods_sn')->find();

            //判断是不是物流订单,是物流订单不判断
            $rs_wu= M('order')->where(array('store_id'=>getAdmStoId(),'order_sn'=>$order_sn))
                ->field('exp_type')->find();

            if ($goodsinfo && $rs_wu['exp_type']==1) {
                /*---
                $getwareno=$goodsinfo['goods_sn'];
                $where['OrdNo'] = $order_sn;
                $where['WareNo'] = $getwareno;
                $user_info['api_token'] = tpCache('shop_info.api_token', getAdmStoId());
                $offline = getApiData('wxd.pos.list.get', $user_info['api_token'], null, $where, 1, 10, '');

                if (empty($offline)) {
                    return json(['code' => 0, 'msg' => '网络异常']);
                }
                $offline = json_decode($offline, true);
                if ($offline['code'] == 1 && $offline['count'] && $offline['data']) {
                    $postStr = "{\"NUMBER\":\"" . $order_sn . "\"}";
                    httpRequest(curHostURL() . "/home/api/order", "POST", $postStr);
                    return json(['code' => 0, 'msg' => '此单已发货,无法申请此操作']);

                }---*/

                $accdb=tpCache("shop_info.ERPId",getAdmStoId());
                $data["WareId"]=$goodsinfo['erpwareid'];
                $data["OrdNo"]=$order_sn;

                $offline=getApiData_java_p("/api/erp/pos/page",$accdb,$data);
                if (empty($offline)) {
                    sleep(3);
                    $offline=getApiData_java_p("/api/erp/pos/page",$accdb,$data);
                    if (empty($offline)) {
                        sleep(3);
                        $offline=getApiData_java_p("/api/erp/pos/page",$accdb,$data);
                        if (empty($offline)) {
                            return json(['code' => 0, 'msg' => '网络异常']);
                        }
                    }
                }
                $offline = json_decode($offline, true);
                if($offline){
                    if($offline['code']==0 && $offline['data']){
                        if($offline['data']['pageData']) {
                            $postStr = "{\"NUMBER\":\"" . $order_sn . "\"}";
                            httpRequest(curHostURL() . "/home/api/order", "POST", $postStr);
                            return json(['code' => 0, 'msg' => '此单已发货,无法申请此操作']);
                        }
                    }
                }
            }
        }

        if ($rg['status']==2) return json(['code' => 0, 'msg' => '此单已经退款']);
        $user_id = $rg['user_id'];
        if ($user_id <= 0) return json(['code' => 0, 'msg' => '会员参数错误']);
        $type = I('type/d');
        $integral = $rg['back_integral'];
        $coupon_no = $rg['coupon_no'];
        $desc = I('desc/s');
        $time = time();
        $store_id = getAdmStoId();
        $wx =$money=0;

        //判断是不是阶梯团
        $ord=M("order")->where('order_id',$rg['order_id'])
            ->where('is_zsorder',4)
            ->field("")->find();
        //type=0退到余额,type=1原路退回
        if ($type == 0){
            $money = $rg['back_money'];
            return $this->return_user_money($money,$rg,$integral,$coupon_no,$desc);
        }else{
            if (($rg['order_amount']+$rg['pt_tail_money']) <= 0 ){
                $money = $rg['back_money'];
                return $this->return_user_money($money,$rg,$integral,$coupon_no,$desc);
            }else if(($rg['user_money']+$rg['pt_tail_money'])<=0){
                $wx = $rg['back_money'];
            }else{
                $money = $rg['user_money'];
                $wx = $rg['order_amount'];
                if($rg['is_zsorder']==4){
                    //当尾款是用余额支付的话
                    if($rg['tail_pay_type']==1){
                        $money += $ord['pt_tail_money'];
                    }else{
                        $wx+= $ord['pt_tail_money'];
                    }
                }
            }
            //$wx,$money,$rg,$integral,$coupon_no,$desc
            return $this->return_weixin_money($wx,$money,$rg,$integral,$coupon_no,$desc,$return_type,$rg['refund_no'],$rg['refund_no2']);
        }
    }

    //退款到用户余额,不需要微信计算
    public function return_user_money($money,$rg,$integral,$coupon_no,$desc){
        $user_id=$rg['user_id'];
        $time=time();
        $store_id=$rg['store_id'];
        $return_id=$rg['id'];
        /* 退货单的修改 */
        $data1['status'] = 2;
        if (empty($rg['handle_time']))
            $data1['handle_time'] = $time;
        $data1['ok_time'] = $time;
        $data1['wxrefund_no'] = I('wx_no/d');
        $data1['refund_admin'] = I('op/s');
        $rs=M('return_goods')->where('id', $return_id)->where('status<>2')->save($data1);
        if($rs) {
            $sql = 'update wxd_users set user_money=user_money+' . $money . ' where user_id=' . $user_id;
            Db::execute($sql);
            $sql1= "update wxd_order set return_amount=return_amount+" . $money . " where order_id=" . $rg['order_id'];
            Db::execute($sql1);
            $odata['user_id'] = $user_id;;
            $odata['create_time'] = $time;
            $odata['money'] = $money;
            $odata['remark'] = "退款";
            $odata['store_id'] = $store_id;
            $odata['order_sn'] = $rg['order_sn'];
            $odata['status'] = 1;
            $odata['type'] = 1;
            M('withdrawals')->save($odata);
            /* 插入帐户变动记录 */
            $account_log = [
                'user_id' => $user_id,
                'user_money' => $money,
                'pay_points' => 0,
                'change_time' => $time,
                'desc' => $desc,
                'order_sn' => $rg['order_sn'],
                'order_id' => $rg['order_id'],
                'store_id' => $store_id,
                'integral' => $integral
            ];
            M('account_log')->add($account_log);

            $vip_id = M('users')->where('user_id', $user_id)->field('erpvipid')->find();
            $token = tpCache('shop_info.api_token', $store_id);
            /*---调用线下接口增加积分---*/
            if (!empty($integral)) {
                /*--
                $data = ['Id' => $vip_id, 'Integral' => $integral, 'Remark' => "退款返回积分"];
                $res = getApiData("wxd.vip.addreduce", $token, array($data));
                $res = json_decode($res, true);
                mlog($user_id . $res[0] . '积分退款', 'Integral');--*/
                $accdb = tpCache('shop_info.ERPId', $store_id);
                com_update_integral($accdb,$vip_id,$integral,"积分退款",$module="后台会员",$rg['order_sn']."_tui");
            }

            /*---调用线下接口增加优惠券---*/
            if (!empty($coupon_no)) {
                $data = array('CashRepNo' => $coupon_no, 'VIPId' => $vip_id, 'IsUse' => 0);
                $s = getApiData('wxderp.cashreplace.edit', $token, array($data));
                mlog("优惠券的" . $coupon_no . "-" . $vip_id . '-' . $s, "quan");
            }
            $this->return_order_change($rg);

            //微信推送
            $title="退款成功通知";
            $remark='感谢您的参与~';
            $backurl= curHostURL() ."/index.php/Mobile/User/order_detail/id/".$rg['order_id']."/stoid/".$store_id;
            $this->post_msg($store_id,$vip_id,$user_id,$title,$rg['order_sn'],$rg['back_money'],$remark,$backurl);

            return json(['code' => 1, 'msg' => '操作成功']);
        }else{
            return json(['code' => -1, 'msg' => '退款失败,未找到订单或者已经退款']);
        }
    }

    //退款到用户余额,不需要微信计算
    public function return_weixin_money($wx,$money,$rg,$integral,$coupon_no,$desc,$return_t=1,$refund_no="",$refund_no2=""){
        $user_id=$rg['user_id'];
        $time=time();
        $store_id=$rg['store_id'];
        $return_id=$rg['id'];
        //微信退款失败的记录
        $ddd=null;
        /* 退货单的修改 */
        $data1['status'] = 2;
        if (empty($rg['handle_time']))
            $data1['handle_time'] = $time;
        $data1['ok_time'] = $time;
        $data1['wxrefund_no'] = I('wx_no');
        $data1['refund_admin'] = I('op/s');
        $rs=M('return_goods')->where('id', $return_id)->where('status<>2')->save($data1);
        if($rs) {

            if(empty($refund_no)) $refund_no='t'.date("YmdHis").get_total_millisecond().rand(1000, 9999).$store_id;
            if(empty($refund_no2)) $refund_no2='t'.date("YmdHis").get_total_millisecond().rand(1000, 9999).$store_id."2";

            //当是自动退的时候
            if($return_t==2) {
                if (empty($data1['wxrefund_no'])) {
                    //如果阶梯团的尾款也是用微信支付
                    if ($rg['is_zsorder'] == 4 && $rg['tail_pay_type'] == 0) {
                        if ($rg['order_amount'] > 0) {
                            $ordno = $rg['order_sn'];
                            $total_fee = $rg['order_amount'];
                            $refund_fee = $rg['order_amount'];
                            $path = BASE_PATH . 'public/cert/' . $store_id . '/';
                            include_once "plugins/payment/weixin/weixin.class.php";
                            $wxx = new \weixin();
                            try {
                                $rs = $wxx->refund2($ordno, $total_fee, $refund_fee, $path, $store_id,$refund_no,$rg['source_type']);
                                if ($rs['return_code'] == 'FAIL') {
                                    if(strpos($rs['return_msg'],'订单已') === false) {
                                        mlog($rg['order_sn'] . "退款失败," . $rs['return_msg'], 'refund/' . $store_id);
                                        $ddd['weixin_err'] = $rs['return_msg'];
                                        $ddd['weixin'] = $wx;
                                    }
                                }
                            } catch (\Exception $e) {
                                mlog($rg['order_sn'] . "退款签名失败," . $e->getMessage(), 'refund/' . $store_id);
                                $ddd['weixin_err'] = $e->getMessage();
                                $ddd['weixin'] = $wx;
                            }
                        }

                        if ($rg['pt_tail_money'] > 0 && empty($ddd)) {
                            $ordno = $rg['pt_pay_sn'];
                            $total_fee = $rg['pt_tail_money'];
                            $refund_fee = $rg['pt_tail_money'];
                            $path = BASE_PATH . 'public/cert/' . $store_id . '/';
                            include_once "plugins/payment/weixin/weixin.class.php";
                            $wxx = new \weixin();
                            try {
                                $rs = $wxx->refund_wk($ordno, $total_fee, $refund_fee, $path, $store_id,$refund_no2);
                                if ($rs['return_code'] == 'FAIL') {
                                    if(strpos($rs['return_msg'],'订单已') === false) {
                                        mlog($rg['order_sn'] . '_wk' . "退款失败," . $rs['return_msg'], 'refund/' . $store_id);
                                        $ddd['weixin_wei_err'] = $rs['return_msg'];
                                        $ddd['weixin_wei'] = $wx;
                                    }
                                }
                            } catch (\Exception $e) {
                                mlog($rg['order_sn'] . '_wk' . "退款签名失败," . $e->getMessage(), 'refund/' . $store_id);
                                $ddd['weixin_wei_err'] = $e->getMessage();
                                $ddd['weixin_wei'] = $wx;
                            }
                        }

                        $rno['refund_no'] = $refund_no;
                        $rno['refund_no2'] = $refund_no2;
                        $rs=M('return_goods')->where('id', $return_id)->save($rno);

                    } else {
                        if ($wx > 0) {
                            $ordno = $rg['order_sn'];
							$total_fee = $rg['order_amount'];

                            //如果单号不等于组合单号,区组合单号
                            if($ordno!=$rg['parent_sn']){
                                $ordno= $rg['parent_sn'];
                                $total_fee=M('order')->where('parent_sn',$ordno)->where('store_id',$store_id)->sum('order_amount');
                            }

                           
                            $refund_fee = $wx;
                            $path = BASE_PATH . 'public/cert/' . $store_id . '/';

                            include_once "plugins/payment/weixin/weixin.class.php";
                            $wxx = new \weixin();
                            try {
                                $rs = $wxx->refund2($ordno, $total_fee, $refund_fee, $path, $store_id,$refund_no,$rg['source_type']);
                                if ($rs['return_code'] == 'FAIL') {
                                    if(strpos($rs['return_msg'],'订单已') === false) {
                                        mlog($rg['order_sn'] . "退款失败," . $rs['return_msg'], 'refund/' . $store_id);
                                        $ddd['weixin_err'] = $rs['return_msg'];
                                        $ddd['weixin'] = $wx;
                                    }
                                }
                            } catch (\Exception $e) {
                                mlog($rg['order_sn'] . "退款签名失败," . $e->getMessage(), 'refund/' . $store_id);
                                $ddd['weixin_err'] = $e->getMessage();
                                $ddd['weixin'] = $wx;
                            }
                        }

                        $rno['refund_no'] = $refund_no;
                        $rs=M('return_goods')->where('id', $return_id)->save($rno);
                    }
                }
                //如果是
                if ($ddd) {
                    /* 退货单的修改 */
                    $data1['status'] = 1;
                    if (empty($rg['handle_time']))
                        $data1['handle_time'] = 0;
                    $data1['ok_time'] = 0;
                    $data1['wxrefund_no'] = "";
                    $data1['refund_admin'] = "";
                    $rs = M('return_goods')->where('id', $return_id)->save($data1);

                    $msg0 = $ddd['weixin_err'];
                    switch ($ddd['weixin_err']) {
                        case "certificate not match":
                            $msg0 = "证书已失效,请到微信商户平台更新证书,重新下载后上传";
                            break;
                        case "mch_id参数格式错误":
                            $msg0 = "微信支付商户号错误,请重新编辑";
                            break;
                        case "签名错误":
                            $msg0 = "微信支付KEY错误,请重新编辑";
                            break;
                        case "curl出错,错误码:58":
                            $msg0 = "证书路径错误,请重新上传";
                            break;
                    }
                    return json(['code' => -1, 'msg' => $msg0]);
                }
            }

            $sql = "update wxd_order set return_amount=return_amount+" . $wx . " where order_id=" . $rg['order_id'];
            Db::execute($sql);
            if($money>0){
                $sql = 'update wxd_users set user_money=user_money+' . $money . ' where user_id=' . $user_id;
                Db::execute($sql);
                $sql1= "update wxd_order set return_amount=return_amount+" . $money . " where order_id=" . $rg['order_id'];
                Db::execute($sql1);

                $odata['user_id'] =$user_id;
                $odata['create_time'] = time();
                $odata['money'] = $money;
                $odata['remark'] = "退款";
                $odata['store_id'] = $store_id;
                $odata['order_sn'] = $rg['order_sn'];
                $odata['status'] = 1;
                $odata['type'] = 1;
                M('withdrawals')->save($odata);

                /* 插入帐户变动记录 */
                $account_log = [
                    'user_id' => $user_id,
                    'user_money' => $money,
                    'pay_points' => 0,
                    'change_time' => $time,
                    'desc' => $desc,
                    'order_sn' => $rg['order_sn'],
                    'order_id' => $rg['order_id'],
                    'store_id' => $store_id,
                    'integral' => $integral
                ];
                M('account_log')->add($account_log);

            }

            $vip_id = M('users')->where('user_id', $user_id)->field('erpvipid')->find();
            $token = tpCache('shop_info.api_token', $store_id);
            $sto_erpid = tpCache('shop_info.ERPId', $store_id);//商户信息
            /*---调用线下接口增加积分---*/
            if (!empty($integral)) {
                /*---
                $data = array(
                    'VIPId' => $vip_id,//会员id
                    'OrderNo' => date('YmdHis') . rand(1000, 9999),//单号
                    'Integral' => $integral,//积分
                    'Remark' => '退款返回积分',
                );
                $res = getApiData_java_p("/api/erp/vip/integral/update", $sto_erpid, $data, 1, 10, null, "PUT");
                mlog($user_id . json_encode($res) . '积分退款', 'Integral/'.$sto_erpid);---*/
                com_update_integral($sto_erpid,$vip_id,$integral,"退款返回积分",$module="admin/user",$rg['order_sn']."_tui");
            }

            /*---调用线下接口更新优惠券---*/
            if (!empty($coupon_no)) {
                $data = array('CashRepNo' => $coupon_no, 'VIPId' => $vip_id, 'IsUse' => 0);
                $s = getApiData('wxderp.cashreplace.edit', $token, array($data));
                mlog("优惠券的" . $coupon_no . "-" . $vip_id . '-' . $s, "quan/".$sto_erpid);
            }

            $this->return_order_change($rg);

            //微信推送
            $title="退款成功通知";
            $remark='感谢您的参与~';
            $backurl= curHostURL() ."/index.php/Mobile/User/order_detail/id/".$rg['order_id']."/stoid/".$store_id;
            $this->post_msg($store_id,$vip_id,$user_id,$title,$rg['order_sn'],$rg['back_money'],$remark,$backurl);
            return json(['code' => 1, 'msg' => '操作成功']);

        }else{
            return json(['code' => -1, 'msg' => '退款失败,未找到订单或者已经退款']);
        }
    }

    //退款订单的修改
    public function return_order_change($rg){
        $dd = array();
        $dd['is_send'] = 4;
        switch ($rg['type']) {
            case 0://退货
                $dd['is_send'] = 3; break;
            case 2://退款
                $dd['is_send'] = 4;break;
        }
        /*订单商品的修改*/
        M('order_goods')->where(['order_id' => $rg['order_id'], 'goods_id' => $rg['goods_id']])->save($dd);
        $rule = tpCache('basic.sales_rules', getAdmStoId());//获取线下线上规则


        $order = M('order')->where('order_id', $rg['order_id'])
            ->field('user_money,gift_receive_id,store_id,order_sn')->find();
        $ord_goods = M('order_goods')->where('order_id', $rg['order_id'])
            ->field('is_send,goods_id,goods_num,store_id,order_sn,goods_price,prom_type')->select();
        /*---当一单里面有多个商品的时候,且不是整单退款---*/
        if (count($ord_goods) > 1) {
            if (empty($rg['goods_id_list'])) {//且不是整单退款
                /*--判断商品里面所有的商品是否都退款--*/
                $isallreturn = 1;
                foreach ($ord_goods as $kl => $vl) {
                    if ($vl['is_send'] < 2) {
                        $isallreturn = 0;
                    } else {
                        //只要这次商品要减,之前减过了不减
                        if($vl['goods_id']==$rg['goods_id']) {
                            M('goods')->where('goods_id', $vl['goods_id'])->setDec('sales_sum', $vl['goods_num']); // 减少商品销售量
                            if ($rule == 1 || $vl['prom_type']==1 || $vl['prom_type']==2 ) {
                                //M('goods')->where('goods_id', $vl['goods_id'])->setDec('sales_sum', $vl['goods_num']); // 减少商品销售量
                                M('goods')->where('goods_id', $vl['goods_id'])->setInc('store_count', $vl['goods_num']); // 增加商品库存
                            } else {
                                //预出库
                                M("erp_yqty")
                                    ->where("store_id", $vl['store_id'])
                                    ->where("order_sn", $vl['order_sn'])
                                    ->where("goods_id", $vl['goods_id'])->delete();
                            }
                        }
                    }
                }
                if ($isallreturn == 1) {
                    M("order")->where('order_id', $rg['order_id'])->save(['order_status' => 6]);
                }
            } else {
                M("order")->where('order_id', $rg['order_id'])->save(['order_status' => 6]);
                foreach ($ord_goods as $kk => $vv) {
                    M('goods')->where('goods_id', $vv['goods_id'])->setDec('sales_sum', $vv['goods_num']); // 减少商品销售量
                    if (($rule == 1  || $vv['prom_type']==1 || $vv['prom_type']==2 ) && $vv['goods_price'] > 0) {
                        M('goods')->where('goods_id', $vv['goods_id'])->setInc('store_count', $vv['goods_num']);
                    }
                    if($rule == 2  && $vv['goods_price'] > 0){
                        //预出库
                        M("erp_yqty")
                            ->where("store_id",$vv['store_id'])
                            ->where("order_sn",$vv['order_sn'])
                            ->where("goods_id",$vv['goods_id'])->delete();
                    }
                    if ($vv['goods_price'] == 0) {//增加赠品库存
                        M('gift')->where(['goods_id' => $vv['goods_id'], 'is_end' => 0])->setInc('goods_num', $vv['goods_num']);
                        M('gift_receive')->where(['id' => ['in', $order['gift_receive_id']]])->delete();
                    }
                }
            }
        } else {
            if ($rule == 1 || $ord_goods[0]['prom_type']==1
                || $ord_goods[0]['prom_type']==2
                || $ord_goods[0]['prom_type']==4
                || $ord_goods[0]['prom_type']==6
            ) {
                M('goods')->where('goods_id', $ord_goods[0]['goods_id'])->setInc('store_count', $ord_goods[0]['goods_num']); // 增加商品库存
            }else{
                //预出库
                M("erp_yqty")
                    ->where("store_id",$order['store_id'])
                    ->where("order_sn",$order['order_sn'])
                    ->where("goods_id",$ord_goods[0]['goods_id'])->delete();
            }
            M('goods')->where('goods_id', $ord_goods[0]['goods_id'])->setDec('sales_sum', $ord_goods[0]['goods_num']); // 减少商品销售量
            M("order")->where('order_id', $rg['order_id'])->save(['order_status' => 6]);
        }
    }

    //微信推送消息
    public function post_msg($store_id,$vip_id,$user_id,$title,$order_sn,$back_money,$remark,$backurl){

        $colorlist = urlencode("#FF0000|#173177|#173177|#173177|#173177|#FF0000|#FF0000|#ca003a");
        //$url = curHostURL() . "/home/api/poswxcode?typeid=1023&Acc=" . $erpid . "&ErpVipid=" . $erpvipid . "&title=" . $title . "&key1=" . $goods_name . "&key2=" . $num . "人团&remark=" . $remark.'&colorlist='. $colorlist."&backurl=" . $backurl;
        //mlog($url,'poswxcode/'.$erpid);
        $data['typeid']='1025';//微信消息类型 1001至1010
        $data['title']=$title;
        $data['remark']=$remark;
        $data['key1']=$order_sn;
        $data['key2']=$back_money;
        $data['colorlist']=$colorlist;
        $data['backurl']=$backurl;

        $data['Acc']=$vip_id;
        $data['user_id']=$user_id;

        $api  = new \app\home\controller\Api();
        //$resp=httpRequest($url, "GET");
        $resp=$api->poswxcode2($data);
        return $resp;
    }

}