<?php

namespace App\Http\Controllers\Admin;

use Carbon\Carbon;
use App\Models\Media;
use Illuminate\Http\Request;
use App\Services\Oss\UploadManager;

class MediaController extends AdminController
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function index(Request $request)
    {
        $where = $request->except('page');
        $data = Media::fileList($where);
        return view('admin.media.media', compact('data', 'where'));
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function lists(Request $request)
    {
        $media = Media::lists($request->except('page'));

        return response()->json($media);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @param UploadManager $up
     * @return \Illuminate\Http\Response
     * @throws \OSS\Core\OssException
     * @throws \OSS\Http\RequestCore_Exception
     */
    public function destroy($id, UploadManager $up)
    {
        $media = Media::whereIn('id', array_str($id))->get();

        if ($media->isEmpty()) {
            return $this->error('资源不存在！');
        }

        $deleteAt = Carbon::now()->timestamp;

        $ids  = $media->pluck('id');

        $result = Media::whereIn('id', $ids)->update(['deleted_at' => $deleteAt]);

        if ($result) {
            return response()->json(['status' => 'success']);
        }

        return response()->json(['status' => 'error']);
    }

    public function recover($id)
    {
        $media = Media::where('id', $id)->first();

        if (is_null($media)) {
            return $this->error('资源不存在！');
        }

        if ($media->deleted_at == 0) {
            return $this->error('媒体资源已恢复！');
        }

        $result = $media->update(['deleted_at' => 0]);

        if ($result) {
            return response()->json(['status' => 'success']);
        }

        return response()->json(['status' => 'error']);

    }
}
