<?php

namespace Api\PhpServices\Ksy;
use Api\PhpUtils\Http\Request;

class Ksyun
{
    private const jinshan_ak = 'AKLTnATdoXUnR72IDSGgN2WSOQ';  //AccessKey
    private const jinshan_sk = 'OMw7UAOkrLVsRevuP44ctAlfzriDzUm9+JvOFoYuiSoLgaLJWi+kjUa+4G3EWXFakQ=='; //SecretKey
    private const bp_bucket = 'bp-yidian';
    private const get_down_from_ksyun = 'http://video-stream-service.int.yidian-inc.com/auth/url-get';

    /**
     * 支持批量
     * 根据 object_id 从金山云 获取下载地址
     * @param $object_ids array  ["90.mp4", "17.mp4"]
     * @param $appid  string  区分不同业务方
     * @param $bucket  string
     * @param $expire_time
     * @return array
     */
    public static function getDownUrl(array $object_ids,$appid,$bucket,$expire_time=60)
    {
        $post_data = [
            'keys' => $object_ids,
            'from' => $appid,
            'bucket' => $bucket,
            'expire' => $expire_time,
        ];

        $res = (new Request())->post(self::get_down_from_ksyun, $post_data,50, 'json',[],1);
        if (isset($res['code'],$res['response']['status']) && $res['response']['status'] === 'success') {
            return $res['response']['data'];
        }
        return [];
    }

    /**
     * 返回 金山云token
     * @param $http_method
     * @param $date
     * @param $resource
     * @param string $headers
     * @param string $content_md5
     * @param string $content_type
     * @file https://docs.ksyun.com/documents/6890
     * @return string
     */
    public function getToken($http_method,$date,$resource,$headers='',$content_md5='',$content_type='') :string
    {
        if (!empty($headers))
        {
            $headers = $headers . "\n";
        }

        $StringToSign = $http_method . "\n"
            . $content_md5 . "\n"
            . $content_type . "\n"
            . $date . "\n"
            . $headers
            . $resource;

        $signature = base64_encode(hash_hmac('sha1', $StringToSign, self::jinshan_sk, true));
        $signature = 'KSS ' . self::jinshan_ak . ':' . $signature;
        return $signature;
    }

    /**
     * 返回bucket
     * @param $appid
     * @param $scenario string 区分业务场景
     * @return string
     */
    public static function getBucket($appid,$scenario) :string
    {
        if ($appid === 'merchant-b' || $appid === 'merchant-c') {
            return self::bp_bucket;
        }
        return '';
    }

    /**
     * 生成objectid 和 bucket
     * @param $appid
     * @param $scenario string 区分业务场景
     * @return array
     */
    public static function getObjectAndBucket($appid,$scenario):array
    {
        return ['bucket' => self::getBucket($appid,$scenario),'objectId' => md5(uniqid(mt_rand(), true))];
    }
}