<?php

namespace app\admin\logic;
use app\common\logic\AccountLogLogic;
use app\common\server\UrlServer;
use think\Db;
use think\Exception;

class StaffLogic{
    /**
     * 显示查询列表的内容
     * @param $get
     * @return array
     */
    public static function lists($get){
        $where = [];

        //判断离职
        if(isset($get['type']) && intval($get['type'])==1){
             $where[] = ['onwork','=',0];
         }
         //判断行政部
        if(isset($get['type']) && intval($get['type'])==5){
             $where[] = ['onwork','=',1];
             $where[] = ['group_id','=',17];
         }
         //判断客服部
        if(isset($get['type']) && intval($get['type'])==4){
             $where[] = ['onwork','=',1];
             $where[] = ['group_id','=',8];
         }
         //保洁部门
        if(isset($get['type']) && intval($get['type'])==6){
             $where[] = ['onwork','=',1];
             $where[] = ['group_id','=',10];
         }
        //做饭部
        if(isset($get['type']) && intval($get['type'])==3){
             $where[] = ['onwork','=',1];
             $where[] = ['group_id','=',15];
         }
         //工程部
        if(isset($get['type']) && intval($get['type'])==2){
             $where[] = ['onwork','=',1];
             $where[] = ['group_id','=',16];
         } 
        //收纳部
        if(isset($get['type']) && intval($get['type'])==7){
             $where[] = ['onwork','=',1];
             $where[] = ['group_id','=',18];
         } 
        //财务部
        if(isset($get['type']) && intval($get['type'])==8){
             $where[] = ['onwork','=',1];
             $where[] = ['group_id','=',21];
         } 
                 //财务部
        if(isset($get['type']) && intval($get['type'])==9){
             $where[] = ['onwork','=',1];
             $where[] = ['group_id','=',19];
         } 
         
        //财务部
        if(isset($get['type']) && intval($get['type'])==10){
             $where[] = ['onwork','=',1];
             $where[] = ['group_id','=',22];
         } 
         
        if(isset($get['id']) && $get['id'] != ''){
            $where[] = ['id','=',$get['id']];
        }
        //根据姓名查询
        if(isset($get['name']) && $get['name'] != ''){
            $where[] = ['name', 'like', '%' . $get['name'] . '%'];
        }
        //手机号码查询
        if(isset($get['mobile']) && $get['mobile'] != ''){
            $where[] = ['mobile', 'like', '%' . $get['mobile'] . '%'];
        }
        //地区查询
        if(isset($get['area_id']) && $get['area_id'] != ''){
            $where[] = ['area','=',$get['area_id']];
        }
        //是否结婚查询
        if(isset($get['marry']) && $get['marry'] != ''){
            $where[] = ['marry','=',$get['marry']];
        }
        //是否过敏
        if(isset($get['allergy']) && $get['allergy'] != ''){
            $where[] = ['allergy','=',$get['allergy']];
        }
         //员工性别
        if(isset($get['sex']) && $get['sex'] != ''){
            $where[] = ['sex','=',$get['sex']];
        } 
        //是否在职查询
        if(isset($get['onwork']) && $get['onwork'] != ''){
             $where[] = ['onwork','=',$get['onwork']];
        }   
        //分组查询
        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[] = ['createtime','>=',strtotime($get['start_time'])];
        }
        if(isset($get['end_time']) && $get['end_time']!=''){
            $where[] = ['createtime','<=',strtotime($get['end_time'])];
        }

        $user_count = Db::name('staff')
                    ->where($where)
                    ->count();
        $user_list = Db::name('staff')
                    ->where($where)
                    ->field('password,pay_password,salt',true)
                    ->page($get['page'],$get['limit'])
                    ->order('id desc')
                    ->select();
        //员工分组
        $user_group = Db::name('staff_group')->column('name','id');
        foreach ($user_list as &$item){
            if(isset($user_group[$item['group_id']])){
                $item['group_name'] = $user_group[$item['group_id']];
            }
            $user=Db::name('user')->where('id', $item['user_id'])->find();                 //获取用户的基本信息
            if($user){
                $item['abs_avatar']=UrlServer::getFileUrl($user['avatar']);
                $item['updatetime']=date("Y-m-d H:i:s",$item['updatetime']);  
                            
            // 用户的出生日期
               $birthday = date("Y-m-d",$user['birthday']);
            // 获取当前日期
             $currentDate = date('Y-m-d');
            // 计算出生日期到当前日期的时间差
             $diff = date_diff(date_create($birthday), date_create($currentDate));
            // 获取年龄
              $item['age']= $diff->format('%y');
                }else{
                   $item['abs_avatar']='-';
                    $item['updatetime']='-';
                    $item['age']='-';
                 }
        }
        return ['count'=>$user_count , 'lists'=>$user_list];
    }
    /**
     * 显示员工分组
     * @param $get
     * @return array
     */
    public static function staff_bellistgoic($get){
        $user_count = Db::name('staff_group')
                    ->count();
        $user_list = Db::name('staff_group')
                    ->page($get['page'],$get['limit'])
                    ->select();
        foreach ($user_list as &$item){
            $item['createtime']=date("Y-m-d H:i:s",$item['createtime']);

        }
                 
         return ['count'=>$user_count , 'lists'=>$user_list];             
    }
    /**
     * 获取到员工部门
     * @param $get
     * @return array
     */
    public static function staff_bellist(){
        return Db::name('staff_group')->select();
    }
    /**
     * 根据获取员工部门的信息
     * @param $get
     * @return array
    */
    public static function staff_beliinfo($id){
           return Db::name('staff_group')->where('id',$id)->find();
    }
    
    public static function staff_beedit($get){
        
        return Db::name('staff_group')->where(['id'=>$get['id']])->update(['name'=>$get['name'],'rloe'=>$get['auth_ids']]);
    }
    /**
     * 增加员工分组
     * @param $get
     * @return array
     */
    public static function staff_beeadd($get){
        return Db::name('staff_group')->data(['name'=>$get['name']])->insert();
    }

    /**
     * 删除员工分组
     * @param $get
     * @return array
     */
    public static function staff_beedel($id){
        return Db::name('staff_group')->where('id',$id)->delete();
    }

    /**
     * 员工类型列表
     * @param $get
     * @return array
     */
    public static function staff_typelist($get){
        $user_count = Db::name('staff_type')->count();
        $user_list = Db::name('staff_type')
                ->page($get['page'],$get['limit'])
                ->select();
        foreach ($user_list as &$item){
        $item['createtime']=date("Y-m-d H:i:s",$item['createtime']);
        }    
        return ['count'=>$user_count , 'lists'=>$user_list]; 
    }
    /**
     * 员工类型增加方法
     * @param $get
     * @return array
     */
    public static function staff_typeadd($post){
        return Db::name('staff_group')->where(['id'=>$post['id']])->update(['name'=>$get['name']]);
    }

    /**
     * 修改员工的服务类别
     * @param $get
     * @return array
     */
    public static function staff_typeedit($post){
        return Db::name('staff_type')->where(['id'=>$post['id']])->update(['name'=>$post['name']]);
    }
    /**
     * 删除员工服务类别
     * @param $get
     * @return array
     */
    public static function staff_typedel($id){
        return Db::name('staff_type')->where('id',$id)->delete();
    }
    /**
     * 获取员工的类别
     * @param $get
     * @return array
     */
    public static function type(){
        return Db::name('staff_type')->field('id,name')->select();
    }
    /**
     * 获取员工的分组
     * @param $get
     * @return array
     */
    public static function staff_beed(){
        return Db::name('staff_group')->field('id,name')->select();
       
    }
    /**
     * 员工地区的分类
     * @param $get
     * @return array
     */
     
    public static function goods_type(){
           return Db::name('goods_brand')->field('id,name')->where('del',0)->where('id','<>',5)->select();
    }
     
    public static function getAllTree()
    {
        $lists = Db::name('dev_region')
            ->field(['name', 'id', 'parent_id', 'level'])
            ->order(['parent_id' => 'desc'])
            ->select();
        return $lists;
    }
    /**
     * 增加新的员工
     * @param $get
     * @return array
     */

    public static function  add($post){
        $now = time();
        $post['createtime'] = $now;
        $post['updatetime'] = $now;
        return Db::name('staff')->insertGetId($post);
      
    }
    /*
     * 员工基本信息
     */
    /**
     * 员工基本信息
     * @param $goods_id
     * @return array
     */
    public static function info($id)
    {
        $info['base'] = Db::name('staff')
            ->where(['id' => $id])
            ->withAttr('abs_image', function ($value, $data) {
                return UrlServer::getFileUrl($data['image']);
            })
            ->withAttr('content', function ($value){
                $preg = '/(<img .*?src=")[^https|^http](.*?)(".*?>)/is';
                $local_url = UrlServer::getFileUrl('/');
                return  preg_replace($preg, "\${1}$local_url\${2}\${3}",$value);
            })
            ->append(['abs_image','abs_video'])->find();
            
        return $info;
    }
    /**
     * 修改员工的基础信息
     * @param $id   员工的ID
     * @return array
     */
    public static function edits($post){
        $data = [
                'updatetime' => time(),
                'name'=>$post['name'],
                'mobile'=>$post['mobile'],
                'sex'=>$post['sex'],
                'identity'=>$post['identity'],
                'nation'=>$post['nation'],
                'group_id'=>$post['brand_id'],
                'goods_id'=>$post['goods_id'],
                'lng'=>$post['store_latitude'],
                'addr'=>$post['addr'],
                'lat'=>$post['store_longitude'],
                'onwork'=>$post['onwork'],
                'remark'=>$post['remark'],
                'first_category_id'=>$post['first_category_id'],
                'second_category_id'=>$post['second_category_id'],
                'third_category_id'=>$post['third_category_id'],
                'jon'=>$post['jon'],
                'education'=>$post['education'],
                'urgent_name'=>$post['urgent_name'],
                'urgent_phone'=>$post['urgent_phone'],
                'birthday'=>$post['birthday'],
                'marry'=>$post['marry'],
                'native'=>$post['native'],
                'mooney'=>$post['mooney'],
                'score'=>$post['score'],
                'star'=>$post['star'],
                'bank'=>$post['bank'],
                'physical'=>$post['physical'],
                'account'=>$post['account'],
                'sbyhk'=>$post['sbyhk'],
                'social'=>$post['social'],
                'sign'=>$post['sign'],
                'transit'=>$post['transit'],
                'security'=>$post['security'],
                'insurances'=>$post['insurances'],
                'password'=>md5(md5($post['password'])),
                'type'=>$post['type'],
                'uid'=>$post['uid'],
                'lnglat'=>$post['lnglat'],
                'grouping_id'=>$post['grouping_id']
                

            ];
        $list=Db::name('staff')->where('id',$post['goodss_id'])->data($data)->update();
        return $list;
    }
    
    
    //获取在职所有的员工
    public static  function sfaffinfo($id){
        $where=[];
        $where[] = ['id','=', $id];
        $where[] = ['onwork','=','1'];
        return Db::name('staff')->where($where)->find();
    }
     //获取所有的员工内容
    public static function infostaff($id){
        $where=[];
        $where[] = ['id','=', $id]; 
         return Db::name('staff')->where($where)->find();
    }

    //获取员工的列表
    public static function stafflist(){
        return Db::name('staff')->where('onwork',1)->select();
    }
    //获取员工的分组
    public static function grouping(){
           return Db::name('staff_grouping')->select();
    }
    //根据员工ID查询请假
    public static function havestaff($time){
        return $time;
    }
  
     //员工分组内容

    public static function group_list($post){
        $count=Db::name('staff_grouping')->count();
        $lists=Db::name('staff_grouping')
        ->page($post['page'],$post['limit'])
        ->select();
        foreach ($lists as &$item){
                $item['create_time']=date("Y-m-d H:i:s",$item['create_time']);
        }  
        return ['count'=>$count , 'lists'=>$lists];  

    }
    
    //员工端口最新公告
    public static function staff_notice($get){
        $count=Db::name('staff_notice')->count();
        $lists=Db::name('staff_notice')
        ->page($get['page'],$get['limit'])
        ->select();
        foreach ($lists as &$item){
                $item['time']=date("Y-m-d H:i:s",$item['time']);
        }  
        return ['count'=>$count , 'lists'=>$lists];  
        
    }
    
    //增加员工端口公告
    public static function  staff_noticeadd($post){
        $post['time']=time();
        $inser=Db::name('staff_notice')->data($post)->insert();
        return $inser;
    }
    
    //修改员工端公告
    public static function staff_noticedit($get){
        $renewal=Db::name('staff_notice')->where('id',$get['id'])->update(['title'=>$get['title'],'connect'=>$get['connect'],'introduction'=>$get['introduction'],'time'=>time()]);
        return $renewal;
    }
    
    
    public static function wages($get){
        $where=[];
        $whereOrdertime=[];
        $findtime=[];
        $currentDate = date('Y-m-d');
        $firstDayOfLastMonth = date('Y-m-01', strtotime('-1 month', strtotime($currentDate)));
        $daysInLastMonth = date('t', strtotime($firstDayOfLastMonth));

        $current_timestamp = time();                     //当前时间戳
        $wherestaff=[];
        if(isset($get['staff_id']) && $get['staff_id'] != ''){
            $wherestaff[]=['id','=',$get['staff_id']]; 
        }
        if(isset($get['phone']) && $get['phone'] != ''){
             $wherestaff[]=['mobile','=',$get['phone']]; 
        }
        if(isset($get['type']) && $get['type'] != ''){
             $wherestaff[]=['goods_id','=',$get['type']]; 
        }
        //增加时间
        if(isset($get['start_time']) && $get['start_time']!=''){
           
            $data=date('Y-m',strtotime($get['start_time']));
            $start_of_last_month = strtotime($data . '-01');
            
            $lastday = date('Y-m-d', strtotime("$data +1 month -1 day"));
            $end_of_last_month=strtotime($lastday);
            
            $whereOrdertime[]=['autotime','>=',$start_of_last_month];
            $whereOrdertime[]=['autotime','<=',$end_of_last_month];
           
           $findtime[]=['create_time','>=',$start_of_last_month];
           $findtime[]=['create_time','<=',$end_of_last_month];
            
           
        }else{
            $now = time();
            $start_of_last_month = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month', $now)));
            $end_of_last_month = strtotime("last day of last month", $current_timestamp); //上一个月结束时间搓
      
           $whereOrdertime[]=['autotime','>=',$start_of_last_month];
           $whereOrdertime[]=['autotime','<=',$end_of_last_month];
           
           $findtime[]=['create_time','>=',$start_of_last_month];
           $findtime[]=['create_time','<=',$end_of_last_month];

        }
       
        
       $count = Db::name('staff')
                    ->where($wherestaff)
                    ->where('onwork',1)
                    ->count();
       $lists = Db::name('staff')
                    ->where($wherestaff)
                    ->where('onwork',1)
                    ->page($get['page'],$get['limit'])
                    ->order('id desc')
                    ->select();
                    
        foreach ($lists as &$item){
             $order_exe=Db::name('order_exe')->where('staff_id',$item['id'])->where($whereOrdertime)->where('staff_status',3)->select(); //获取当月的订单
             //统计总订单
             $item['total_orders']=Db::name('order_exe')
                                ->where('staff_id',$item['id'])
                                ->where($whereOrdertime)
                                ->where('staff_status',3)
                                ->count();
            //上午订单               
            $item['sw_orders']=Db::name('order_exe')
                                ->where('staff_id',$item['id'])
                                ->where($whereOrdertime)
                                ->where('staff_status',3)
                                ->where('addtime',1)
                                ->count();
            //下午 
            $item['xw_orders']=Db::name('order_exe')
                                ->where('staff_id',$item['id'])
                                ->where($whereOrdertime)
                                ->where('staff_status',3)
                                ->where('addtime',2)
                                ->count();
            //财务报销
            $item['finance']=Db::name('finance')
                                ->where('user_id',$item['id'])
                                ->whereTime('create_time','last month')
                                ->where('status',2)
                                ->sum('pay');
                         
             //上午加时                 
            $item['sw_addtime']=Db::name('order_exe a')
                              ->join('order_timeadd u','u.orderid=a.id')
                              ->where('a.staff_id',$item['id'])
                              ->where('a.autotime','>=',$start_of_last_month)
                              ->where('a.autotime','<=',$end_of_last_month)
                              ->where('u.status',2)
                              ->where('a.addtime',1)
                              ->sum('minute');
                              
            $item['sw_addtimes']=$item['sw_addtime']/60;                  
            $item['xw_addtime']=Db::name('order_exe a')
                              ->join('order_timeadd u','u.orderid=a.id')
                              ->where('a.staff_id',$item['id'])
                              ->where('a.autotime','>=',$start_of_last_month)
                              ->where('a.autotime','<=',$end_of_last_month)
                              ->where('u.status',2)
                              ->where('a.addtime',2)
                              ->sum('minute');                  
            $item['xw_addtimes']=round($item['xw_addtime']/60,2); 
             
            //请假
            $item['leave']=Db::name('leavesd')
                            ->where('staff_id',$item['id'])
                            ->where('time','>=',$start_of_last_month)
                            ->where('time','<=',$end_of_last_month)
                            ->where('status',1)
                            ->where('addtime','<>',2)
                            ->count();
            $number=Db::name('leavesd')
                            ->where('staff_id',$item['id'])
                            ->where('time','>=',$start_of_last_month)
                            ->where('time','<=',$end_of_last_month)
                            ->where('status',1)
                            ->where('addtime',2)
                            ->count();                
            $item['leaves']= $item['leave']/2+$number;                
                              
            $item['attendance']=$daysInLastMonth-$item['leaves'];   
             
            $item['fine']=Db::name('fine')
                                ->where('staff_id',$item['id'])
                                ->where('create_time','>=',$start_of_last_month)
                                ->where('create_time','<=',$end_of_last_month)
                                ->sum('score');
                              
            //异常订单       
            $item['abnormal']=Db::name('order_abnormal')
                                ->where('staff_id',$item['id'])
                                ->where('create_time','>=',$start_of_last_month)
                                ->where('create_time','<=',$end_of_last_month)
                                ->count();
                    
            $item['annual']=Db::name('order_exe a')
                              ->join('order u','u.order_sn=a.order_sn')
                              ->where('a.staff_id',$item['id'])
                              ->where('a.autotime','>=',$start_of_last_month)
                              ->where('a.autotime','<=',$end_of_last_month)
                              ->where('u.number','>',9)
                              ->count();
            $item['erp_staff']=Db::name('erp_staff')
                                ->where('staff_id',$item['id'])
                                ->where('status',2)
                                ->where('create_time','>=',$start_of_last_month)
                                ->where('create_time','<=',$end_of_last_month)
                                ->sum('number');                   
        }
        return ['count'=>$count , 'lists'=>$lists]; 
        
    }
    
 
    
    
    
    public static function wagesdel($post){
        return Db::name('staff_wages')->where('id',$post)->delete();
    }
    
    public static function serverstaff(){
        return Db::name('staff')->where('onwork',1)->where('type',0)->select(); 
    }
    
    public  static function goods_brand(){
        return Db::name('goods_brand')->where('id','<>',5)->select();  
    }
    
    public static function adder($post){
        return Db::name('staff')->where('id',$post['id'])->update(['lng'=>$post['store_longitude'],'lat'=>$post['store_latitude']]);
    }
    
    //获取员工积分记录
    public static function points($get){
        $where=[];
        if(isset($get['mobile']) && $get['mobile'] != ''){
            $where[] = ['mobile', 'like', '%' . $get['mobile'] . '%'];
        }
        $user_count = Db::name('staff_points')
                    ->where($where)
                    ->count();
        $user_list = Db::name('staff_points')
                    ->where($where)
                    ->page($get['page'],$get['limit'])
                    ->order('id desc')
                    ->select();
         foreach ($user_list as &$item){
              $staff=Db::name('staff')->where('id',$item['staff_id'])->find();
              if($staff){
                 $item['staff_name']=$staff['name'];
                 $item['staff_mobile']=$staff['mobile'];
                 $item['staff_number']=$staff['number'];
              }
                $item['add_time']=date("Y-m-d H:i:s",$item['add_time']);
         }
        return ['count'=>$user_count , 'lists'=>$user_list];
    }
    //根据部门ID获取到
    
    public static function infolist($get){
     $count=Db::name('staff_grouping')
    ->alias('s')
    ->join('staff sg', 's.id = sg.grouping_id')
    ->where('sg.onwork',1)
     ->where('s.id',$get['id'])
    ->count();   
    $result = Db::name('staff_grouping')
    ->alias('s')
    ->join('staff sg', 's.id = sg.grouping_id')
    ->where('sg.onwork',1)
    ->where('s.id',$get['id'])
    ->page($get['page'],$get['limit'])
    ->select(); 
     return ['count'=>$count , 'list'=>$result];
        
    }
    
}