<?php

namespace Api\PhpServices\Ksy;

use Api\PhpUtils\Http\HttpUtil;
use Api\PhpUtils\Mon\MonUtil;

/**
 * 文档: http://ydwiki.yidian-inc.com/pages/viewpage.action?pageId=68515904
 * Class Ks3Api
 * @package Api\PhpServices\Ksy
 */
class Ks3Api
{
    const KSYUN_SK = "3wm9z0P0ja6NceaZYf477EDZrJs7dSSZ";
    const KSYUN_AK = "47DA6034D64E7023";
    const KS_DATE_SCHEME = 'D, d M Y H:i:s \G\M\T';
    const BASE_URL = "http://image-upload.int.yidian-inc.com";
    const BASE_GEN_URL = "http://image-urlgen.int.yidian-inc.com";
    const PATH_GEN = "/v1/key/gen";
    const PATH_SIGNATURE = "/v1/ks3/signature";
    const PATH_PIC_ENCRYPT_URL = "/v1/url/gen";
    const PATH_PIC_UPLOAD = "/upload";
    const AUDIT_ID = "shqbp";

    const TYPE_QUALIFICATION = "shq_qualification";//商户资质
    const TYPE_GOODS = "shq_goods";//商品图片
    public static $typeList = [
        self::TYPE_QUALIFICATION,
        self::TYPE_GOODS
    ];

    /**
     * 获取bucket与objectKey
     * @param $type
     * @return mixed
     */
    public static function gen($type)
    {
        $url = self::BASE_URL . self::PATH_GEN;

        $timestamp = self::msectime();
        $md5Str = $type . "&" . $timestamp . "&" . self::KSYUN_SK;
        $signature = self::KSYUN_AK . ":" . md5($md5Str);

        $params = [
            "timestamp" => $timestamp,
            "signature" => $signature,
            "type" => $type,
        ];

        $begin = microtime(true);
        $genRes = HttpUtil::post($url, $params);
        $end = microtime(true);
        $totalTime = round(($end - $begin), 4) * 1000;
        $resCode = $genRes["response"]['code'] === 0 ? 200 : $genRes["response"]['code'];
        MonUtil::proxyMon($url, $resCode, 'ks3api', $totalTime);
        return $genRes;
    }

    /**
     * 获取KS签名
     * @param $resource
     * @param $httpMethod
     * @param $contentType
     * @param $contentMd5
     * @param $headers
     * @return array
     */
    public static function signature($resource, $httpMethod, $contentType, $contentMd5, $headers, $date)
    {
        $url = self::BASE_URL . self::PATH_SIGNATURE;

        $timestamp = self::msectime();

        $md5Str = $httpMethod . "&" . $contentType . "&" . $contentMd5 . "&" . $date . "&" . $resource . "&" . $headers . "&" . $timestamp . "&" . self::KSYUN_SK;
        $signature = self::KSYUN_AK . ":" . md5($md5Str);

        $params = [
            "timestamp" => $timestamp,
            "signature" => $signature,
            "http_method" => $httpMethod,
            "content_type" => $contentType,
            "date" => $date,
            "content_md5" => $contentMd5,
            "resource" => $resource,
            "headers" => $headers,
        ];

        $begin = microtime(true);
        $signatureRes = HttpUtil::post($url, $params);
        $end = microtime(true);
        $totalTime = round(($end - $begin), 4) * 1000;
        $resCode = $signatureRes["response"]['code'] === 0 ? 200 : $signatureRes["response"]['code'];
        MonUtil::proxyMon($url, $resCode, 'ks3api', $totalTime);
        return $signatureRes;
    }

    /**
     * 生成图片访问加密链接
     * @param $imageId
     * @param $authId
     * @param $widthSize
     * @param $highSize
     * @param int $expirationTime
     * @return mixed
     */
    public static function picEncryptUrl($imageId, $widthSize = 0, $highSize = 0, $expirationTime = 60 * 60 * 24 * 365)
    {
        $url = self::BASE_GEN_URL . self::PATH_PIC_ENCRYPT_URL;
        $timestamp = self::msectime();
        $extend = [];
        $extend["expiration_time"] = $expirationTime;
        if (!empty($widthSize) && !empty($highSize)) {
            $extend["query"] = "type=thumbnail_" . $widthSize . "x" . $highSize;
        }
        $extendJsonStr = json_encode($extend);
        $md5Str = $extendJsonStr . "&" . $imageId . "&" . self::AUDIT_ID . "&" . $timestamp . "&" . self::KSYUN_SK;
        $signature = self::KSYUN_AK . ":" . md5($md5Str);

        $contentType = 'multipart/form-data';
        $params = [
            "image_id" => $imageId,
            "auth_id" => self::AUDIT_ID,
            "timestamp" => $timestamp,
            "signature" => $signature,
            "content_type" => $contentType,
            "extend" => $extendJsonStr,
        ];

        $begin = microtime(true);
        $encryptRes = HttpUtil::post($url, $params);
        $end = microtime(true);
        $totalTime = round(($end - $begin), 4) * 1000;
        $resCode = $encryptRes["response"]['code'] === 0 ? 200 : $encryptRes["response"]['code'];
        MonUtil::proxyMon($url, $resCode, 'ks3api', $totalTime);
        return $encryptRes;
    }

    /**
     * 上传图片
     * @param int $type
     * @return mixed
     */
    public static function upload($type)
    {
        $url = self::BASE_URL . self::PATH_PIC_UPLOAD;
        $timestamp = self::msectime();

        $handle = fopen($_FILES['file']['tmp_name'], 'r');
        $content = fread($handle, filesize($_FILES['file']['tmp_name']));

        $extend = ["type" => $type];
        $extendJsonStr = json_encode($extend);
        $md5Str = $extendJsonStr . "&" . md5($content) . "&" . $timestamp . "&" . self::KSYUN_SK;
        $signature = self::KSYUN_AK . ":" . md5($md5Str);

        $params = [
            "pic" => new \CURLFile($_FILES['file']['tmp_name'], $_FILES['file']['type']),
            "timestamp" => $timestamp,
            "signature" => $signature,
            "extend" => $extendJsonStr,
        ];

        $begin = microtime(true);
        $uploadRes = HttpUtil::post($url, $params);
        $end = microtime(true);
        $totalTime = round(($end - $begin), 4) * 1000;
        $resCode = $uploadRes["response"]['code'] === 0 ? 200 : $uploadRes["response"]['code'];
        MonUtil::proxyMon($url, $resCode, 'ks3api', $totalTime);
        return $uploadRes;
    }

    /**
     * 时间戳（毫秒）
     * @return float
     */
    private static function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    }
}