<?php
namespace Our;
/**
 * User: liuyuzhen
 * Date: 2018/5/16
 * Time: 16:43
 * Description:
 */
class ImageUtil {



    /**
     * 上传bas64格式的图片
     * @param $imageBase64Str base64图片字符串
     * @param $path 上传到服务器后带的前缀
     * @param $uploadImageName 上传之后图片名称
     * @return mixed 上传成功,返回上传图片对应浏览路径
     * @throws \Exception
     * @throws \OSS\Core\OssException
     */
    public static function uploadBase64Image($imageBase64Str,$path,$uploadImageName){
        $basepath = APPLICATION_PATH.\Our\ImageConst::tempImageUploadPath;
        if(! file_exists($basepath)) {
            @mkdir($basepath, 0777, true);
            @chmod($basepath, 0777);
        }
        if(!is_writable($basepath)) {
            @chmod($basepath, 0777);
            if(!@is_writable($basepath)) {
                \Error\ErrorModel::throwException(\Error\CodeConfigModel::folderUnwritable);
            }
        }
        if($imageBase64Str!=null&&$imageBase64Str!=''&&preg_match('/^(data:\s*image\/(\w+);base64,)/', $imageBase64Str, $result)){
            $type = $result[2];
            if(in_array($type,\Our\ArrayConst::imageExtensions)){
                $fileName = time().\Our\Validate::getNumberString();
                $tempFile = $basepath.$fileName.\Our\NameConst::dot.$type;
                if(file_put_contents($tempFile, base64_decode(str_replace($result[1], '', $imageBase64Str)))){
                    return self::uploadImage($tempFile,$path,$uploadImageName);
                }else{
                    \Error\ErrorModel::throwException(\Error\CodeConfigModel::imageUploadFailed);
                }
            }else{
                \Error\ErrorModel::throwException(\Error\CodeConfigModel::imageExtensionsWrong);
            }
        }
        \Error\ErrorModel::throwException(\Error\CodeConfigModel::base64ImageError);
    }


    /**
     * @param $url 需要下载的图片对应url
     * @param $path 上传到OSS服务器对应的路径 值如 'data/upload/osstest/'
     * @param $uploadImageName 上传到oss服务器对应的路片名称
     * @return mixed 返回图片在oss服务器的访问路径
     * @throws \Exception
     * @throws \OSS\Core\OssException
     */
    public static function uploadImageWithUrl($url,$path,$uploadImageName){
        if(!$url){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyImageUrl);
        }
        $ch=curl_init();
        $timeout= \Our\ApiConst::five;
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        $img=curl_exec($ch);
        curl_close($ch);
        $basepath = APPLICATION_PATH.\Our\ImageConst::tempImageUploadPath;
        $ext =  $ext=strrchr($url,'.');
        $ext = substr($ext,1);
        if(in_array($ext,\Our\ArrayConst::imageExtensions)||$notCheckExtention){
            $fileName = time().\Our\Validate::getNumberString();
            $tempFile = $basepath.$fileName.\Our\NameConst::dot.$ext;
            if(file_put_contents($tempFile, $img)){
                return self::uploadImage($tempFile,$path,$uploadImageName);
            }else{
                \Error\ErrorModel::throwException(\Error\CodeConfigModel::imageUploadFailed);
            }
        }else{
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::imageExtensionsWrong);
        }
    }


    /**
     * 将本地图片上传到OSS
     * @param $filePath 本地图片路径(包括文件名)
     * @param $path 上传到OSS服务器的中间路径
     * @param $uploadImageName 上传到OSS服务器的图片名称
     * @return mixed
     * @throws \Exception
     * @throws \OSS\Core\OssException
     */
    public static function uploadImage($filePath,$path,$uploadImageName){
        $bucketName = \OSS\Common::getBucketName();
        $ossClient =  \OSS\Common::getOssClient();
        if (is_null($ossClient)) {
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::ossServerSetError);
        }
        $ossUploadFilePath = $path.$uploadImageName;
        //return $ossUploadFilePath;
        $return = $ossClient->uploadFile($bucketName, $ossUploadFilePath, $filePath);
        return $return['oss-request-url'];
    }

    /**
     * 获取商品图片对应路径
     * @param $goodsImg 图片名称
     * @param int $type 图片规格
     * @return mixed|string 返回图片路径
     */
    public static function getGoodsImgUrl($goodsImg,$width=\Our\ImageConst::goodsListImgSize, $height = 0){
        $width = $width * \Our\ImageConst::sizeScale;
        $height ? $height = $height * \Our\ImageConst::sizeScale : $height = $width;
        if (empty($goodsImg)) {
            $directory =\Our\ImageConst::defaultPath;
            //$goodsImg = str_ireplace('.', '_' . $type . '.', 'default_goods_image.gif');
            $goodsImg .= 'default_goods_image.gif';
        }else{
            $storeId = substr ( $goodsImg, 0, strpos ( $goodsImg, '_' ) );
            $directory = \Our\ImageConst::goods.$storeId.\Our\NameConst::slash;
            //$goodsImg = str_ireplace('.', '_' . $type . '.', $goodsImg);
            //$goodsImg .= '?x-oss-process=image/resize,m_pad,h_226,w_334';
        }
        $goodsImg =  \Our\Common::getStaticFile($goodsImg,$directory);
        if($width > 0) {
            $goodsImg .= "?x-oss-process=image/resize,m_fill,h_{$height},w_{$width}";
        }
        return $goodsImg;
    }

    public function getStoreLabel($storeLabel, $directory = \Our\ImageConst::storeLabel,$width=\Our\ApiConst::zero,$height=\Our\ApiConst::zero){
        $storeLableImage = \Our\Common::getStaticFile($storeLabel, $directory);
        if($width){
            if(!$height){
                $height = $width;
            }
            $storeLableImage .= "?x-oss-process=image/resize,m_fill,h_{$height},w_{$width}";
        }
        return $storeLableImage;
    }

    public function getGoodsImgWithUrl($goodsImgUrl,$width=\Our\ImageConst::goodsListImgSize, $height = 0) {
        $width = $width * \Our\ImageConst::sizeScale;
        $height ? $height = $height * \Our\ImageConst::sizeScale : $height = $width;
        $goodsImgUrl .= "?x-oss-process=image/resize,m_fill,h_{$height},w_{$width}";
        return $goodsImgUrl;
    }
    public static function getTopClassAdvImageUrl($gcId){
        $fileName = \Our\ImageConst::topClassAdvImagePrefis.$gcId.\Our\NameConst::jpgSuffix;
        $gcImageUrl = \Our\Common::getStaticFile($fileName,\Our\ImageConst::defaultPath);
        return $gcImageUrl;
    }


    /**
     * 设置文件名称 不包括 文件路径
     *
     * 生成(从2000-01-01 00:00:00 到现在的秒数+微秒+四位随机)
     */
    public static function getFileName($fprefix=''){
        $tmp_name = sprintf('%010d',time() - 946656000)
            . sprintf('%03d', microtime() * 1000)
            . sprintf('%04d', mt_rand(0,9999));
        $file_name = (empty ( $fprefix ) ? '' : $fprefix . '_')
            . $tmp_name;
        return $file_name;
    }



    public static function saveWxImage($data)
    {
        $fileName = isset($data['image'])&&$data['image']?$data['image']:$data['memberAvatar'];
        //$fileName ='data';
        if (!empty($_FILES[$fileName]['tmp_name'])) {
            $savePath = ImageConst::uploadTypes[$data['type']];
            $res = self::uploadImage($_FILES[$fileName]['tmp_name'], $savePath, ImageUtil::getFileName($data['type']));
            $fileName = basename($res);
            return array(
                'fileName' => $fileName,
                'url' => $res
            );
        }
        return false;


    }

}
