<?php

namespace app\model;

use app\service\AliOss;
use Exception;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Config;
use think\Image;

class File extends Base
{
    const IMG   = 'image';
    const VIDEO = 'video';
    const FILE  = 'file';

    //获取文件类型
    public static function getTypes()
    {
        return [
            'image' => '图片',
            'video' => '视频',
            'file'  => '文件'
        ];
    }

    //获取文件列表
    public static function getList($type = '', $page = 1, $per = 20)
    {
        $limit = ($page - 1) * $per;
        if ($type != '') {
            if (!in_array($type, array_keys(self::getTypes()))) {
                return [];
            }
            $items = self::where('type', $type)
                ->order('id desc');
        } else {
            $items = self::order('id desc');
        }
        $items = $items->limit($limit, $per)->select()->toArray();
        foreach ($items as &$item) {
            $item['sizeStr'] = sizeToStr($item['size']);
        }
        return $items;
    }

    //获取分页列表
    public static function getListPage($type = '', $per = 20)
    {
        if ($type != '') {
            if (!in_array($type, array_keys(self::getTypes()))) {
                return [];
            }
            return self::where('type', $type)
                ->order('id desc')
                ->paginate([
                    'list_rows' => $per,
                    'query'     => [
                        'type' => $type
                    ]
                ], false);
        } else {
            return self::order('id desc')
                ->paginate([
                    'list_rows' => $per
                ], false);
        }
    }

    //添加,$w_h图片尺寸大小,单位像素,只对type=img时有效
    public static function add($file, $src, $md5, $type = 'image')
    {
        $realPath = public_path().ltrim($src, '/');
        $oss      = false;
        if (is_file($realPath) && $type == 'image') {
            $img = Image::open($realPath);
            list($w, $h) = $img->size();
            $w_h = $w.'px * '.$h.'px';
        } else {
            $w_h = '';
        }

        $now = date('Y-m-d H:i:s');
        Attachment::pathDirHandle($src);

        Config::load('extra/base', 'base');
        $baseConfig = config('base');
        if (isset($baseConfig['oss']) && $baseConfig['oss'] == 'true') {
            //            //阿里云
            //            $ossObject = AliOss::instance();
            //            try {
            //                $pathInfo = pathinfo($src);
            //
            //                $ossConfig = AliOss::config();
            //                $bucket = $ossConfig['bucket'];
            //                //是否存在
            //                if (!$ossObject->doesObjectExist($bucket, ltrim($src, '/'))) {
            //                    //创建目录
            //                    $ossObject->createObjectDir($bucket, ltrim($pathInfo['dirname'], '/'));
            //
            //                    $ossObject->uploadFile($bucket, ltrim($src, '/'), $realPath);
            //                }
            //                $oss = true;
            //            } catch (Exception $e) {
            //                \think\facade\Log::error('阿里云OSS上传文件失败 '.$e->getMessage());
            //            }

            // 七牛
            try {
                Config::load('extra/qiniu', 'qiniu');
                $conf = config('qiniu');
                // 控制台获取密钥:https://portal.qiniu.com/user/key
                $accessKey = $conf['qiniuAccessKey'] ?? '';
                $secretKey = $conf['qiniuSecretKey'] ?? '';
                $bucket    = $conf['bucket'] ?? '';

                // 构建鉴权对象
                $auth = new Auth($accessKey, $secretKey);
                // 生成上传 Token
                $token = $auth->uploadToken($bucket);
                // 要上传文件的本地路径
                //                $filePath = './php-logo.png';
                $filePath = $realPath;
                // 上传到七牛存储后保存的文件名
                //                $key = 'my-php-logo.png';
                $key = ltrim($src, '/');

                // 初始化 UploadManager 对象并进行文件的上传。
                $uploadMgr = new UploadManager();

                // 调用 UploadManager 的 putFile 方法进行文件的上传,该方法会判断文件大小,进而决定使用表单上传还是分片上传,无需手动配置。
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                if ($err !== null) {
                    \think\facade\Log::error('七牛云OSS上传文件失败 '.$err);
                    //                    var_dump($err);
                } else {
                    //                    var_dump($ret);
                }
            } catch (Exception $e) {
                \think\facade\Log::error('七牛云OSS上传文件失败 '.$e->getMessage());
            }
        }

        // 将src中路径创建
        return self::create([
            'type'       => $type,
            'name'       => $file->getOriginalName(),
            'md5'        => $md5,
            'src'        => $src,
            'path'       => isset(pathinfo($src)['dirname']) ? pathinfo($src)['dirname'].'/' : '',
            'size'       => $file->getSize(),
            'suffix'     => $file->getOriginalExtension(),
            'mime_type'  => $file->getOriginalMime(),
            'created_at' => $now,
            'updated_at' => $now,
            'is_oss'     => $oss,
            'w_h'        => $w_h
        ]);
    }

    //获取所有记录
    public static function getAll()
    {
        return self::select()->toArray();
    }
}