<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */


namespace app\common\service;


use app\common\enum\FileEnum;
use app\common\model\File;
use app\common\service\storage\Driver as StorageDriver;
use EasyWeChat\Factory;
use FFMpeg\FFMpeg;
use Exception;
use think\file\UploadedFile;

class UploadService
{
    /**
     * 上传图片
     * @notes
     * @param $cid
     * @param int $source_id  来源id
     * @param int $source 来源
     * @param string $save_dir
     * @return array
     * @throws Exception
     */
    public static function image($cid,$source_id = 0,$source = FileEnum::SOURCE_BACKSTAGE, $save_dir='uploads/images')
    {
        try {
            $config = [
                'default' => ConfigService::get('storage', 'default', 'local'),
                'engine'  => ConfigService::get('storage') ?? ['local'=>[]],
            ];
            if($config['default'] != 'local'){
                $save_dir = 'oss/'.$config['default'].'/'.$save_dir;
            };

            // 2、执行文件上传
            $StorageDriver = new StorageDriver($config);
            $StorageDriver->setUploadFile('file');
            if (!$StorageDriver->upload($save_dir)) {
                throw new Exception($StorageDriver->getError());
            }

            $fileName = $StorageDriver->getFileName();
            $fileInfo = $StorageDriver->getFileInfo();

            // 3、处理文件名称
            if (strlen($fileInfo['name']) > 128) {
                $file_name = substr($fileInfo['name'], 0, 123);
                $file_end = substr($fileInfo['name'], strlen($fileInfo['name'])-5, strlen($fileInfo['name']));
                $fileInfo['name'] = $file_name.$file_end;
            }

            // 4、写入数据库中
            $file = File::create([
                'cid'         => $cid,
                'type'        => FileEnum::IMAGE_TYPE,
                'name'        => $fileInfo['name'],
                'uri'         => $save_dir . '/' . str_replace("\\","/", $fileName),
                'source'      => $source,
                'source_id'   => $source_id,
                'create_time' => time(),
            ]);

            // 5、返回结果
            return [
                'id'   => $file['id'],
                'cid'  => $file['cid'],
                'type' => $file['type'],
                'name' => $file['name'],
                'uri'  => FileService::getFileUrl($file['uri']),
                'url'  => $file['uri']
            ];

        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @notes 视频上传
     * @param $cid
     * @param int $user_id
     * @param string $save_dir
     * @return array
     * @throws Exception
     */

    public static function video($cid,$source_id = 0,$source = FileEnum::SOURCE_BACKSTAGE,  $save_dir='uploads/video')
    {
        try {
            $config = [
                'default' => ConfigService::get('storage', 'default', 'local'),
                'engine'  => ConfigService::get('storage') ?? ['local'=>[]],
            ];

            if($config['default'] != 'local'){
                $save_dir = 'oss/'.$config['default'].'/'.$save_dir;
            };

            // 2、执行文件上传
            $StorageDriver = new StorageDriver($config);
            $StorageDriver->setUploadFile('file');
            if (!$StorageDriver->upload($save_dir)) {
                throw new Exception($StorageDriver->getError());
            }

            $fileName = $StorageDriver->getFileName();
            $fileInfo = $StorageDriver->getFileInfo();

            
            // 3、处理文件名称
            if (strlen($fileInfo['name']) > 128) {
                $file_name = substr($fileInfo['name'], 0, 123);
                $file_end = substr($fileInfo['name'], strlen($fileInfo['name'])-5, strlen($fileInfo['name']));
                $fileInfo['name'] = $file_name.$file_end;
            }

            // 4、写入数据库中
            $file = File::create([
                'cid'         => $cid,
                'type'        => FileEnum::VIDEO_TYPE,
                'name'        => $fileInfo['name'],
                'uri'         => $save_dir . '/' . str_replace("\\","/", $fileName),
                'source'      => $source,
                'source_id'   => $source_id,
                'create_time' => time(),
            ]);

            $thumb = '';
            // 阿里云OSS  视频封面
            if( $config['default'] =='aliyun'){
                $thumb = FileService::getFileUrl($file['uri']) . '?x-oss-process=video/snapshot,t_7000,f_jpg,m_fast,w_500';
            }
            // cos
            if( $config['default'] =='qcloud'){
                $thumb = FileService::getFileUrl($file['uri']) . '?ci-process=snapshot&time=1&format=jpg&width=500';
            }

            
            
            // 5、返回结果
            return [
                'id'   => $file['id'],
                'cid'  => $file['cid'],
                'type' => $file['type'],
                'name' => $file['name'],
                'uri'  => FileService::getFileUrl($file['uri']),
                'url'  => $file['uri'],
                'thumb' => $thumb ,
            ];

        } catch (Exception $e) {
           
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @notes 附件上传
     * @param $cid
     * @param int $user_id
     * @param string $save_dir
     * @return array
     * @throws Exception
     */
     public static function file($cid,$source_id = 0,$source = FileEnum::SOURCE_BACKSTAGE,  $save_dir='uploads/file')
     {
         try {
             $config = [
                 'default' => ConfigService::get('storage', 'default', 'local'),
                 'engine'  => ConfigService::get('storage') ?? ['local'=>[]],
             ];
 
             if($config['default'] != 'local'){
                 $save_dir = 'oss/'.$config['default'].'/'.$save_dir;
             };
 
             // 2、执行文件上传
             $StorageDriver = new StorageDriver($config);
             $StorageDriver->setUploadFile('file');
             if (!$StorageDriver->upload($save_dir)) {
                 throw new Exception($StorageDriver->getError());
             }
 
             $fileName = $StorageDriver->getFileName();
             $fileInfo = $StorageDriver->getFileInfo();
 
             
             // 3、处理文件名称
             if (strlen($fileInfo['name']) > 128) {
                 $file_name = substr($fileInfo['name'], 0, 123);
                 $file_end = substr($fileInfo['name'], strlen($fileInfo['name'])-5, strlen($fileInfo['name']));
                 $fileInfo['name'] = $file_name.$file_end;
             }
 
             // 4、写入数据库中
             $file = File::create([
                 'cid'         => $cid,
                 'type'        => FileEnum::VIDEO_TYPE,
                 'name'        => $fileInfo['name'],
                 'uri'         => $save_dir . '/' . str_replace("\\","/", $fileName),
                 'source'      => $source,
                 'source_id'   => $source_id,
                 'create_time' => time(),
             ]);
 
             $thumb = '';
             // 阿里云OSS  视频封面
             if( $config['default'] =='aliyun'){
                 $thumb = FileService::getFileUrl($file['uri']) . '?x-oss-process=video/snapshot,t_7000,f_jpg,m_fast,w_500';
             }
             // cos
             if( $config['default'] =='qcloud'){
                 $thumb = FileService::getFileUrl($file['uri']) . '?ci-process=snapshot&time=1&format=jpg&width=500';
             }
 
             
             
             // 5、返回结果
             return [
                 'id'   => $file['id'],
                 'cid'  => $file['cid'],
                 'type' => $file['type'],
                 'name' => $file['name'],
                 'uri'  => FileService::getFileUrl($file['uri']),
                 'url'  => $file['uri'],
                 'thumb' => $thumb ,
             ];
 
         } catch (Exception $e) {
            
             throw new Exception($e->getMessage());
         }
     }

    /**
     * @notes 上传素材
     * @param $url
     */
    public static function wechatMaterial(UploadedFile $file)
    {
        try {
            $dir = './uploads/temp';
            $original_name = $file->getOriginalName();
            $file->move($dir,$original_name);
            $config = WeChatConfigService::getMnpConfig();

            $app = Factory::miniProgram($config);
            $path = ROOT_PATH . '/uploads/temp/' . $original_name;

            $result = $app->media->uploadImage($path);
            unlink($path);
            return ['media_id' => $result['media_id'], 'url' => FileService::getFileUrl('uploads/temp/' . $original_name)];

        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
}