<?php


namespace app\admin\common;
use think\facade\Cache;

class Ocr
{
    private  $name="hw98795781";
    private  $id="0b5f3e336280f3c91f09c01ad29e253e";
    private  $password="wyhtQazwsx12";
    public   $region="cn-north-4";
    public   $project_id	="0b5f50097c80f2722fd7c01af96659ce";
    private  $auth_api="https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens?nocatalog=1";
    public  $token="";

    public  function GetToken(){
        $params=[
            "auth"=>[
                "identity"=>[
                    "methods"=>["password"],
                    "password"=>[
                        "user"=>[
                            "domain"=>["name"=>$this->name],
                            "name"=>$this->name,
                            "password"=>$this->password
                        ]
                    ]
                ],
                "scope"=>[
                    "project"=>["name"=>$this->region,"id"=>$this->project_id]
                ]
            ]
        ];
        $this->token=Cache::get("x-auth-token");
        if($this->token==""){
            $result = post($this->auth_api,json_encode($params));
            $data =explode("\r\n",$result);
            array_walk($data,function (&$val,$key){
                $temp = explode(":",$val);
                if(count($temp)>1){
                    $val=[$temp[0]=>$temp[1]];
                }

            });
            $token=array_column($data,"X-Subject-Token");
            $this->token= $token[0];
            Cache::set("x-auth-token",$token[0],23*3600);
        }
    }
    public function query($img="",$url=""){
        if($img==""&&$url==""){
           return  ["code"=>1003,"msg"=>"图片识别失败"];
        }
        $this->GetToken();
        $header=["x-auth-token:" .$this->token,"Content-Type:application/json;charset=UTF-8"];
        $urlc ="https://ocr.cn-north-4.myhuaweicloud.com/v2/".$this->project_id."/ocr/business-license";
        $param=["url"=>$url,"image"=>$img];
        $key = post2($urlc,json_encode($param),$header);
        if($key==false){
            $return = ["code"=>1003,"msg"=>"图片识别失败"];
        }else{
            $return = ["code"=>0,"msg"=>"图片识别成功","data"=>json_decode($key,true)];
        }
        return $return;
    }
}