<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-05
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\model;
use think\Model as Basemodel;
use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class Media extends Basemodel
{
	public function getSizeAttr($value)
    {
        return format_bytes($value);
    }
    public function getTypeAttr($value)
    {
        switch ($value) {
        	case 'image':
        		return '图片';
        		break;
        	case 'file':
        		return '文件';
        		break;
        	case 'video':
        		return '视频';
        		break;
        	default:
        		return '其他';
        		break;
        }
    }

    // 删除
	static public function del($id)
	{
		try {
			$id = is_array($id) ? $id : array($id);
			foreach ($id as $v) {
				$media = self::get($v);
                if(strpos($media['url'],'http')!==false && config('app.qiniu.qiniu') && config('app.qiniu.qiniudelete')) {
                    $imgArr = explode('/',$media['url']);
                    unset($imgArr[0]);
                    unset($imgArr[1]);
                    unset($imgArr[2]);
                    $delImgName = implode('/', $imgArr);
                    // 初始化签权对象
                    $auth = new Auth(config('app.qiniu.AK'),config('app.qiniu.SK'));
                    $config = new Config();
                    // 管理资源
                    $bucketManager = new BucketManager($auth,$config);
                    // 删除文件操作
                    $bucketManager->delete(config('app.qiniu.bucket'),$delImgName);
                } else {
                    is_file(env('root_path').$media['url']) && unlink(env('root_path').$media['url']);
                }
                $media->delete();
			}
			return ['code'=>1 ,'msg'=>lang('deltrue')];
		} catch (\Exception $e) {
			return ['code'=>0 ,'msg'=>$e->getMessage()];
		}
	}

    // 清除不存在
    static public function dels()
    {
        try {
            $media = self::select();
            foreach ($media as $v) {
                if(!file_exists(env('root_path').$v['url'])) {
                    self::destroy($v['id']);
                }
            }
            return ['code'=>1 ,'msg'=>lang('deltrue')];
        } catch (\Exception $e) {
            return ['code'=>0 ,'msg'=>$e->getMessage()];
        }
    }
}