<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\library\utils;

use think\facade\Request;
use xzncit\OSS;
use app\common\model\Attachment as AttachmentModel;
use app\common\library\file\File as FileUtils;
use app\common\service\Config as ConfigService;
use app\common\service\diy\Setting as SettingService;

/**
 * @package app\common\library\utils
 * @class Image
 * @author xzncit 2023-09-04
 */
class Image {

    /**
     * 会员头像
     * @param $value
     * @param array $options
     * @return mixed|string|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function avatar($value,$options=[]){
        $image  = self::get($value,$options);
        if(empty($image)){
            $domain = trim(env("web_url",Request::domain()),"/");
            $avatar = trim(ConfigService::getArray("users.avatar"),"/");
            return $domain . '/' . $avatar;
        }

        return $image;
    }

    /**
     * 获取图片
     * @param $value
     * @param array $options
     * @return mixed|string|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function thumb($value,$options=[]){
        $image = self::get($value,$options);
        if(empty($image)){
            $site   = SettingService::get(["name"=>"site"]);
            return trim(env("web_url",Request::domain()),"/") . '/' . trim($site["image"]??'',"/");
        }

        return $image;
    }

    /**
     * 获取图片路径
     * @param $value
     * @param array $options
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function get($value,$options=[]){
        $config = array_merge(["domain"=>true,"prefix"=>null],$options);

        if(is_numeric($value)){
            $attachment = AttachmentModel::where("id",$value)->find();
            $value = $attachment["path"]??"";
        }

        $domain = "";
        if($config["domain"]){
            $domain = trim(env("web_url",Request::domain()),"/");
        }

        if(Check::url($value)){
            if(self::parseUrl($value,PHP_URL_HOST) == self::parseUrl($domain,PHP_URL_HOST)){
                $value = self::parseUrl($value);
            }else{
                return $value;
            }
        }

        $image = trim($value,"/");
        if(!empty($config["prefix"])){
            $array        = explode("/",$image);
            $fileName     = end($array);
            $path         = str_replace($fileName,"",$image);
            $prefixPath   = $path . (stripos($config["prefix"],'_') !== false ? $config["prefix"] : $config["prefix"] . '_') . $fileName;
            if(file_exists(FileUtils::getPath() . "public/" . $prefixPath)){
                return $domain . "/" . $prefixPath;
            }
        }

        if(empty($image)){
            return null;
        }

        $module = app('http')->getName();
        $upload = ConfigService::getArray("upload");
        if(in_array($module,["admin"]) && isset($upload["type"]) && $upload["type"] != "local"){
            return OSS::getUrl($upload["type"],$image,$upload[$upload["type"]]);
        }

        if(!empty($image) && !file_exists(FileUtils::getPath() . "public/" . $image)){
            return null;
        }

        return $domain . '/' . $image;
    }

    /**
     * 获取图片 path
     * @param $value
     * @param int $component
     * @return array|false|int|string|null
     */
    public static function parseUrl($value,$component=PHP_URL_PATH){
        return parse_url($value,$component);
    }

    /**
     * 删除 HTML tag attribute
     * @param $content
     * @param array $pattern
     * @param string[] $replacement
     * @return string|string[]|null
     */
    public static function removeAttribute($content,$pattern=[],$replacement=["$1"]){
        if(empty($pattern)){
            $pattern = [
                '/(<img.*?)((data-href)=[\'"].*?[\'"]+)/',
                '/(<img.*?)((style)=[\'"].*?[\'"]+)/',
                '/(<img.*?)((alt)=[\'"].*?[\'"]+)/'
            ];

            $replacement = [];
            for($i=0; $i < count($pattern); $i++){
                $replacement[] = "$1";
            }
        }

        return preg_replace($pattern,$replacement,$content);
    }

    /**
     * 替换图片路径
     * @param $content
     * @param $fn
     * @return mixed
     */
    public static function replace($content,$fn){
        $matches = [];
        preg_match_all('/<img([ ]+)src="([^\"]+)"/i', $content, $matches);

        $array = [];
        foreach($matches[2] as $val){
            if(!in_array($val,$array)){
                $array[] = $val;
                $content = $fn($val,$content);
            }
        }

        return $content;
    }

}