<?php

namespace Extend\TencentIm;

use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use App\Utils\HttpRequest;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Utils\ApplicationContext;

/**
 * 账号
 */
class Account extends Base
{
    private string $version = 'v4';

    /**
     * 创建单个账号
     * @param string $user_id 用户id
     * @param string $nick_name 用户昵称
     * @param string $avatar 用户头像 URL
     * @return array
     * @throws GuzzleException
     */
    public function createAccount(string $user_id,string $nick_name = "",string $avatar = ""): array
    {
        try {
            $options = [
                "json"=> [
                    "UserID" => $user_id,
                    "Nick" => $nick_name,
                    "FaceUrl" => addAliyunOssWebsite($avatar),
                ]
            ];

            $path = $this->config['base_url'] . $this->version . "/im_open_login_svc/account_import?" . $this->buildRequestParams();
            return $this->postRequest($path,$options);
        }catch (\Exception $e) {
            throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR);
        }
    }

    /**
     * 查询账号导入状态-单条
     * @param string $user_id
     * @return bool
     * @throws GuzzleException
     */
    public function checkAccountStatus(string $user_id): bool
    {
        try {
            $options = [
                "json"=> [
                    "CheckItem" => [
                        [
                            "UserID" => $user_id
                        ]
                    ]
                ]
            ];

            $path = $this->config['base_url'] . $this->version . "/im_open_login_svc/account_check?" . $this->buildRequestParams();
            $result = $this->postRequest($path,$options);
            if (empty($result['ResultItem'])){
                throw new BusinessException("im返回值错误");
            }

            foreach ($result['ResultItem'] as $item){
                if ($item['AccountStatus'] != "Imported"){
                    // 未导入
                    return false;
                }
            }

            return true;
        }catch (\Exception $e) {
            throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR);
        }
    }
}