<?php

namespace Modules\Storage\Http\Controllers;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Api\Controllers\Controller;
use Illuminate\Support\Facades\Config;

class StsController extends Controller
{

    /**
     * Notes   : 获取 STS 授权直传配置
     *
     * @Date   : 2021/4/25 5:24 下午
     * @Author : <Jason.C>
     * @return mixed
     */
    public function config()
    {
        $config = Config::get('storage.disks.oss');

        try {
            AlibabaCloud::accessKeyClient(
                $config['access_key'],
                $config['secret_key'],
            )->regionId($config['RegionId'])->asDefaultClient();
        } catch (ClientException $e) {
            return $this->failed($e->getErrorMessage());
        }

        try {
            $Policy = [
                'Version'   => "1",
                'Statement' => [
                    [
                        'Effect'   => 'Allow',
                        'Action'   => 'oss:*',
                        'Resource' => [
                            "*",
                        ],
                    ],
                ],
            ];

            $result = AlibabaCloud::rpc()
                ->product('Sts')
                ->scheme('https') // https | http
                ->version('2015-04-01')
                ->action('AssumeRole')
                ->method('POST')
                ->host('sts.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId'        => $config['RegionId'],
                        'RoleArn'         => $config['RoleArn'],
                        'RoleSessionName' => 'RoleSessionName',
                        // 'Policy'          => json_encode($Policy),
                        'DurationSeconds' => 3600,
                    ],
                ])
                ->request();

            return $this->success([
                'secure'          => true,
                'bucket'          => $config['bucket'],
                'region'          => $config['RegionId'], // 前缀带 oss- ？
                'accessKeyId'     => $result->Credentials->AccessKeyId,
                'accessKeySecret' => $result->Credentials->AccessKeySecret,
                'stsToken'        => $result->Credentials->SecurityToken,
                'endpoint'        => $config['endpoint'],
                'cname'           => $config['isCName'],
            ]);
        } catch (ClientException | ServerException $e) {
            return $this->failed($e->getErrorMessage());
        }
    }
}
