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 ='
';
        $strTable .= '';
        $strTable .= '手机号码 ';
        $strTable .= '会员昵称 ';
        $strTable .= '一级下线数 ';
        $strTable .= '二级下线数 ';
        $strTable .= '三级下线数 ';
        $strTable .= '注册日期 ';
        $strTable .= ' ';
        if(is_array($userList)){
            foreach($userList as $k=>$val){
                $strTable .= '';
                $strTable .= ' '.$val['mobile'].' ';
                $strTable .= ''.$val['nickname'].'  ';
                $strTable .= ''.($val['fisrt_leader']==''?'0':$val['fisrt_leader']).' ';
                $strTable .= ''.($val['second_leader']==''?'0':$val['second_leader']).'  ';
                $strTable .= ''.($val['third_leader']==''?'0':$val['third_leader']).' ';
                $strTable .= ''.date('Y-m-d H:i:s', $val['reg_time']).' ';
                $strTable .= ' ';
            }
        }
        $strTable .='
';
        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 "{$val['email']} ";
            }                        
        }
        else
        {
            $list = M('users')->where(" mobile like '%$search_key%' ")->select();        
            foreach($list as $key => $val)
            {
                echo "{$val['mobile']} ";
            }            
        } 
        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 "";
        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 "";
            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 ='';
        $strTable .= '';
        $strTable .= '申请单号 ';
        $strTable .= '用户手机 ';
        $strTable .= '申请时间 ';
        $strTable .= '申请金额 ';
        $strTable .= '银行名称 ';
        $strTable .= '银行账号 ';
        $strTable .= '银行账户 ';
        $strTable .= '状态 ';
        $strTable .= ' ';
        if(is_array($list)){
            foreach($list as $k=>$val){
                $strTable .= '';
                $strTable .= ''.$val['order_sn'].' ';
                $strTable .= ''.$val['mobile'].' ';
                $strTable .= ''.date('Y-m-d H:i:s',$val['create_time']).' ';
                $strTable .= '¥'.$val['money'].' ';
                $strTable .= ''.$val['bank_name'].'  ';
                $strTable .= ''.$val['account_bank'].'  ';
                $strTable .= ''.$val['account_name'].' ';
                $strTable .= ''.($val['status']=='0'?'申请中':$val['status']=='1'?'申请成功':'申请失败').' ';
                $strTable .= ' ';
            }
        }
        $strTable .='
';
        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 ='';
        $strTable .= '';
        $strTable .= '用户手机 ';
        $strTable .= '银行名称 ';
        $strTable .= '银行账号 ';
        $strTable .= '申请金额 ';
        $strTable .= '状态 ';
        $strTable .= '操作时间 ';
        $strTable .= '备注 ';
        $strTable .= ' ';
        if(is_array($list)){
            foreach($list as $k=>$val){
                $strTable .= '';
                $strTable .= ''.$val['mobile'].' ';
                $strTable .= ''.$val['bank_name'].'  ';
                $strTable .= ''.$val['account_bank'].'  ';
                $strTable .= '¥'.$val['money'].' ';
                $strTable .= '已处理 ';
                $strTable .= ''.date('Y-m-d H:i:s',$val['create_time']).' ';
                $strTable .= ''.$val['remark'].' ';
                $strTable .= ' ';
            }
        }
        $strTable .='
';
        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;
    }
}