<?php

namespace App\Services;

use App\Exception\BusinessException;
use App\Model\User;
use App\Model\User as UserModel;
use App\Model\UserDoctor;
use App\Model\UserPatient;
use App\Model\UserPharmacist;
use Extend\Alibaba\Oss;
use Extend\TencentIm\Account;
use Extend\TencentIm\Safe;

/**
 * 安全服务
 */
class SafeService extends BaseService
{
    /**
     * 获取oss签名数据
     * @return array
     */
    public function getOssSign(): array
    {
        $user_type = $this->request->input('user_type');
        $scene = $this->request->input('scene');
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        if (empty($user_info)){
            return fail();
        }

        if ($user_type == 1){
            $dir = "applet/patient/";
        }elseif ($user_type == 2){
            $dir = "applet/doctor/";
        }elseif ($user_type == 3){
            $dir = "applet/pharmacist/";
        }

        switch ($scene) {
            case 1:
                // 头像
                $dir = $dir . 'avatar/';
                break;
            case 2:
                // 证书
                $dir = $dir . 'cert/';
                break;
            case 3:
                // 名片
                $dir = $dir . 'card/';
                break;

            default:
                // code...
                break;
        }

        // 获取用户数据
        $params = array();
        $params['user_id'] = $user_info['user_id'];
        $user = UserModel::getOne($params);
        if (empty($user)){
            return fail();
        }

        if ($user['user_type'] != $user_info['user_type']){
            return fail();
        }

        $oss = new Oss();

        return success($oss->signature($dir));
    }

    /**
     * 获取im签名数据
     * @return array
     */
    public function getImSign(): array
    {
        $user_info = $this->request->getAttribute("userInfo") ?? [];

        if (empty($user_info)){
            return success();
        }

        // 验证用户数据
        $params = array();
        $params['user_id'] = $user_info['user_id'];
        $user = User::getOne($params);
        if (empty($user)){
            return success();
        }

        $safe = new Safe();
        $sign = $safe->getUserSign($user['user_id']);
        if (empty($sign)){
            return success();
        }

        return success($sign);
    }
}