<?php

namespace App\Http\Controllers\App;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Sts\Sts;
use App\Http\Controllers\Controller;
use App\Facades\UploadService;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class UploadController extends Controller
{
    use ResponseJson;

    public function uploadImage(Request $request)
    {
        $file = $request->file();
        if (empty($file)) return $this->failure(trans('app.select_images'));
        $url = UploadService::upload($file['fileData']);
        if (empty($url)) return $this->failure();
        return $this->success('ok', $url);
    }

    public function neteaseUpload(Request $request)
    {
        try {
            $file = $request->get('file');
            $client = new Client();
            $time = time();
            $nonce = uniqid();
            $response = $client->post('https://api.netease.im/nimserver/msg/upload.action', [
                'headers' => [
                    'AppKey' => config('chat.im.app_id'),
                    'Nonce' => $nonce,
                    'CurTime' => $time,
                    'CheckSum' => sha1(config('chat.im.app_secret') . $nonce . $time),
                ],
                'multipart' => [
                    [
                        'name' => 'content', // 修改为正确的文件内容参数名称
                        'contents' => $file
                    ],
                ],
            ]);
            $body = json_decode($response->getBody(), true);
            if ($body['code'] === 200) {
                // 文件上传成功
                return $this->success('文件上传成功', $body['url']);
            } else {
                // 文件上传失败
                return $this->failure('文件上传失败');
            }
        } catch (\Exception $e) {
            AddErrorLog::dispatch('uploadWangYiFile file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure("上传失败");
        }
    }

    public function stsConfig()
    {
        $accessKeyId = config('alioss.id');
        $accessKeySecret = config('alioss.secret');
        $data = [];
        $data['endpoint'] = config('alioss.out_endpoint');
        $data['bucket'] =  config('alioss.bucket');
        $data['dir'] = date('Y') . date('m') . "/" . date('d') . "/";
        $data['host'] = 'https://' . config('alioss.domain');
        $regionId = config('app.env') == "production"?"cn-hangzhou":"cn-shenzhen";
        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId($regionId)
            ->asDefaultClient()->options([
            ]);
        Log::info($regionId);
        Log::info(config('alioss.role_arn'));
        try {
            $request = Sts::v20150401()->assumeRole();
            $result = $request
                ->withRoleSessionName("hankin")
                ->withRoleArn(config('alioss.role_arn'))
//                ->debug(true) // Enable the debug will output detailed information

                ->request();
            $result= $result->toArray();
//            $securityToken = $result['Credentials']['SecurityToken'];
            $data['securityToken'] = $result['Credentials']['SecurityToken'];
            $data['accessKeyId'] = $result['Credentials']['AccessKeyId'];
            $data['accessKeySecret'] = $result['Credentials']['AccessKeySecret'];
            return $this->success('ok', $data);
        } catch (ClientException $exception) {
            Log::error($exception->getMessage());
            return $this->success('ok', $data);
        } catch (ServerException $exception) {
            Log::error($exception->getMessage());
            Log::error($exception->getErrorCode());
            Log::error($exception->getRequestId());
            Log::error($exception->getErrorMessage());
            return $this->success('ok', $data);
        }
    }
}
