<?php
/**
 * 阿里云OSS存储驱动
 */

namespace Plugin\storage\drivers;

class AliyunDriver extends Driver
{
    private $accessKeyId;
    private $accessKeySecret;
    private $bucket;
    private $endpoint;
    private $domain;

    public function __construct($config = [])
    {
        parent::__construct($config);
        $this->accessKeyId = $config['access_key_id'] ?? '';
        $this->accessKeySecret = $config['access_key_secret'] ?? '';
        $this->bucket = $config['bucket'] ?? '';
        $this->endpoint = $config['endpoint'] ?? '';
        $this->domain = $config['domain'] ?? '';
    }

    /**
     * 上传文件到阿里云OSS
     */
    public function upload($filePath, $savePath, $originalName = '')
    {
        if (!$this->validateConfig()) {
            return ['success' => false, 'message' => '阿里云OSS配置不完整'];
        }

        // 检查是否安装了OSS SDK
        if (!class_exists('OSS\OssClient')) {
            return ['success' => false, 'message' => '请安装阿里云OSS PHP SDK'];
        }

        try {
            $ossClient = new \OSS\OssClient(
                $this->accessKeyId,
                $this->accessKeySecret,
                $this->endpoint
            );

            $result = $ossClient->uploadFile($this->bucket, $savePath, $filePath);
            
            return [
                'success' => true,
                'path' => $savePath,
                'url' => $this->getUrl($savePath),
                'filename' => $savePath,
                'original_name' => $originalName,
                'file_size' => filesize($filePath)
            ];
        } catch (\Exception $e) {
            return ['success' => false, 'message' => '上传失败: ' . $e->getMessage()];
        }
    }

    /**
     * 删除阿里云OSS文件
     */
    public function delete($path)
    {
        if (!$this->validateConfig()) {
            return false;
        }

        try {
            $ossClient = new \OSS\OssClient(
                $this->accessKeyId,
                $this->accessKeySecret,
                $this->endpoint
            );
            
            $ossClient->deleteObject($this->bucket, $path);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 获取阿里云OSS文件URL
     */
    public function getUrl($path)
    {
        $domain = rtrim($this->domain, '/');
        return $domain . '/' . ltrim($path, '/');
    }

    /**
     * 检查文件是否存在
     */
    public function exists($path)
    {
        if (!$this->validateConfig()) {
            return false;
        }

        try {
            $ossClient = new \OSS\OssClient(
                $this->accessKeyId,
                $this->accessKeySecret,
                $this->endpoint
            );
            
            return $ossClient->doesObjectExist($this->bucket, $path);
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 获取驱动名称
     */
    public function getName()
    {
        return 'aliyun';
    }

    /**
     * 获取配置表单
     */
    public function getConfigForm()
    {
        return [
            'title' => '阿里云OSS存储',
            'fields' => [
                [
                    'name' => 'aliyun_access_key_id',
                    'label' => 'AccessKey ID',
                    'type' => 'text',
                    'placeholder' => '请输入阿里云AccessKey ID',
                    'required' => true
                ],
                [
                    'name' => 'aliyun_access_key_secret',
                    'label' => 'AccessKey Secret',
                    'type' => 'password',
                    'placeholder' => '请输入阿里云AccessKey Secret',
                    'required' => true
                ],
                [
                    'name' => 'aliyun_bucket',
                    'label' => 'Bucket名称',
                    'type' => 'text',
                    'placeholder' => '请输入OSS Bucket名称',
                    'required' => true
                ],
                [
                    'name' => 'aliyun_endpoint',
                    'label' => 'Endpoint',
                    'type' => 'text',
                    'placeholder' => '如: oss-cn-hangzhou.aliyuncs.com',
                    'required' => true
                ],
                [
                    'name' => 'aliyun_domain',
                    'label' => '访问域名',
                    'type' => 'text',
                    'placeholder' => '如: https://cdn.example.com',
                    'required' => true
                ]
            ]
        ];
    }

    /**
     * 验证配置
     */
    public function validateConfig()
    {
        return !empty($this->accessKeyId) && !empty($this->accessKeySecret) && 
               !empty($this->bucket) && !empty($this->endpoint) && !empty($this->domain);
    }

    /**
     * 测试连接
     */
    public function testConnection()
    {
        if (!$this->validateConfig()) {
            return false;
        }

        if (!class_exists('OSS\OssClient')) {
            return false;
        }

        try {
            $ossClient = new \OSS\OssClient(
                $this->accessKeyId,
                $this->accessKeySecret,
                $this->endpoint
            );
            $ossClient->listObjects($this->bucket, ['max-keys' => 1]);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}
