<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Easemob;
use app\common\library\Tenim;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function test()
    {
        $easemob = new Easemob();

        $rs = $easemob->user_create('doctor1');

    }

    /**
     * 无需登录的接口
     *
     */
    public function test1()
    {
        $tenim = new Tenim();
        $rs = $tenim->register('user'. 1, 'nickname', '');
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $tenim = new Tenim();

        $order_id = 26;

        $message = [
            'businessID' => 'order_status',
            'name' => '待接单',
            'status' => '10',
            'id' => (string)$order_id,
            'content' => '已通知医生尽快接诊,超时自动取消订单并退款',
        ];


        $rs = $tenim->sendCustomMessageToUser('user7','doctor7',$message);
        dump($rs);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $a = 346846154;
        dump(format_bytes($a));
    }

    public function test4(){
        $a = time() - 20;
        dump($a);
        dump(get_last_time($a));
    }


    //腾讯云拍照识别商品
    //{"Response":{"Products":[{"Name":"按摩椅","Parents":"家用电器-个护健康","Confidence":99,"XMin":107,"YMin":59,"XMax":447,"YMax":366}],"RequestId":"187745fc-0497-441e-88f5-f3f17d854016"}}
    public function search_by_image($image = 'https://jiankangyijia-1304634122.cos.ap-nanjing.myqcloud.com/uploads/20240504/5cbfbb7880323f05839d82afe1500569.png'){
        $tencent_yun = config('tencent_yun');
        $secret_id   = $tencent_yun['secret_id'];
        $secret_key  = $tencent_yun['secret_key'];

        $token       = "";
        $service     = "tiia";
        $host        = "tiia.tencentcloudapi.com";
        $req_region  = "ap-beijing";
        $version     = "2019-05-29";
        $action      = "DetectProduct";
        $payload     = json_encode(['ImageUrl' => localpath_to_netpath($image)]);
        $endpoint    = "https://tiia.tencentcloudapi.com";
        $algorithm   = "TC3-HMAC-SHA256";
        $timestamp   = time();
        $date        = gmdate("Y-m-d", $timestamp);

// ************* 步骤 1:拼接规范请求串 *************
        $http_request_method = "POST";
        $canonical_uri = "/";
        $canonical_querystring = "";
        $ct = "application/json; charset=utf-8";
        $canonical_headers = "content-type:".$ct."\nhost:".$host."\nx-tc-action:".strtolower($action)."\n";
        $signed_headers = "content-type;host;x-tc-action";
        $hashed_request_payload = hash("sha256", $payload);
        $canonical_request = "$http_request_method\n$canonical_uri\n$canonical_querystring\n$canonical_headers\n$signed_headers\n$hashed_request_payload";

// ************* 步骤 2:拼接待签名字符串 *************
        $credential_scope = "$date/$service/tc3_request";
        $hashed_canonical_request = hash("sha256", $canonical_request);
        $string_to_sign = "$algorithm\n$timestamp\n$credential_scope\n$hashed_canonical_request";

// ************* 步骤 3:计算签名 *************
        $secret_date    = hash_hmac("sha256", $date, "TC3".$secret_key, true);
        $secret_service = hash_hmac("sha256", $service, $secret_date, true);
        $secret_signing = hash_hmac("sha256", "tc3_request", $secret_service, true);
        $signature      = hash_hmac("sha256", $string_to_sign, $secret_signing);

// ************* 步骤 4:拼接 Authorization *************
        $authorization = "$algorithm Credential=$secret_id/$credential_scope, SignedHeaders=$signed_headers, Signature=$signature";

// ************* 步骤 5:构造并发起请求 *************
        $headers = [
            "Authorization"  => $authorization,
            "Content-Type"   => "application/json; charset=utf-8",
            "Host"           => $host,
            "X-TC-Action"    => $action,
            "X-TC-Timestamp" => $timestamp,
            "X-TC-Version"   => $version
        ];
        if ($req_region) {
            $headers["X-TC-Region"] = $req_region;
        }
        if ($token) {
            $headers["X-TC-Token"] = $token;
        }
        $headers = array_map(function ($k, $v) { return "$k: $v"; }, array_keys($headers), $headers);

        try {
            $timeOut = 3;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $endpoint);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            $response = curl_exec($ch);
            curl_close($ch);

            //return $response;
            $response = json_decode($response,true);
            if(is_array($response) && isset($response['Response']['Products'][0]['Name'])){
                $searchname = $response['Response']['Products'][0]['Name'];
                if(!empty($searchname)){
                    return $searchname;
                }
            }
            return '';
        } catch (Exception $err) {
            //echo $err->getMessage();
            return '';
        }

    }


}