<?php
namespace app\admin\logic;
use app\admin\model\User;
use think\Db;
use app\common\logic\AccountLogLogic;
use app\common\logic\UserLevelLogic;
use app\common\model\AccountLog;
use app\common\model\Order;
use app\common\model\Pay;
use app\common\server\UrlServer;
use think\Exception;

class UserLogic{
    /**
     * 用户的列表
     * @param $get
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function lists($get){
        $user = new User();

        $where = [];
        $user_id=[];
        $where[] = ['del','=', '0'];

        // 查询
        if(isset($get['keyword']) && $get['keyword']){
            $where[] = [$get['keyword_type'],'like','%'.$get['keyword'].'%'];
        }
        if(isset($get['id']) && $get['id'] != ''){
            $where[] = ['id','=',$get['id']];
        }
        if(isset($get['nickname']) && $get['nickname'] != ''){
            $where[] = ['nickname', 'like', '%' . $get['nickname'] . '%'];
        }
        //根据客户电话查询
        if(isset($get['phone']) && $get['phone'] != ''){
            $phone=Db::name('user_address')->whereLike('phone',$get['phone'])->find();
            $where[] = ['user_id','=',$phone['user_id']];
        }
         //根据客户姓名查询
        if(isset($get['name']) && $get['name'] != ''){
            $phone=Db::name('user_address')->whereLike('consignee',$get['name'])->find();
            $where[] = ['user_id','=',$phone['user_id']];
        } 
        if(isset($get['number_fre']) && $get['number_fre'] != ''){
            $where[] = ['number_fre','=',$get['number_fre']];
        }
       
        //等级查询
        if(isset($get['level']) && $get['level'] != ''){
            $where[] = ['level','=',$get['level']];
        }

        //分组查询
        if(isset($get['group_id']) && $get['group_id']){
            $where[] = ['group_id','=',$get['group_id']];
        }
        //消费金额
        if(isset($get['total_amount_start']) && $get['total_amount_start']){
            $where[] = ['total_order_amount','>=',$get['total_amount_start']];
        }
        if(isset($get['total_amount_end']) && $get['total_amount_end']){
            $where[] = ['total_order_amount','<=',$get['total_amount_end']];
        }

        //注册时间
        if(isset($get['start_time']) && $get['start_time']!=''){
            $where[] = ['create_time','>=',strtotime($get['start_time'])];
        }
        if(isset($get['end_time']) && $get['end_time']!=''){
            $where[] = ['create_time','<=',strtotime($get['end_time'])];
        }
        
                //注册时间
        if(isset($get['start_times']) && $get['start_times']!=''){
            $where[] = ['login_time','>=',strtotime($get['start_times'])];
        }
        if(isset($get['end_times']) && $get['end_times']!=''){
            $where[] = ['login_time','<=',strtotime($get['end_times'])];
        }
        
        $user_count = $user
                    ->where($where)
                    ->count();

        $user_list = $user
                    ->where($where)
                    ->field('password,pay_password,salt',true)
                    ->page($get['page'],$get['limit'])
                    ->order('id desc')
                    ->select()->toArray();
        //会员分组
        $user_group = Db::name('user_group')->where(['del'=>0])->column('name','id');
        //会员等级
        $user_level = Db::name('user_level')->where(['del'=>0])->column('name','id');

        $all_user_list = $user->where(['del'=>0])->column('sn,nickname,avatar,mobile,level','id');
        $group_list = db::name('user_group')->where(['del'=>0])->column('name','id');

        foreach ($user_list as &$item){
            $item['group_name'] = '-';
            $item['level_name'] = '无等级';
            //会员所属分组
            if(isset($user_group[$item['group_id']])){
                $item['group_name'] = $user_group[$item['group_id']];
            }

            if(isset($user_level[$item['level']])){
                $item['level_name'] = $user_level[$item['level']];
            }


            if ($item['avatar'] != '/static/common/image/default/user.png') {
                $item['abs_avatar'] = $item['avatar'] ? UrlServer::getFileUrl($item['avatar']) : '';
            } else {
                $item['abs_avatar'] = '/static/common/image/default/user.png';
            }

            $item['referrer_nickname'] = '';
            $item['referrer_sn'] = '';
            $item['referrer_mobile'] = '';
            $item['referrer_avatar'] = '';
            $item['referrer_level_name'] = '-';
            if(isset($all_user_list[$item['first_leader']])){
                 $referrer_user = $all_user_list[$item['first_leader']];
                 $item['referrer_nickname'] = $referrer_user['nickname'];
                 $item['referrer_sn'] = $referrer_user['sn'];
                 $item['referrer_mobile'] = $referrer_user['mobile'];
                 $item['referrer_avatar'] = UrlServer::getFileUrl($referrer_user['avatar']);
                 if(isset($user_level[$referrer_user['level']])){
                     $item['referrer_level_name'] =$user_level[$referrer_user['level']];

                 }
            }
            if(isset($group_list[$item['group_id']])){
                $item['group_name'] = $group_list[$item['group_id']];
            }


        }

        return ['count'=>$user_count , 'lists'=>$user_list];
    }


    /**
     * 年卡用户的列表
     * @param $get
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function yearlists($get){
        $user = new User();
        $where = [];
        $user_id=[];
        $where[] = ['del','=', '0'];
        if(isset($get['id']) && $get['id'] != ''){
            $where[] = ['id','=',$get['id']];
        }
        if(isset($get['nickname']) && $get['nickname'] != ''){
            $where[] = ['nickname', 'like', '%' . $get['nickname'] . '%'];
        }
        //根据客户电话查询
        if(isset($get['phone']) && $get['phone'] != ''){
            $phone=Db::name('user_address')->whereLike('phone',$get['phone'])->find();
            $where[] = ['user_id','=',$phone['user_id']];
        }
         //根据客户姓名查询
        if(isset($get['name']) && $get['name'] != ''){
            $phone=Db::name('user_address')->whereLike('consignee',$get['name'])->find();
            $where[] = ['user_id','=',$phone['user_id']];
        } 
        if(isset($get['number_fre']) && $get['number_fre'] != ''){
            $where[] = ['number_fre','=',$get['number_fre']];
        }
       
        //等级查询
        if(isset($get['level']) && $get['level'] != ''){
            $where[] = ['level','=',$get['level']];
        }

        //分组查询
        if(isset($get['group_id']) && $get['group_id']){
            $where[] = ['group_id','=',$get['group_id']];
        }
        //消费金额
        if(isset($get['total_amount_start']) && $get['total_amount_start']){
            $where[] = ['total_order_amount','>=',$get['total_amount_start']];
        }
        if(isset($get['total_amount_end']) && $get['total_amount_end']){
            $where[] = ['total_order_amount','<=',$get['total_amount_end']];
        }

        //注册时间
        if(isset($get['start_time']) && $get['start_time']!=''){
            $where[] = ['create_time','>=',strtotime($get['start_time'])];
        }
        if(isset($get['end_time']) && $get['end_time']!=''){
            $where[] = ['create_time','<=',strtotime($get['end_time'])];
        }
        $user_count =Db::name('user')
        ->where($where)
        ->orderRaw("rand()")
        ->where('user_id','IN',function($query){
            $query->table('ls_order_yearcard')->field("user_id");
        })
        ->page($get['page'],$get['limit'])
        ->count();

        $user_list = $user
                    ->where($where)
                    ->field('password,pay_password,salt',true)
                    ->orderRaw("rand()")
                    ->where('user_id','IN',function($query){
                        $query->table('ls_order_yearcard')->field("user_id");
                    })
                    ->page($get['page'],$get['limit'])
                    ->order('id desc')
                    ->select()->toArray();
        //会员分组
        $user_group = Db::name('user_group')->where(['del'=>0])->column('name','id');
        //会员等级
        $user_level = Db::name('user_level')->where(['del'=>0])->column('name','id');
        $all_user_list = $user->where(['del'=>0])->column('sn,nickname,avatar,mobile,level','id');
        $group_list = db::name('user_group')->where(['del'=>0])->column('name','id');

        foreach ($user_list as &$item){
            $item['group_name'] = '-';
            $item['level_name'] = '无等级';
            //会员所属分组
            if(isset($user_group[$item['group_id']])){
                $item['group_name'] = $user_group[$item['group_id']];
            }
            if(isset($user_level[$item['level']])){
                $item['level_name'] = $user_level[$item['level']];
            }


            if ($item['avatar'] != '/static/common/image/default/user.png') {
                $item['abs_avatar'] = $item['avatar'] ? UrlServer::getFileUrl($item['avatar']) : '';
            } else {
                $item['abs_avatar'] = '/static/common/image/default/user.png';
            }

            $item['referrer_nickname'] = '';
            $item['referrer_sn'] = '';
            $item['referrer_mobile'] = '';
            $item['referrer_avatar'] = '';
            $item['referrer_level_name'] = '-';
            if(isset($all_user_list[$item['first_leader']])){
                 $referrer_user = $all_user_list[$item['first_leader']];
                 $item['referrer_nickname'] = $referrer_user['nickname'];
                 $item['referrer_sn'] = $referrer_user['sn'];
                 $item['referrer_mobile'] = $referrer_user['mobile'];
                 $item['referrer_avatar'] = UrlServer::getFileUrl($referrer_user['avatar']);
                 if(isset($user_level[$referrer_user['level']])){
                     $item['referrer_level_name'] =$user_level[$referrer_user['level']];

                 }
            }


            if(isset($group_list[$item['group_id']])){
                $item['group_name'] = $group_list[$item['group_id']];
            }

        }

        return ['count'=>$user_count , 'lists'=>$user_list];
    }

    /**
     * 次卡用户列表
     * @param $get
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function onelist($get){
      
        $where = [];
        if(isset($get['id']) && $get['id'] != ''){
            $where[] = ['id','=',$get['id']];
        }
        //根据客户电话查询
        if(isset($get['phone']) && $get['phone'] != ''){
            $where[] = ['telephone','=',$get['phone']];
        }
        
       if(isset($get['chann_id']) && $get['chann_id'] != ''){
            $where[] = ['brand_id','=',$get['chann_id']];
        }
       if(isset($get['label_id']) && $get['label_id'] != ''){
            $where[] = ['label_id','=',$get['label_id']];
        }
                //注册时间
        if(isset($get['start_time']) && $get['start_time']!=''){
            $where[] = ['createtime','>=',strtotime($get['start_time'])];
        }
        if(isset($get['end_time']) && $get['end_time']!=''){
            $where[] = ['createtime','<=',strtotime($get['end_time'])];
        }
        
         //根据客户姓名查询
        if(isset($get['name']) && $get['name'] != ''){
            $where[] = ['contact', 'like', '%' . $get['name'] . '%'];
        } 
        if(isset($get['adder']) && $get['adder'] != ''){
            $where[] = ['address', 'like',$get['adder'] . '%'];
        } 
        if(isset($get['area_id']) && $get['area_id'] != ''){
            $where[] = ['district_id','=',$get['area_id']];
        }
        if(isset($get['admin_id']) && $get['admin_id'] != ''){
            $where[] = ['admin_id','=',$get['admin_id']];
        }
        if(isset($get['pet']) && $get['pet'] != ''){
            $where[] = ['pet','=',$get['pet']];
        }
        if(isset($get['hbl']) && $get['hbl'] != ''){
            $where[] = ['hbl','=',$get['hbl']];
        }
        
        
        $user_count = Db::name('user_address')
                    ->where($where)
                    ->field('password,pay_password,salt',true)
                    ->order('id desc')
                    ->count();
        $user_list = Db::name('user_address')
                    ->where($where)
                    ->field('password,pay_password,salt',true)
                    ->page($get['page'],$get['limit'])
                    ->order('id desc')
                    ->select();
        foreach ($user_list as &$item){
            $staff=Db::name('admin')->where('id',$item['admin_id'])->find();
            if($staff){
                $item['name']= $staff['name'];
            }else{
                $item['name']='-';
            }
            
          
            $user=Db::name('user')->where('id',$item['user_id'])->find();
            if($user){
                  $item['avatar'] = UrlServer::getFileUrl($user['avatar']);
                  $item['nickname']=$user['nickname'];
            }else{
                $item['nickname']='-';
            }
            $item['qudao']=Db::name('staffchannel')->where('id', $item['brand_id'])->column('name');
            $custom=Db::name('custom')->where('custom_id',$item['id'])->order('id desc')->find();
            $item['custom']=Db::name('custom')->where('custom_id', $item['id'])->order('id desc')->limit(1)->column('connect');
            if($custom){
                $item['create_timess']=date("Y年m月d日 H:i",$custom['create_time']);
            }else{
                $item['create_timess']="-";
            }
            $item['qudao']=Db::name('staffchannel')->where('id', $item['brand_id'])->column('name');
            

            $label=Db::name('user_label')->where('id',$item['label_id'])->find();
            if($label){
                $item['user_label']=$label['name'];
            }else{
                $item['user_label']='-'; 
            }
            
            
        }

        return ['count'=>$user_count , 'lists'=>$user_list];
    }
     public static function exportFiles($get)
    {
        $where=[];
        //查询
        if(isset($get['keyword']) && $get['keyword']){
            $where[] = [$get['keyword_type'],'like','%'.$get['keyword'].'%'];
        }
         if(isset($get['label_id']) && $get['label_id'] != ''){
            $where[] = ['label_id','=',$get['label_id']];
        }
       
        if(isset($get['name']) && $get['name'] != ''){
            $where[] = ['contact', 'like', '%' . $get['name'] . '%'];
        }          
        if(isset($get['admin_id']) && $get['admin_id'] != ''){
            $where[] = ['admin_id','=',$get['admin_id']];
        }
        
     
        //根据客户电话查询
        if(isset($get['phone']) && $get['phone'] != ''){
            $where[] = ['telephone','=',$get['phone']];
        }
        //注册时间
        if(isset($get['start_time']) && $get['start_time']!=''){
            $where[] = ['create_time','>=',strtotime($get['start_time'])];
        }
        if(isset($get['end_time']) && $get['end_time']!=''){
            $where[] = ['create_time','<=',strtotime($get['end_time'])];
        }

        $user_list = Db::name('user_address')->where($where)
            ->order('id desc')
            ->select();
        $exportData = [];
        foreach ($user_list as $item){
            $groupName = '-';
            $adminname='-';
            $levelName = '-';
            $goud=Db::name('user_label')->where('id',$item['label_id'])->find();
           $admin =Db::name('admin')->where('id',$item['admin_id'])->find();
            if($admin){
               $adminname=$admin['name'];  
            }
            if($goud){
                $groupName =$goud['name'] ;
            }
            $lent=Db::name('staffchannel')->where('id',$item['brand_id'])->find();
            if($lent){
              $levelName=$lent['name'];
            }
            $loginTime = date('Y-m-d H:i:s', $item['createtime']);

            $exportData[] = [$item['id'], $item['contact'],$item['telephone'],$groupName,$levelName,$adminname,$loginTime];
        }

        $exportTitle = ['用户iD', '客户姓名','客户电话','客户标签','渠道来源','客户管家','注册时间',];
        $exportExt = 'xls';
        return ['exportTitle'=> $exportTitle, 'exportData' => $exportData, 'exportExt'=>$exportExt, 'exportName'=>'会员列表'.date('Y-m-d H:i:s')];
    }
    
    
    public static function exportFile($get)
    {
        $where[] = ['del','=', '0'];

        //查询
        if(isset($get['keyword']) && $get['keyword']){
            $where[] = [$get['keyword_type'],'like','%'.$get['keyword'].'%'];
        }
        //等级查询
        if(isset($get['level']) && $get['level'] != ''){
            $where[] = ['level','=',$get['level']];
        }
        //分组查询
        if(isset($get['group_id']) && $get['group_id']){
            $where[] = ['group_id','=',$get['group_id']];
        }
        //消费金额
        if(isset($get['total_amount_start']) && $get['total_amount_start']){
            $where[] = ['total_order_amount','>=',$get['total_amount_start']];
        }
        if(isset($get['total_amount_end']) && $get['total_amount_end']){
            $where[] = ['total_order_amount','<=',$get['total_amount_end']];
        }

        //注册时间
        if(isset($get['start_time']) && $get['start_time']!=''){
            $where[] = ['create_time','>=',strtotime($get['start_time'])];
        }
        if(isset($get['end_time']) && $get['end_time']!=''){
            $where[] = ['create_time','<=',strtotime($get['end_time'])];
        }

        $user_list = Db::name('user')->where($where)
            ->order('id desc')
            ->select();

        //会员分组
        $user_group = Db::name('user_group')->where(['del'=>0])->column('name','id');
        //会员等级
        $user_level = Db::name('user_level')->where(['del'=>0])->column('name','id');
        // 所有会员信息
        $all_user_list = User::where(['del'=>0])->column('sn,nickname,mobile,level','id');

        $exportData = [];
        foreach ($user_list as $item){
            $groupName = '-';
            $levelName = '无等级';
            //会员所属分组
            if(isset($user_group[$item['group_id']])){
                $groupName = $user_group[$item['group_id']];
            }

            if(isset($user_level[$item['level']])){
                $levelName = $user_level[$item['level']];
            }

            $referrer_user_info = '';
            $referrer_nickname = '';
            $referrer_sn = '';
            $referrer_mobile = '';
            $referrer_level_name = '-';
            if(isset($all_user_list[$item['first_leader']])){
                $referrer_user = $all_user_list[$item['first_leader']];
                $referrer_nickname = $referrer_user['nickname'];
                $referrer_sn = $referrer_user['sn'];
                $referrer_mobile = $referrer_user['mobile'];
                if(isset($user_level[$referrer_user['level']])){
                    $referrer_level_name =$user_level[$referrer_user['level']];
                }
                $referrer_user_info.= '【昵称:'.$referrer_nickname.' 编号:'.$referrer_sn. ' 手机:'. $referrer_mobile . ' 等级:'. $referrer_level_name.'】';
            }
            $loginTime = date('Y-m-d H:i:s', $item['login_time']);

            $exportData[] = [$item['sn'], $item['nickname'], $levelName, $groupName, $referrer_user_info, $item['total_order_amount'], $item['user_money'], $item['user_integral'], $loginTime];
        }

        $exportTitle = ['会员编号', '会员昵称', '会员等级', '会员分组', '推荐人信息', '消费金额', '账户余额', '积分', '最后登录时间'];
        $exportExt = 'xls';
        return ['exportTitle'=> $exportTitle, 'exportData' => $exportData, 'exportExt'=>$exportExt, 'exportName'=>'会员列表'.date('Y-m-d H:i:s')];
    }
     
    /**
     * Notes: 
     * @param 根据检索的内容导出
     * @param bool $getdata 导出内容
     * @param bool $expenditure 是否显示会员消费
     * @return User|mixed
     */   
    
    public static function userexportfiles($get){
        $where = [];
        if(isset($get['id']) && $get['id'] != ''){
            $where[] = ['id','=',$get['id']];
        }
        //根据客户电话查询
        if(isset($get['phone']) && $get['phone'] != ''){
            $where[] = ['telephone','=',$get['phone']];
        }
        
       if(isset($get['chann_id']) && $get['chann_id'] != ''){
            $where[] = ['brand_id','=',$get['chann_id']];
        }
       if(isset($get['label_id']) && $get['label_id'] != ''){
            $where[] = ['label_id','=',$get['label_id']];
        }
        //注册时间
        if(isset($get['start_time']) && $get['start_time']!=''){
            $where[] = ['createtime','>=',strtotime($get['start_time'])];
        }
        if(isset($get['end_time']) && $get['end_time']!=''){
            $where[] = ['createtime','<=',strtotime($get['end_time'])];
        }
        
         //根据客户姓名查询
        if(isset($get['name']) && $get['name'] != ''){
            $where[] = ['contact', 'like', '%' . $get['name'] . '%'];
        } 
        if(isset($get['adder']) && $get['adder'] != ''){
            $where[] = ['address', 'like',$get['adder'] . '%'];
        } 
        if(isset($get['area_id']) && $get['area_id'] != ''){
            $where[] = ['district_id','=',$get['area_id']];
        }
        if(isset($get['admin_id']) && $get['admin_id'] != ''){
            $where[] = ['admin_id','=',$get['admin_id']];
        }
        if(isset($get['pet']) && $get['pet'] != ''){
            $where[] = ['pet','=',$get['pet']];
        }
        if(isset($get['hbl']) && $get['hbl'] != ''){
            $where[] = ['hbl','=',$get['hbl']];
        }
        
        $user_list = Db::name('user_address')
                    ->where($where)
                    ->order('id desc')
                    ->select();
         $exportData = [];
         foreach ($user_list as $item){
            $admin=Db::name('admin')->where('id',$item['admin_id'])->find();    //客户归属
            if($admin){
                $item['admin']=$admin['name'];
            }else{
                $item['admin']='-';
            }
            
            $label=Db::name('user_label')->where('id',$item['label_id'])->find();                        //客户标签
            
            if($label){
                $item['label_name']=$label['name'];
            }else{
                 $item['label_name']='-';
            }
            
            $break=Db::name('staffchannel')->where('id',$item['brand_id'])->find();                                //客户渠道来源
            
            if($break){
                $item['break_name']=$break['name'];
            }else{
                 $item['break_name']='-';
            }
            
            $userquy=Db::name('user')->where('mobile',$item['telephone'])->find();                                       //客户的区域
           ;
            
            if($userquy){
                $item['userjf']=$userquy['user_integral'];
            }else{
                 $item['userjf']='-';
            }
            $money=0;
           
            if($get['year']==2022){                                                                       //统计2022年消费的金额
                $money=Db::name('order')
                      ->where('mobile',$item['telephone'])
                      ->where(['del'=>0,'pay_status'=>1])
                      ->where('create_time','>',strtotime('2022-1-01 00:00:00'))
                      ->where('create_time','<',strtotime('2022-12-31 12:59:59'))
                      ->sum('order_amount');
            }
            if($get['year']==2023){                                                                       //统计2022年消费的金额
                $money=Db::name('order')
                      ->where('mobile',$item['telephone'])
                      ->where(['del'=>0,'pay_status'=>1])
                      ->where('create_time','>=',strtotime('2023-1-01 00:00:00'))
                      ->where('create_time','<=',strtotime('2023-12-31 12:59:59'))
                      ->sum('order_amount');
            }
            
            if($get['year']==2024){                                                                       //统计2022年消费的金额
                $money=Db::name('order')
                      ->where('mobile',$item['telephone'])
                      ->where(['del'=>0,'pay_status'=>1])
                      ->where('create_time','>',strtotime('2024-1-01 00:00:00'))
                      ->where('create_time','<',strtotime('2024-12-31 12:59:59'))
                      ->sum('order_amount');
            }
            
            if($get['year']==2025){                                                                       //统计2022年消费的金额
                $money=Db::name('order')
                      ->where('mobile',$item['telephone'])
                      ->where(['del'=>0,'pay_status'=>1])
                      ->where('create_time','>=',strtotime('2025-1-01 00:00:00'))
                      ->where('create_time','<=',strtotime('2025-12-31 12:59:59'))
                      ->sum('order_amount');
            }
            
            $exportData[] = [$item['id'],$item['contact'],$item['telephone'],$item['address'],$item['areas'],$item['admin'], $item['label_name'],$item['break_name'],$item['areadistrict'],$item['userjf'],$money];
         }
  
          $exportTitle = ['会员ID', '客户姓名', '客户电话', '房屋地址','房屋面积', '客户归属', '标签', '客户来源', '客户区域', '客户积分','消费金额'];
          $exportExt = 'xls';
          return ['exportTitle'=> $exportTitle, 'exportData' => $exportData, 'exportExt'=>$exportExt, 'exportName'=>'客户档案'.date('Y-m-d H:i:s')];  
    }
    
    
    /**
     * Notes: 
     * @param $id获取会员的数据
     * @param bool $getdata 是否获取原始数据
     * @param bool $expenditure 是否显示会员消费
     * @return User|mixed
     */
    public static function getuserlist($id){
        $user=Db::name('user')->where('id',$id)->find();
        $user['avatar'] = UrlServer::getFileUrl($user['avatar']);
        $user['birthday']=date("Y-m-d",$user['birthday']);
        return $user;
    }
    /**
     * Notes: 获取会员信息
     * @param $id
     * @param bool $getdata 是否获取原始数据
     * @param bool $expenditure 是否显示会员消费
     * @return User|mixed
     */
    public static function getUser($id,$getdata = false,$expenditure = false){

        $user =  User::get($id);
        $user->append(['level_name','group_name']);
        if($getdata){
            $user = $user->getData();
            if($user['birthday']) $user['birthday'] = date('Y-m-d',$user['birthday']);
        }
        $user['abs_avatar'] = UrlServer::getFileUrl($user['avatar']);
        if($expenditure){
            //本月的消费金额
            $month_amount = Db::name('order')
                        ->where('order_status','not in',[Order::STATUS_CLOSE,Order::STATUS_WAIT_PAY])
                        ->where(['user_id'=>$id,'pay_status'=>Pay::ISPAID])
                        ->whereTime('create_time', 'month')
                        ->sum('order_amount');
            //本月的订单笔数
            $month_num = Db::name('order')
                       ->where('order_status','not in',[Order::STATUS_CLOSE,Order::STATUS_WAIT_PAY])
                       ->where(['user_id'=>$id,'pay_status'=>Pay::ISPAID])
                       ->whereTime('create_time', 'month')
                       ->count();
            //累计消费笔数
            $total_num =Db::name('order')
                        ->where('order_status','not in',[Order::STATUS_CLOSE,Order::STATUS_WAIT_PAY])
                        ->where(['user_id'=>$id,'pay_status'=>Pay::ISPAID])
                        ->sum('order_amount');
            $avg_amount = Db::name('order')
                        ->where('order_status','not in',[Order::STATUS_CLOSE,Order::STATUS_WAIT_PAY])
                        ->where(['user_id'=>$id,'pay_status'=>Pay::ISPAID])
                        ->avg('order_amount');
            $user['month_amount'] = '￥'.round($month_amount,2);
            $user['month_num'] = round($month_num,2);
            $user['total_num'] = round($total_num,2);
            $user['avg_amount'] = '￥'.round($avg_amount,2);
            //分销会员
            $user['distribution_tips'] = '否';
            $user['superior_referrer'] = '-';
            $user['superior_referrer_sn'] = '-';
            if($user['is_distribution']){
                $user['distribution_tips'] = '是';
                $superior_referrer = Db::name('user')->where(['id'=>$user['first_leader']])->field('nickname,sn')->findOrEmpty();
                $user['superior_referrer'] = '-';
                $user['superior_referrer_sn'] = '-';
                if($superior_referrer) {
                    $user['superior_referrer'] = $superior_referrer['nickname'];
                    $user['superior_referrer_sn'] = $superior_referrer['sn'];
                }
            }
            // 头像
            $user['avatar'] = UrlServer::getFileUrl($user['avatar']);
        }
        return $user;



    }
    /*
     * 批量设置会员分组
     */
    public static function setGroup($post){
        return Db::name('user')->where(['id'=>$post['user_ids']])->update(['group_id'=>$post['group_id']]);
    }

    /*
     * 用户账户调整
     */
    public static function adjustAccount($post_data){
        Db::startTrans();
        try {
            $update_data = [];
            $account_log = [];
            //余额调整
            if (isset($post_data['money_handle'])) {
                $number = $post_data['money'];
                $change_type = 1;
                $source_type = AccountLog::admin_add_money;
                $money_sql = Db::raw('user_money + ' . $post_data['money']);
                if ($post_data['money_handle'] == 0) {
                    $change_type = 2;
                    $source_type = AccountLog::admin_reduce_money;
                    $money_sql = Db::raw('user_money - ' . $post_data['money']);
                }
                $update_data['user_money'] = $money_sql;
                $account_log[] = [
                    'number'        => $number,
                    'change_type'   => $change_type,
                    'source_type'   => $source_type,
                    'remark'        => $post_data['money_remark'],
                ];
            }
            //积分调整
            if (isset($post_data['integral_handle'])) {
                $number = $post_data['integral'];
                $change_type = 1;
                $source_type = AccountLog::admin_add_integral;
                $integral_sql = Db::raw('user_integral + ' . $post_data['integral']);

                if ($post_data['integral_handle'] == 0) {
                    $change_type = 2;
                    $source_type = AccountLog::admin_reduce_integral;
                    $integral_sql = Db::raw('user_integral - ' . $post_data['integral']);
                }
                $update_data['user_integral'] = $integral_sql;
                $account_log[] = [
                    'number'        => $number,
                    'change_type'   => $change_type,
                    'source_type'   => $source_type,
                    'remark'        => $post_data['integral_remark'],
                ];
            }
            //成长值调整
            if (isset($post_data['growth_handle'])) {
                $number = $post_data['growth'];
                $change_type = 1;
                $source_type = AccountLog::admin_add_growth;
                $growth_sql = Db::raw('user_growth + ' . $post_data['growth']);

                if ($post_data['growth_handle'] == 0) {
                    $change_type = 2;
                    $source_type = AccountLog::admin_reduce_growth;
                    $growth_sql = Db::raw('user_growth - ' . $post_data['growth']);
                }
                $update_data['user_growth'] = $growth_sql;
                $account_log[] = [
                    'number'        => $number,
                    'change_type'   => $change_type,
                    'source_type'   => $source_type,
                    'remark'        => $post_data['growth_remark'],
                ];
            }


            Db::name('user')->where('id', $post_data['id'])->update($update_data);
            foreach ($account_log as $item => $value){
                AccountLogLogic::AccountRecord($post_data['id'],$value['number'],$value['change_type'],$value['source_type'],$value['remark']);
            }
            if (isset($post_data['growth_handle'])) {
                UserLevelLogic::updateUserLevel($post_data['id']);
            }
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
    }


    //todo 用户更新的地址
    public static function adjustLevel($post_data){
       return Db::name('user_address')->where('id',$post_data['id'])->update([
        'consignee'=>$post_data['name'],
        'phone'=>$post_data['phone'],
        'address'=>$post_data['address'],
        'lng'          =>$post['store_latitude'],
        'lat'          =>$post['store_longitude'],
        'province'=>$post_data['first_category_id'],
        'city'=>$post_data['second_category_id'],
        'area'=>$post_data['third_category_id'],
    ]);
    }
    /*
     * 获取分组
     */
    public static function getGroupList(){
        return Db::name('user_group')->where(['del'=>0])->field('id,name')->select();
    }

    /*
     * 获取等级
     */
    public static function getLevelList(){
        return Db::name('user_level')->where(['del'=>0])->field('id,name')->select();
    }

    /*
     * 编辑会员
     */
    public static function edit($post){
        $user = User::get($post['id']);
        if (!empty($post['password'])) {
            //生成密码
            $post['password'] = create_password($post['password'], $user->salt);
        } else {
            unset($post['password']);
        }
        $post['update_time'] = time();
        $post['birthday'] = strtotime($post['birthday']);
        return $user->allowField(true)->save($post);
    }

    /*
     * 后台增加用户会员
     */
    public static function add($post){
        $data=[
            'contact'            =>$post['name'],
            'telephone'          =>$post['phone'],
            'sex'               =>$post['sex'],
            'province_id'          =>$post['first_category_id'],
            'city_id'          =>$post['second_category_id'],
            'district_id'          =>$post['third_category_id'],
            'lng'          =>$post['store_latitude'],
            'lat'          =>$post['store_longitude'],
            'areas'          =>$post['areas'],
            'brand_id'          =>$post['brand_id'],
            'pet'          =>$post['pet'],
            'hbl'          =>$post['hbl'],
            'label_id'          =>$post['label_id'],
            'wx'          =>$post['wx'],
            'address'      =>$post['address'],
            'admin_id'     =>session('admin_info.id'),
            'updatetime'          =>time(), 
            'createtime'          =>time(),      

        ];
       return Db::name('user_address')->data($data)->insert();
     }


    public static function getList($get){
        switch ($get['type']){
            case 0://下单明细
                $order = new Order();
                $phto=Db::name('user')->where('id',$get['user_id'])
                ->find();
                
                $count = $order->alias('o')
                        ->where(['mobile'=>$phto['mobile']])
                        ->where('order_status','not in',[Order::STATUS_CLOSE,Order::STATUS_WAIT_PAY])
                        ->count();

                $list = $order->alias('o')
                        ->where(['mobile'=>$phto['mobile']])
                        //->where('order_status','not in',[Order::STATUS_CLOSE,Order::STATUS_WAIT_PAY])
                        ->page($get['page'],$get['limit'])
                        ->order('id desc')
                        ->field('o.id,order_sn,total_num,pay_time,total_amount,order_amount,discount_amount,
                                o.create_time,consignee,province,city,district,o.address,mobile')
                        ->select();

                break;
            case 1://积分明细
                $account_log =new AccountLog();
                $count = $account_log
                        ->where(['user_id'=>$get['user_id'],'source_type'=>AccountLog::integral_change])
                        ->count();
                $list = $account_log
                        ->where(['user_id'=>$get['user_id'],'source_type'=>AccountLog::integral_change])
                        ->page($get['page'],$get['limit'])
                        ->order('id desc')
                        ->select();
                break;
            case 2://签到明细
                $account_log =new AccountLog();
                $count = $account_log
                        ->where(['user_id'=>$get['user_id'],'source_type'=>AccountLog::sign_in_integral])
                        ->count();
                $list = $account_log
                        ->where(['user_id'=>$get['user_id'],'source_type'=>AccountLog::sign_in_integral])
                        ->page($get['page'],$get['limit'])
                        ->order('id desc')
                        ->select();
                break;
            case 3://余额明细
                $account_log = new AccountLog();
                $count = $account_log
                    ->where(['user_id'=>$get['user_id'],'source_type'=>AccountLog::money_change])
                    ->count();
                $list = $account_log
                    ->where(['user_id'=>$get['user_id'],'source_type'=>AccountLog::money_change])
                    ->page($get['page'],$get['limit'])
                    ->order('id desc')
                    ->select();
                break;
            case 4://推广明细
                $count = 1;
                $first_leader = Db::name('user')->where(['id'=>$get['user_id']])->value('first_leader');
                $list = [];
                if($first_leader){
                    $user = new User();
                    $list = $user
                            ->where(['id'=>$first_leader])
                            ->field('id,sn,nickname,mobile,avatar,level,sex,create_time,total_order_amount,user_money,user_integral')
                            ->order('id desc')
                            ->select();
                    $level_list = Db::name('user_level')->where(['del'=>0])->column('name','id');
                    foreach ($list as &$item) {
                        $item['avatar'] = UrlServer::getFileUrl($item['avatar']);
                        $item['level_name'] = '-';
                        if(isset($level_list[$item['level']])){
                            $item['level_name'] = $level_list[$item['level']];
                        }
                    }
                }
                break;
            case 5://房屋的地址
                $count = Db::name('user_address')
                            ->where(['user_id'=>$get['user_id'],'del'=>0])
                            ->count();
                $list = Db::name('user_address')
                            ->where(['user_id'=>$get['user_id'],'del'=>0])
                            ->order('id desc')
                            ->select();
                break;
            case 6://投诉建议的内容
                    $count = Db::name('user_report')
                                ->where(['user_id'=>$get['user_id']])
                                ->count();
                    $list = Db::name('user_report')
                                ->where(['user_id'=>$get['user_id']])
                                ->order('id desc')
                                ->select();
                    foreach ($list as &$item){
                      $item['create_time']=date("Y-m-d H:i:s",$item['create_time']);
                }

                break;
            case 7://回访记录
                    $count = Db::name('user_follow')
                                ->where(['user_id'=>$get['user_id']])
                                ->count();
                    $list = Db::name('user_follow')
                                ->where(['user_id'=>$get['user_id']])
                                ->order('id desc')
                                ->select();
                    foreach ($list as &$item){
                      $item['create_time']=date("Y-m-d H:i:s",$item['create_time']);
                      $staff=Db::name('staff')->where('id',$item['staff_id'])->find();
                      $item['name']=$staff['name'];
                      $item['phone']=$staff['mobile'];

                }

                break;

        }

        return ['count'=>$count , 'lists'=>$list];
    }

  /**
   * 转账记录
   */
  public static function transferRecord($get)
  {
    $where = [];
    // 开始时间
    if(!empty($get['start_time'])) {
      $where[] = ['create_time', '>=', strtotime($get['start_time'])];
    }
    // 结束时间
    if(!empty($get['end_time'])) {
      $where[] = ['create_time', '<=', strtotime($get['end_time'])];
    }

    $list = Db::name('user_transfer')
      ->where($where)
      ->page($get['page'], $get['limit'])
      ->order('create_time', 'desc')
      ->select();

    $count = Db::name('user_transfer')->count();

    // 获取转账人及收款人信息
    foreach($list as &$item) {
      $transferFromInfo = Db::name('user')->alias('u')
        ->field('u.sn, u.nickname, u.avatar, ul.name as user_level_name')
        ->leftJoin('user_level ul', 'u.level=ul.id')
        ->where('u.id', $item['transfer_from_id'])->find();
      $transferToInfo = Db::name('user')->alias('u')
      ->field('u.sn, u.nickname, u.avatar, ul.name as user_level_name')
      ->leftJoin('user_level ul', 'u.level=ul.id')
      ->where('u.id', $item['transfer_to_id'])->find();
      $item['from_nickname'] = $transferFromInfo['nickname'];
      $item['from_avatar'] = UrlServer::getFileUrl($transferFromInfo['avatar']);
      $item['from_sn'] = $transferFromInfo['sn'];
      $item['from_level_name'] = $transferFromInfo['user_level_name'] ?? '无等级';
      $item['to_nickname'] = $transferToInfo['nickname'];
      $item['to_avatar'] = UrlServer::getFileUrl($transferToInfo['avatar']);
      $item['to_sn'] = $transferToInfo['sn'];
      $item['to_level_name'] = $transferToInfo['user_level_name'] ?? '无等级';
      $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
    }

    $data = [
      'count' => $count,
      'list' => $list
    ];
    return $data;
  }

  public static function adder($user_id){
    return Db::name('user_address')->where('id',$user_id)->find();
  }
  public static function adders($user_id){
    return Db::name('user_address')->where('id',$user_id)->find();
  }

          /**
         * 计算地球上两点之间的距离（根据经纬度）
         *
         * @param float $lon1 地点1的经度
         * @param float $lat1 地点1的纬度
         * @param float $lon2 地点2的经度
         * @param float $lat2 地点2的纬度
         * @param string $unit 单位（'m' 为米，'km' 为千米，默认为 'm'）
         * @return float 两点之间的距离（根据 $unit 返回不同单位的结果）
         */
        public static function haversine_distance($lon1, $lat1, $lon2, $lat2, $unit = 'm')
        {
            // 地球半径，单位：米
            $earthRadius = 6371393;
            // 将经纬度从度数转换为弧度
            $lon1Rad = deg2rad($lon1);
            $lon2Rad = deg2rad($lon2);
            $lat1Rad = deg2rad($lat1);
            $lat2Rad = deg2rad($lat2);
            // 计算经纬度的差值
            $deltaLon = $lon2Rad - $lon1Rad;
            $deltaLat = $lat2Rad - $lat1Rad;

            // 应用 Haversine 公式计算两点之间的距离
            $a = sin($deltaLat / 2) * sin($deltaLat / 2) + cos($lat1Rad) * cos($lat2Rad) * sin($deltaLon / 2) * sin($deltaLon / 2);
            $c = 2 * asin(sqrt($a));
            $distance = $earthRadius * $c;

            // 返回计算结果，根据需要将单位转换为 'm' 或 'km'
            return $unit == 'm' ? $distance : $distance / 1000;
        }

        /**
         *获取用户的列表
         *
         * @param string $unit 单位（'m' 为米，'km' 为千米，默认为 'm'）
         * @return float 两点之间的距离（根据 $unit 返回不同单位的结果）
         */

        public static function userlist(){
             return Db::name('user_address')->order('id desc')->select();
        }

    /**
     * Notes: 
     * @param $id获取会员的数据
     * @param bool $getdata 是否获取原始数据
     * @param bool $expenditure 是否显示会员消费
     * @return User|mixed
     */
    public static function userinfo($id){
        $user=Db::name('user')->where('user_id',$id)->find();
        $user['avatar'] = UrlServer::getFileUrl($user['avatar']);
        $user['birthday']=date("Y-m-d",$user['birthday']);
        return $user;
    }
    /**
     * Notes: 
     * @param $把日期转换称为礼拜
     * @param bool $getdata 是否获取原始数据
     * @param bool $expenditure 是否显示会员消费
     * @return User|mixed
     */

    public static  function Get_Chinese_WeekDay($Join_Date)
    {
         $WeekDay  = date('w', strtotime($Join_Date));
        $WeekList = array('日', '一', '二', '三', '四', '五', '六');
        return '星期' . $WeekList[$WeekDay];
    }


    public static function onedit($post){
       $data=[
         'contact'            =>$post['name'],
         'telephone'          =>$post['phone'],
         'sex'               =>$post['sex'],
         'province_id'          =>$post['first_category_id'],
         'city_id'          =>$post['second_category_id'],
         'district_id'          =>$post['third_category_id'],
         'lng'=>$post['store_latitude'], 
         'lat'=>$post['store_longitude'],
         'areas'          =>$post['areas'],
         'brand_id'          =>$post['brand_id'],
         'pet'          =>$post['pet'],
         'hbl'          =>$post['hbl'],
          'wx'          =>$post['wx'],
         'address'      =>$post['address'],
         'label_id'    =>$post['label_id'],
         'updatetime'          =>time(),          

       ];
       return Db::name('user_address')->where('id',$post['id'])->data($data)->update();

    }
    
     /**
     * Notes: 
     * @param $获取用户访问记录
     * @param bool $getdata 是否获取原始数据
     * @param bool $expenditure 是否显示会员消费
     * @return User|mixed
     */
    public static function Record($post){
         $where=[];
       //访问记录时间
        if(isset($post['start_time']) && $post['start_time']!=''){
            $where[] = ['add_time','>=',strtotime($post['start_time'])];
        }
        if(isset($get['end_time']) && $get['end_time']!=''){
            $where[] = ['add_time','<=',strtotime($post['end_time'])];
        }
        
        
      $list = Db::name('goods_stay_time')
      ->where($where)
      ->page($post['page'], $post['limit'])
      ->order('id', 'desc')
      ->select();
      $count = Db::name('goods_stay_time')->where($where)->count();   
      foreach($list as &$item) {
          $user['mobile']='-';
          $user['nickname']='-';
          $user=Db::name('user')->where('id',$item['uid'])->find();
          $goods=Db::name('goods')->where('id',$item['goods_id'])->find();
          $item['add_time']=date("Y-m-d",$item['add_time']);                   //访问的时
          $end = strtotime($item['add_time'].'23:59:59');       //结束时间
          $ends = strtotime($item['add_time'].'00:00:00');       //结束时间
          $item['order_pay']='-';                                 //支付状态
       //   $order=Db::name('order')->where('mobile',$user['mobile'])->where('create_time','>=', $end-86400)->where('create_time','<=',$end)->find();   //查询订单
      
        $order=Db::name('order')->where('mobile',$user['mobile'])->where('goods_id',$item['goods_id'])->where('create_time','<',$end)->where('create_time','>', $ends)->find();   //查询订单
          if($order){
              $item['order']='是';
              if($order['pay_status']){
                     $item['order_pay']='支付';
              }else{
                 $item['order_pay']='-'; 
              }
          }else{
              $item['order']='-'; 
              $item['order_pay']='-';
          }
          if($user){
              $item['user_name']=$user['nickname'];
              $item['user_mobile']=$user['mobile'];
            }
          
            $coust=Db::name('user_address')->where('telephone', $item['user_mobile'])->find();
            $item['coust_name']='-'; 
            if($coust){
                $item['coust']='是'; 
                $coudsd=Db::name('admin')->where('id',$coust['admin_id'])->find();
                if($coudsd){
                   $item['coust_name']= $coudsd['name'];   
                }
            }else{
                 $item['coust']='-'; 
            }

            $admin=Db::name('goods_add_time')->where('phone', $item['user_mobile'])->find();
            
            if($admin){
                $item['admin']='已跟进';
            }else{
                 $item['admin']='-';
            }
           $item['goods_name']=$goods['name'];
           $item['time']= intval($item['time']/1000);
           
          $recommended=Db::name('user')->where('id',$user['first_leader'])->find();
          if($recommended){
               $item['recommended_name']=$recommended['nickname'];
               $item['recommended_mobile']=$recommended['mobile'];
               $item['recommended_sn']=$recommended['sn'];
               $item['recommended_images']=UrlServer::getFileUrl($recommended['avatar']);
          }
            
      }   
      return ['count'=>$count , 'lists'=>$list];    
    }
    
    
    /**
     * Notes: 
     * @param 线索的更新记录
     * @param bool $getdata 是否获取原始数据
     * @param bool $expenditure 是否显示会员消费
     * @return User|mixed
     */
     
     public static function goods_info($postdd){
       $list = Db::name('goods_add_time')
      ->where('phone',$postdd['phone'])
      ->page($postdd['page'], $postdd['limit'])
      ->order('id', 'desc')
      ->select();
       $count = Db::name('goods_add_time')->where('phone',$postdd['phone'])->count();  
        foreach($list as &$item) {
            $coudsd=Db::name('admin')->where('id',$item['admin_id'])->find(); 
            if($coudsd){
                $item['coust_name']= $coudsd['name'];  
            }
             $item['add_time']=date("Y-m-d:H:i:s",$item['add_time']);                   //访问的时
             
           
             
            
        }
       
       return ['count'=>$count , 'lists'=>$list];        
     }


}