<?php

namespace App\Servers\Aliyun;

use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Credentials\StaticCredentialsProvider;
use App\Facades\Servers\Logs\Log;

/**
 * 阿里oss
 *
 * @author    jun
 */

class Oss {
    private $ossClient;
    function __construct()
    {
        $accessKeyId        =   config('aliyun.oss.accessKeyId','');
        $accessKeySecret    =   config('aliyun.oss.accessKeySecret','');
        $provider           =   new StaticCredentialsProvider($accessKeyId,$accessKeySecret);
        $endpoint           =   'https://'. config('aliyun.oss.endpoint','oss-cn-shenzhen') .'.aliyuncs.com';
        $config = array(
            "provider" => $provider,
            "endpoint" => $endpoint,
            "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
            "region"=> "cn-shenzhen"
        );
        $this->ossClient = new OssClient($config);
    }
    /**
     *  使用签名URL上传
     * @param string 	bucket	存储空间名称
     * @param string 	object	不包含Bucket名称在内的Object完整路径
     *
     * */
    function signUrl($bucket, $object,$options=['Content-Type'=>'multipart/form-data'] )
    {
        // 指定签名URL的过期时间为600s（最长可达32400s）。
        $timeout = 600;
        try {
            // 生成签名URL。
            $signedUrl = $this->ossClient->signUrl($bucket, $object, $timeout, "PUT",$options);
            return $signedUrl;
        } catch (OssException $e) {
            Log::error('oss/signUrl','获取签名URL上传失败，错误：'.json_encode($e->getMessage()));
            return false;
        }
    }
    /**
     *  上传文件
     * @param string 	file_name	文件名称
     * @param string 	bucket	    存储空间名称
     * @param string 	object	    填写Object完整目录路径，例如exampledir/。Object路径中不能包含Bucket名称。
     * @param string 	filePath	填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
     *
     * */
    public function uploadFile($file_name,$filePath,$bucket="", $object=""){

        $bucket                   = $bucket ? $bucket : config('aliyun.oss.bucket','kailin-saas');
        try{
            $object               = $object.'/'.date('Y').'/'.date('m').'/'.$file_name;
            $result               = $this->ossClient->uploadFile($bucket, $object, $filePath);
            $httpCode             = $result['info']['http_code'] ?? 0;
            if ($httpCode == 200) {
                $url = $result['info']['url'];
                $url    = str_replace('https://drugreport.oss-cn-shenzhen.aliyuncs.com','https://file.snowkirin.com.cn',$url);
                return $url;
            }
            return false;

        }catch(OssException $e ){
            Log::error('oss/uploadFile','oss上传文件失败，错误：'.json_encode($e->getMessage()));
            return false;
        }
    }

    public function uploadDiyFile($filePath, $bucket="", $object="uploads/shop")
    {
        $bucket                   = $bucket ? $bucket : config('aliyun.oss.bucket','kailin-saas');
        try{
            //$object               = $object.'/'.date('Y').'/'.date('m').'/'.'123';
            $result               = $this->ossClient->uploadFile($bucket, $object, $filePath);
            $httpCode             = isset($result['info']['http_code'])  ? $result['info']['http_code'] : 0;
            if ($httpCode == 200) {
                $url = $result['info']['url'];
                $url    = str_replace('https://drugreport.oss-cn-shenzhen.aliyuncs.com','https://file.snowkirin.com.cn',$url);
                return $url;
            }
            return false;

        }catch(OssException $e ){
            Log::error('oss/uploadFile','oss上传文件失败，错误：'.json_encode($e->getMessage()));
            return false;
        }
    }

    // 上传对象
    public function putObject($object,$content,$bucket="",$options = NULL){

        $bucket                   = $bucket ? $bucket : config('aliyun.oss.bucket','kailin-saas');
        try{
            //$object               = $object.'/'.date('Y').'/'.date('m').'/'.'123';
            $result               = $this->ossClient->putObject($bucket,$object,$content,$options);

            $httpCode             = isset($result['info']['http_code'])  ? $result['info']['http_code'] : 0;
            if ($httpCode == 200) {
               $url = $result['info']['url'];
                $url    = str_replace('https://drugreport.oss-cn-shenzhen.aliyuncs.com','https://file.snowkirin.com.cn',$url);
                return $url;
            }
            return false;

        }catch(OssException $e ){
            Log::error('oss/putObject','oss上传文件失败，错误：'.json_encode($e->getMessage()));
            return false;
        }
    }
}