<?php
namespace aliyun;

/**
 * 开放搜索 
 */

class Search{
	
	/**
	 * 初始化
	 */
    public function __construct($config=array()){
    	foreach ($config as $k => $v) {
    		$this->$k=$v;
    	}
		$this->ACCESS_KEY=isset($config['ACCESS_KEY'])?$config['ACCESS_KEY']:C('ALIYUN.ACCESS_KEY');
		$this->ACCESS_SECRET=isset($config['ACCESS_SECRET'])?$config['ACCESS_SECRET']:C('ALIYUN.ACCESS_SECRET');
		$this->apiUrl=C('ALIYUN.SEARCH_APIURL')?C('ALIYUN.SEARCH_APIURL'):'http://opensearch-cn-hangzhou.aliyuncs.com';
		$this->options=C('ALIYUN.SEARCH_OPTIONS')?C('ALIYUN.SEARCH_OPTIONS'):$config['options'];//调试模式
		$this->appName=C('ALIYUN.SEARCH_appName')?C('ALIYUN.SEARCH_appName'):$config['appName'];//为应用名
		$this->suggestName=C('ALIYUN.SEARCH_suggestName')?C('ALIYUN.SEARCH_suggestName'):$config['suggestName'];//下拉提示名称
		vendor('aliyun.OpenSearch.Autoloader.Autoloader');
    }
	
	
	protected function client(){
		return new \OpenSearch\Client\OpenSearchClient($this->ACCESS_KEY, $this->ACCESS_SECRET, $this->apiUrl, $this->options);
	}
	
	public function search($opts){
		$searchClient = new \OpenSearch\Client\SearchClient($this->client());
		$params=new \OpenSearch\Util\SearchParamsBuilder();
		$params->setQuery($opts['query']);// 搜索关键字 string
		$params->setAppName($opts['name']?$opts['name']:$this->appName);// 应用名称  array
		$params->setStart($opts['start']?$opts['start']:0);//搜索起始值 int
		$params->setHits($opts['hits']?$opts['hits']:20);//搜索一页条数 int
		$params->setFormat($opts['format']?$opts['format']:'fulljson');// 返回数据格式 string
		
		$re=$searchClient->execute($params->build());
		$re=json_decode($re->result,true);
		return array(
			'total'=>$re['result']['total'],
			'num'=>$re['result']['num'],
			'data'=>$re['result']['items'],
		);
	}
	
	/**
	 * 添加数据
	 * $data['fields'] 数据   二维数组
	 * $table 表   字符串
	 * $data['cmd'] 操作方法     add update delete字符串
	 * array(
	 * 	array(
	 * 	 'fields'=>array('id'=>1,'name'=>'张三'),
	 *   'cmd'=>'add',
	 *  ),
	 *  array(
	 * 	 'fields'=>array('id'=>2,'name'=>'李四'),
	 *   'cmd'=>'update',
	 *  )
	 * );
	 */
	public function write($data,$table='wdtable'){
		$documentClient = new \OpenSearch\Client\DocumentClient($this->client());
		$docs_to_upload = array();
		foreach ($data as $k => $v) {
			$item = array();
		    $item['cmd'] = $v['cmd'];
			$item["fields"]=$v['fields'];
			$docs_to_upload[] = $item;
		}
		$json = json_encode($docs_to_upload);
		$re = $documentClient->push($json, $this->appName, $table);
	}

}