<?php

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

class Ksyun
{
    private const jinshan_ak = 'AKLTTpZx6fNBQsGSKe5chqHdXA';  //AccessKey
    private const jinshan_sk = 'OG9Bk93RUHwaH71U9K+OtWkvx44AdMheywjFlifILikvh96jNGgznJm+AyR5l4wPhw=='; //SecretKey
    private const bp_bucket = 'bp-yidian';
    private const get_down_from_ksyun = 'http://10.103.34.109:8007/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
     * @return string
     */
    public static function getBucket($appid) :string
    {
        if ($appid === 'merchant-b' || $appid === 'merchant-c') {
            return self::bp_bucket;
        }
        return '';
    }

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