<?php

namespace Modules\Statistic\Http\Controllers;

use Carbon\Carbon;
use Catch\Base\CatchController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\User\Http\Controllers\UserTrait;
use Modules\Statistic\Models\VideoStatByCompany;

/**
 * 短剧统计
 */
class VideoStatController extends CatchController
{

    use UserTrait;
    public function __construct(protected readonly VideoStatByCompany $videoStatByCompany)
    {
        
    }

    public function index(Request $request)
    {
        
        if(!$this->isCompanyManager()){
            return [];
        }

        $limit = $request->get('limit',15);
        $is_export = $request->get('is_export');
        $where = $this->requestParam($request);
        if($is_export){
            $result = $this->videoStatByCompany->where($where)->select('day','video_name','video_id','amount','charge_count','charge_user_num','play_count')->get();
        }else{
            $result = $this->videoStatByCompany->where($where)->select('day','video_name','video_id','amount','charge_count','charge_user_num','play_count')->paginate($limit);
        }
        return $result;
    }


    public function stats(Request $request){
        $stats_obj = [
            'amount'=>0,
            'charge_count'=>0,
            'charge_user_num'=>0
        ];
        if(!$this->isCompanyManager()){
            return  $stats_obj;
        }
        $where = $this->requestParam($request);
        $stats = $this->videoStatByCompany->where($where)->select(DB::raw('sum(amount) as amount,sum(charge_count) as charge_count,sum(charge_user_num) as charge_user_num'))->first();
        if($stats){
            $stats_obj = [
                'amount'=>$stats->amount,
                'charge_count'=>$stats->charge_count,
                'charge_user_num'=>$stats->charge_user_num
            ];
        }
        return $stats_obj;
    }

    private function requestParam(Request $request){
        $default_end_time = Carbon::now();
        $user_id = $this->getLoginUser()->id;
        $video_name = $request->get('video_name');
        $start_date = $request->get('start_date');
        $end_date = $request->get('end_date');
        
        if(!$end_date){
            $end_date = $default_end_time;
        }else{
            $end_date = Carbon::createFromTimeString($end_date.' 00:00:00');
        }

        if($start_date){
            $start_date = Carbon::createFromTimeString($start_date.' 00:00:00');
        }else{
            $start_date = $end_date->clone()->subDays(7);
        }

        $where = [
            ['user_id','=',$user_id],
            ['is_delete','=',0],
            ['day','>=',$start_date->format('Y-m-d')],
            ['day','<=',$end_date->format('Y-m-d')]
        ];
        
        if(trim($video_name)){
            $where[] = ['video_name','like','%'.trim($video_name).'%'];
        }
        return $where;
    }

 
}
