<?php

namespace app\admin\logic;

use app\common\model\DistributionOrder;
use app\common\model\OrderGoods;
use app\common\model\Pay;
use app\common\server\UrlServer;
use app\common\model\Withdraw;
use think\Db;

class FinanceLogic
{
    public static function lists()
    {
        //本月订单金额
        $month_order_amount = Db::name('order')
            ->where(['pay_status' => Pay::ISPAID, 'refund_status' => OrderGoods::REFUND_STATUS_NO])
            ->whereTime('create_time', 'month')
            ->sum('order_amount');

        //订单总金额
        $order = Db::name('order')
            ->field('sum(order_amount) as amount, count(id) as num')
            ->where('pay_status' , 'in', [Pay::ISPAID, Pay::REFUNDED])
            ->find();

        //退款订单
        $refund_order = Db::name('order_refund')
            ->field('sum(refund_amount) as amount, count(id) as num')
            ->where(['refund_status' => 1])
            ->find();

        //会员相关
        $user = Db::name('user')
            ->field('sum(user_money) as money, sum(user_integral) as integral, sum(earnings) as earnings')
            ->where(['del' => 0])
            ->find();

        //已提现佣金
        $have_withdraw_earnings = Db::name('withdraw_apply')
            ->where(['status' => Withdraw::STATUS_SUCCESS])
            ->sum('money');

        //提现中
        $wait_withdraw_earnings = Db::name('withdraw_apply')
            ->where(['status' => Withdraw::STATUS_ING])
            ->sum('money');


        //本月分销佣金金额
        $month_earnings = Db::name('distribution_order_goods')
            ->where('status', '<>', DistributionOrder::STATUS_ERROR)
            ->whereTime('create_time', 'month')
            ->sum('money');

        //分销佣金总佣金
        $distribution_earnings = Db::name('distribution_order_goods')
            ->where('status', '<>', DistributionOrder::STATUS_ERROR)
            ->sum('money');

        return [
            'month_order_amount' => round($month_order_amount, 2),
            'total_amount' => round($order['amount'], 2),
            'order_num' => $order['num'] ?? 0,
            'refund_amount' => round($refund_order['amount'], 2),
            'refund_num' => $refund_order['num'] ?? 0,

            'total_user_money' => round($user['money'], 2),
            'total_user_integral' => $user['integral'] ?? 0,
            'able_earnings' => round($user['earnings'], 2),
            'have_withdraw_earnings' => round($have_withdraw_earnings, 2),

            'month_earnings' => round($month_earnings, 2),
            'distribution_earnings' => round($distribution_earnings, 2),
            'wait_earnings' => round($wait_withdraw_earnings, 2),
        ];
    }

   public static function acctypelist($get){
        $user_count = Db::name('finance_type')
        ->count();
        $user_list = Db::name('finance_type')
            ->page($get['page'],$get['limit'])
            ->select();
        foreach ($user_list as &$item){
        $item['time']=date("Y-m-d H:i:s",$item['time']);
        }
        return ['count'=>$user_count , 'lists'=>$user_list];   
   }

   public static function acctypeadd($post){
        $data = [
            'name'                =>$post['name'],
            'time'         =>time(),           
        ];
        return Db::name('finance_type')->data($data)->insert();
   }

    public static function typelist(){
        return Db::name('finance_type')->select();
    }
    //
    public static function add($post){
        $post['create_time']=time();
        $post['user_id']=$post['order_id'];
        return Db::name('finance')->insert($post);
    } 
    //
    public static function fidlists($get){
        $where=[];
        if (isset($get['staffid']) && $get['staffid']) {
            $where[] = ['user_id','=',$get['staffid']];
        }
        if (isset($get['type']) && $get['type']) {
            $where[] = ['brand_id','=',$get['type']];
        }
        
       //注册时间
        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'])];
        }
        $fidlists = Db::name('finance')->where($where)
             ->count();
        $fidlists_list = Db::name('finance')
            ->where($where)
            ->page($get['page'],$get['limit'])
            ->order('id desc')
            ->select();
        foreach ($fidlists_list as &$item){
           $item['create_time']=date("Y-m-d H:i:s",$item['create_time']);
           $staff=Db::name('order_exe')->where('id',$item['order_id'])->find();  //获取订单的基本信息
           if($staff){
                $item['time']=date('Y-m-d',$staff['autotime']);
                $order=Db::name('order')->where('order_sn',$staff['order_sn'])->find();  //获取主订单信息
                      
               if($order){
                 $item['adder']=$order['address'];  
               }
                          $goods=Db::name('goods')->where('id',$staff['goods_id'])->find();  //判断套餐名称
               if($goods){
                   $item['goods_name']=$goods['name'];
               }
                         $user=Db::name('staff')->where('id', $staff['staff_id'])->find();    //判断员工信息
          if($user){
              $item['staff_name']=$user['name'];
              $item['staff_phone']=$user['mobile'];
          }
          $admin=Db::name('admin')->where('id',$order['admin_id'])->find();
          if($admin){
                $item['admin_name']=$admin['name'];
          }
                
           $type=Db::name('finance_type')->where('id',$item['brand_id'])->find();
           if($type){
               $item['type_name']=$type['name'];
           }
           }





           
        }
        return ['count'=>$fidlists , 'lists'=>$fidlists_list];   
    }
    //
    public static function info($id){
        $info['base'] = Db::name('finance')
        ->where(['id' => $id])
        ->withAttr('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_avatar','abs_video'])->find();
       return $info;
    }

    public static function eidt($post){
        return Db::name('finance')->where('id',$post['id'])->data($post)->update();
    
    }
    
    public static function stafftime($get){
           $where=[];
            if (isset($get['staffid']) && $get['staffid']) {
               $where[]=['user_id','=',$get['staffid']];
            }
            if (isset($get['pay_status']) && $get['pay_status']) {
                $where[] = ['pay_status','=',$get['pay_status']];
            }
            if (isset($get['admin_id']) && $get['admin_id']) {
                $where[] = ['admin_id','=',$get['admin_id']];
            }
            if(isset($get['name']) && $get['name'] != ''){
                 $where[] = ['name', 'like', '%' . $get['name'] . '%'];
            }
            if(isset($get['phone']) && $get['phone'] != ''){
                     $where[] = ['phone', 'like', '%' . $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'])];
            }
            
            
            $fidlists = Db::name('order_timeadd')->where($where)
                 ->count();
              $fidlists_list = Db::name('order_timeadd')
              ->where($where)
             ->page($get['page'],$get['limit'])
             ->order('id desc')
             ->select();
            foreach ($fidlists_list as &$item){
               $item['create_time']=date("Y-m-d H:i:s",$item['create_time']);
               $staff=Db::name('order_exe')->where('id',$item['orderid'])->find();  //获取订单的基本信息
               if(!empty($staff)){
                    $item['order_id']=$staff['id'];
                    $item['order_name']=$staff['name'];
                    $item['order_phone']=$staff['phone'];
                    $item['order_time']=date('Y-m-d',$staff['autotime']);
                    $user=Db::name('staff')->where('id', $staff['staff_id'])->find();
               if($user){
                  $item['staff_name']=$user['name'];
                  $item['staff_phone']=$user['mobile'];
               }else{
                  $item['staff_name']='-';
                  $item['staff_phone']='-'; 
               }
               }

               $admin=Db::name('admin')->where('id',$item['admin_id'])->find();
               if(!empty($admin)){
                    $item['admin_name']=$admin['name'];  
               }
               


               if($item['admin_id']=='0'){
                   $user_adder=Db::name('user_address')->where('telephone',$staff['phone'])->find();
                   if($user_adder){
                                          $date=Db::name('order_timeadd')->where('id',$item['id'])->update(['admin_id'=>$user_adder['admin_id'],'name'=>$staff['name'],'phone'=>$staff['phone']]);
                   }

               }
             
     
        }
        
        return ['count'=>$fidlists , 'lists'=>$fidlists_list];   
    }
    
    public static function stafftimeinfo($id){
          return Db::name('order_timeadd')->where('id',$id)->find();
    }
    
    public static function editaddtimup($post){
        if($post['pay_type']==1){
        
            return Db::name('order_timeadd')->where('id',$post['id'])->update(['pay_type'=>1]);
        }
        if($post['pay_type']==0){
            
             return Db::name('order_timeadd')->where('id',$post['id'])->update(['pay_type'=>0,'pay'=>$post['pay']]);
        }

     }





}