<?php
/**
  * @method 百度本地识别
  * @author soul
  */
class OthBaiduOcr
{
	public $hostArr = null;
	public $cachefile = '';
	public function __construct()
	{
		$this->cachefile =  mvc::$cfg['LOGS'].'baiduocr_chk.php';
		$this->hostArr = mvc::$cfg['BAIDUOCRLOCAL'];
	}
	
	/**
	 * @method 百度本地识别  已换到飞浆
	 * @param  {"rotate":90,"image":"base64"}
	*/
	public function ocr($data)
	{
		if(!is_array($data)) $data = ['image'=>$data];
		$MainOcr = new MainOcr();
		$res =  $MainOcr->paddleOcr($data['image'], ['rotate'=>$data['rotate']]);
		$res['data'] = implode("\r\n", $res['data']);
		return $res;

		$hostKey = $this->getHostkey();
		$url = $this->hostArr[$hostKey].'api/BaiduOcr';
		if(stripos($data['image'], 'data:image') === false)
			$data['image'] = 'data:image/jpg;base64,'.$data['image'];
		if(strlen($data['image']) < 100)
			return ['status'=>true, 'data'=>''];
		if(isset($data['rotate']) && empty($data['rotate']))
			unset($data['rotate']);
		$result = $this->curl($url, $data);
		return $result;
	}

	public function getHostkey()
	{
		if(count($this->hostArr) > 1)
		{
			if(!file_exists($this->cachefile) || (time() - filemtime($this->cachefile)) > 60*10)
			{
				$this->checkStatus();
			}
			$chkres = include($this->cachefile);
		}
		if(empty($chkres['ok'])) $chkres = ['ok'=>array_keys($this->hostArr)];
		shuffle($chkres['ok']);
		$hostKey = $chkres['ok'][0];
		return $hostKey;
	}

	public function checkStatus()
	{
		$chkres = ['ok'=>[], 'no'=>[]];
		foreach($this->hostArr as $hk=>$hv)
		{
			$result = $this->curl($hv.'api/status', $data);
			if($result['status'] && $result['status'] == 1)
			{
				$chkres['ok'][] = $hk;
			}
			else
			{
				$chkres['no'][] = $hk;
			}
		}
		LibFc::ArraySave($chkres, $this->cachefile);
		return LibFc::ReturnData(true, $chkres);
	}

	public function curl($url, $data = [])
	{
		$data = json_encode($data);
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
		$result = curl_exec($ch);
		//var_dump($url, $result);
		$result = json_decode($result, true);
		if($result['code'] == 200)
		{
			return ['status'=>true, 'data'=>trim($result['data'])];
		}
		else
		{
			return ['status'=>false, 'data'=>$result['message']];
		}
	}
}