<?php

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

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 bp_image_yidian = 'bp-image-yidian';
    private const get_down_from_ksyun = 'http://video-stream-service.int.yidian-inc.com/auth/url-get';
    private const get_down_from_pic_service = 'https://ibp.go2yd.com/imagebp.php'; //来自图片服务

    public const scenario_id_card                 = 'id_card';
    public const scenario_living_data             = 'living_data';
    public const scenario_living_business_license = 'business_license';
    public const scenario_living_goods            = 'goods';
    public const scenario_living_goods_temp       = 'goods_temp';  //商品图片临时方案

    /**
     * 支持批量
     * 根据 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)
    {
        if (empty($object_ids)) {
            return [];
        }
        $object_ids = array_values(array_filter($object_ids));
        $post_data = [
            'keys' => $object_ids,
            'from' => $appid,
            'bucket' => $bucket,
            'expire' => $expire_time,
        ];
        $begin =  microtime(true);
        $res = (new Request())->post(self::get_down_from_ksyun, $post_data,50, 'json',[],1,true);
        $end = microtime(true);
        $total_time = round(($end - $begin),4) * 1000;
        if(isset($res['response']['code'])){
            $code = $res['response']['code'];
        }else{
            $code = -1;
        }
        MonUtil::proxyMon(self::get_down_from_ksyun, $code, 'merchant', $total_time);
        if (isset($res['code'],$res['response']['status']) && $res['response']['status'] === 'success') {
            return $res['response']['data'];
        }
        return [];
    }

    /**
     *
     * @param $url
     * @param $appid
     * @param int $expire_time
     * @param string $scenario
     * @return mixed|string
     */
    public static function getUrlFromKsyn($url,$appid,$expire_time=60)
    {
        $del_str   = explode('/',$url);
        $bucket    = $del_str[0] ?? '';
        $objectid  = $del_str[1] ?? '';
        $image_url = self::getDownUrl([$objectid],$appid,$bucket,$expire_time);
        if (empty($image_url) || (!isset($image_url[$objectid]) )
        ) {
            return '';
        }

        return $image_url[$objectid];
    }

    /**
     * 根据金山云文档 生成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 .= "\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;
    }

    /**
     * @param string $appid 应用
     * @param $scenario
     * @param $http_method
     * @param $date
     * @param $resource
     * @param string $headers
     * @param string $content_md5
     * @param string $content_type
     * @return string
     */
    public function getTokenV2($appid,$scenario,$http_method,$date,$resource,$headers='',$content_md5='',$content_type='') : string
    {
        return $this->getToken($http_method,$date,$resource,$headers,$content_md5,$content_type);
    }

    /**
     * 返回bucket
     * @param $appid
     * @param $scenario string 区分业务场景
     * @return string
     */
    public static function getBucket($appid,$scenario) :string
    {
        if ($appid === 'merchant-b' || $appid === 'merchant-c') {
            if ($scenario === self::scenario_living_goods) {
                return self::bp_image_yidian;
            }
            if (in_array($scenario,[self::scenario_id_card,self::scenario_living_business_license,self::scenario_living_data])) {
                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))];
    }

    /**
     * 获取可支持裁剪的图片url
     * @param $bucket
     * @param $objectid
     * @param $wideSize
     * @param $highSize
     * @param string $type 目前只支持 png webp jpeg
     * @wiki http://ydwiki.yidian-inc.com/pages/viewpage.action?pageId=41584585
     * @return string
     */
    public static function getCutPicUrl($bucket,$objectid,$wideSize,$highSize,$type='jepg')
    {
        if ($bucket !== self::bp_image_yidian || !in_array($type,['png','webp','jpeg'])) {
            //目前只有当bucket == bp-image_yidian 才支持可裁剪
            return '';
        }
        return sprintf(self::get_down_from_pic_service.'?'.'url=%s&%s_%sx%s',$objectid,$type,$wideSize,$highSize);
    }

    /**
     * 图片下载地址 的统一出口函数
     * @param $appid
     * @param $scenario
     * @param $url
     * @param $wideSize
     * @param $highSize
     * @param string $type
     * @return mixed|string
     */
    public static function getPicUrl($appid,$scenario,$url,$wideSize,$highSize,$type='jepg')
    {
        if (!in_array($appid,['merchant-b','merchant-c'])) {
            return '';
        }

        if (in_array($appid,['merchant-b','merchant-c'])) {
            if ($scenario === self::scenario_living_goods_temp) {
                $del_str   = explode('/',$url);
                $bucket    = $del_str[0] ?? '';
                $objectid  = $del_str[1] ?? '';
                return self::getCutPicUrl($bucket,$objectid,$wideSize,$highSize,$type);
            }

            if (in_array($scenario, [self::scenario_living_data, self::scenario_id_card, self::scenario_living_business_license], true)) {
                return self::getUrlFromKsyn($url,$appid);
            }
        }

        return '';
    }
}