<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service\admin\media;

use app\repository\media\MediaFileRepository;
use app\repository\media\MediaGroupRepository;
use app\service\RequestHelper;
use app\service\admin\BaseAdminService;
use app\service\domain\media\CoreMediaService;
use think\facade\Log;
use think\Request;


/**
 * Media Service
 * @package app\service\admin\media
 */
class MediaService extends BaseAdminService
{

    /**
     * 上传媒体文件
     * @param Request $request 请求对象
     * @return array
     */
    public function upload(Request $request): array
    {
        $uid = $request->uid ?? null;
        if (!$uid) {
            return ['code' => 401, 'msg' => '', '_http_status' => 401];
        }

        $file = $this->getUploadFiles($request);
        $type = trim((string)$request->post('type', ''));
        $groupId = $this->core()->normalizeGroupId((int)$request->post('group_id', 0));

        if (!$file) {
            return ['code' => 1, 'msg' => ''];
        }

        try {
            if (is_array($file)) {
                $items = [];
                foreach ($file as $one) {
                    $items[] = $this->core()->saveUpload($one, $type, $groupId);
                }
                return ['code' => 0, 'msg' => '', 'data' => ['items' => $items]];
            }

            return ['code' => 0, 'msg' => '', 'data' => $this->core()->saveUpload($file, $type, $groupId)];
        } catch (\RuntimeException $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        } catch (\Throwable $e) {
            Log::error('admin media upload failed: ' . $e->getMessage(), [
                'type' => $type,
                'group_id' => $groupId,
                'uid' => $uid,
                'exception' => get_class($e),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ]);
            return ['code' => 1, 'msg' => $this->app->isDebug() ? $e->getMessage() : ''];
        }
    }


    /**
     * 媒体文件分页列表
     * @param Request $request 请求对象
     * @return array
     */
    public function list(Request $request): array
    {
        return [
            'code' => 0,
            'data' => $this->fileRepository()->paginate([
                'keyword' => $request->get('keyword', ''),
                'type' => $request->get('type', ''),
                'group_id' => $request->get('group_id'),
            ], RequestHelper::parseLimit($request, 'limit', 10, 100)),
        ];
    }


    /**
     * 删除媒体文件
     * @param Request $request 请求对象
     * @return array
     */
    public function delete(Request $request): array
    {
        return $this->core()->delete((int)$request->post('id', 0));
    }


    /**
     * 批量删除媒体文件
     * @param Request $request 请求对象
     * @return array
     */
    public function deleteBatch(Request $request): array
    {
        $ids = $request->post('ids');
        if (!is_array($ids)) {
            return ['code' => 1, 'msg' => ''];
        }

        return $this->core()->deleteBatch($ids);
    }


    /**
     * 获取媒体分组列表
     * @return array
     */
    public function groupList(): array
    {
        return ['code' => 0, 'data' => $this->groupRepository()->listAll()];
    }


    /**
     * 新增或更新媒体分组
     * @param Request $request 请求对象
     * @return array
     */
    public function groupSave(Request $request): array
    {
        return $this->core()->saveGroup([
            'id' => $request->post('id', 0),
            'name' => $request->post('name', ''),
            'sort' => $request->post('sort', 0),
        ]);
    }


    /**
     * 删除媒体分组
     * @param Request $request 请求对象
     * @return array
     */
    public function groupDelete(Request $request): array
    {
        return $this->core()->deleteGroup((int)$request->post('id', 0));
    }

    /**
     * 从请求中获取上传文件
     * 依次检查 file/files/upload 字段
     * @param Request $request 请求对象
     * @return mixed 上传文件对象或null
     */
    private function getUploadFiles(Request $request)
    {
        $file = $request->file('file');
        if ($file) {
            return $file;
        }

        $file = $request->file('files');
        if ($file) {
            return $file;
        }

        $file = $request->file('upload');
        if ($file) {
            return $file;
        }

        return null;
    }

    /**
     * 获取媒体核心服务实例
     * @return CoreMediaService
     */
    private function core(): CoreMediaService
    {
        return $this->app->make(CoreMediaService::class);
    }

    /**
     * 获取媒体文件仓储实例
     * @return MediaFileRepository
     */
    private function fileRepository(): MediaFileRepository
    {
        return $this->app->make(MediaFileRepository::class);
    }

    /**
     * 获取媒体分组仓储实例
     * @return MediaGroupRepository
     */
    private function groupRepository(): MediaGroupRepository
    {
        return $this->app->make(MediaGroupRepository::class);
    }
}