<?php

namespace App\Models;

use App\Traits\ModelTrait;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class Media extends Model
{
    use ModelTrait;

    protected $table = 'media';

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    protected $casts = [
        'meta' => 'array',
    ];

    /**
     * 获取列表
     * @param array $where
     * @param string $orderName
     * @param string $order
     * @param int $pageSize
     * @return mixed
     * @throws \Exception
     */
    public static function lists($where = [], $orderName = 'id', $order = 'DESC', $pageSize = 30)
    {
        $where = collect($where);
        $query = self::query();

        if ($type = $where->get('type')) {
            $query->whereIn('type', explode('-', $type));
        }

        if ($fileName = $where->get('file_name')) {
            $query->where('file_name', 'like', "%{$fileName}%");
        }

        $where->has('delete') && $where->get('delete') ? $query->where('deleted_at', '>', 0) : $query->where('deleted_at', 0);

        if ($lastId = $where->get('last_id')) {
            $query->where('id', '<', $lastId);
        }

        return $query->orderBy($orderName, $order)->limit($where->get('limit', $pageSize))->get();
    }

    /**
     * 获取文件管理列表
     * @param array $where
     * @param string $orderName
     * @param string $order
     * @param int $pageSize
     * @return mixed
     * @throws \Exception
     */
    public static function fileList($where = [], $orderName = 'id', $order = 'DESC', $pageSize = 36)
    {
        $where = collect($where);
        $query = self::query();

        if ($type = $where->get('type')) {
            $query->whereIn('type', explode('-', $type));
        }

        if ($fileName = $where->get('file_name')) {
            $query->where('file_name', 'like', "%{$fileName}%");
        }

        $where->has('delete') && $where->get('delete') ? $query->where('deleted_at', '>', 0) : $query->where('deleted_at', 0);

        $data  = $query->orderBy($orderName, $order)->paginate($where->get('limit', $pageSize));
        $sizes = self::select('type', DB::raw('SUM(size) as total_size '))->groupBy('type')->get()->pluck('total_size', 'type');

        return compact('data', 'sizes');
    }
}
