<?php

namespace App\Http\Services;

use Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Volc\Service\Sts;
use Tos\TosClient;
use Tos\Exception\TosClientException;
use Tos\Exception\TosServerException;
use Tos\Model\PutObjectInput;
use Tos\Model\Enum;

class FileService extends BaseService
{

    protected $client;

    /**
     * 使用AK&SK初始化账号Client
     */
    public function createClient() {
        $this->client = Sts::getInstance();

        $this->client->setAccessKey('AKLTYzQ1M2Q5ODUwMTM4NDMyYzlmMWU4MzY3YzFhYmRiZjQ');
        $this->client->setSecretKey('TjJObU9HTTROVEJpWldZeE5HVmhaR0l4TW1KbE1UQXhNall6T0dFd1pqZw==');
    }

    public function getOssAccessTokenHandle(){
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => null,
        ];

        $this->createClient();

        $query = [
            "query" => [
                "DurationSeconds" => "1800",
                "RoleSessionName" => "yihuo_session",
                "RoleTrn" => "trn:iam::2100416222:role/tos-yihuo",
            ]
        ];

        try {
            $response = $this->client->assumeRole($query);
            $responseData = json_decode($response->getContents(), true);
            $credentials = $responseData['Result']['Credentials'] ?? [];
            if (empty($credentials)) {
                $result['msg'] = '获取失败';
                $result['response'] = json_encode($responseData['ResponseMetadata']['Error'] ?? [], JSON_UNESCAPED_UNICODE);
                return $result;
            }

            $result['res'] = true;
            $result['data'] = $credentials;
            $result['data']['Bucket'] = 'xcx';
            $result['data']['Endpoint'] = 'tos-cn-beijing.volces.com';
            $result['data']['Region'] = 'cn-beijing';
        } catch (Exception $error) {
            $result['msg'] = $error->getMessage();
        }

        return $result;
    }

    public function uploadFile($filePath, $remoteFilePath) {
        $result = [
            'res' => false,
            'msg' => '上传成功',
            'data' => [],
        ];

        try {
            $client = new TosClient([
                'region' => 'cn-beijing',
                'endpoint' => 'tos-cn-beijing.volces.com',
                'ak' => 'AKLTYzQ1M2Q5ODUwMTM4NDMyYzlmMWU4MzY3YzFhYmRiZjQ',
                'sk' => 'TjJObU9HTTROVEJpWldZeE5HVmhaR0l4TW1KbE1UQXhNall6T0dFd1pqZw==',
            ]);

            $input = new PutObjectInput('xcx',  $remoteFilePath);
            // 设置对象 ACL
            $input->setACL(Enum::ACLPublicRead);
            // 设置对象 StorageClass
            $input->setStorageClass(Enum::StorageClassStandard);

            $file = fopen($filePath, 'r');
            $input->setContent($file);
            $output = $client->putObject($input);

            $result['data']['request_id'] = $output->getRequestId();
        } catch (TosClientException $ex) {
            $result['msg'] = $ex->getMessage();
            return $result;
        } catch (TosServerException $ex) {
            $result['msg'] = $ex->getMessage();
            $result['data']['request_id'] = $ex->getRequestId();
            $result['data']['status_code'] = $ex->getStatusCode();
            $result['data']['error_code'] = $ex->getErrorCode();
            return $result;
        }

        $result['res'] = true;
        return $result;
    }


}
