<?php

/**
 *--------------------------------------
 * search
 *--------------------------------------
 * @project		: loga
 * @author		: cblee
 * @created		: 2016-07-13
 * @copyright	: (c)2016 AsThis
 *--------------------------------------
 */
defined('PFA_PATH') or exit('Access Denied');

class SearchModl extends Modl {
	protected $sphinx;
	protected $_o_p = array();

	public function __construct() {
		$this->autoCheckFields = false;
		parent::__construct();
	}

	public function analysis_keywords($keywords) {
		$keywords = str_replace(array(',', '，', '  '), ' ', $keywords);
		$keywords = explode(' ', $keywords);
		foreach($keywords as $key => $keyword) {
			$keyword = trim($keyword);
			if(!empty($keyword)) {
				$keywords[$key] = $keyword;
			}
			else {
				unset($keywords[$key]);
			}
		}
		return array_slice(array_unique($keywords), 0, 3);
	}

	public function get_count($keywords = array(), $type = 'A', $keywordType = 'OR') {
		$where = $this->_get_where($keywords, $type, $keywordType);
		if('A' == $type) {
			$rowsNum = M('Article')->get_articleCount($where);
		}
		elseif('S' == $type) {
			$rowsNum = M('SinglePage')->get_singlePageCount($where);
		}
		return $rowsNum;
	}

	public function search($keywords = array(), $limit = '0,20', $type = 'A', $keywordType = 'OR') {
		$where = $this->_get_where($keywords, $type, $keywordType);
		if('A' == $type) {
			$L =  M('Article')->get_articleList($where, 'a_edit_time desc', $limit);
		}
		elseif('S' == $type) {
			$L =  M('SinglePage')->get_singlePageList('', 'all', $limit, $where);
		}
		return $L;
	}

	private function _get_where($keywords, $type, $keywordType) {
		$map = array();
		/* keywords */
		$likeArr = array();
		foreach($keywords as $k => $v) {
			$likeArr[] = array('LIKE', '%'.$v.'%');
		}
		$likeArr[] = $keywordType;
		if('A' == $type) {
			$map['__ARTICLE__.a_title'] = $likeArr;
			$map['__ARTICLE__.a_description'] = $likeArr;
			$map['__ARTICLE__.a_keywords'] = $likeArr;
			$map['_logic'] = 'OR';

			$where = array();
			$where['_complex'] = $map;
			$where['__ARTICLE__.a_status'] = array('EQ', 1);
		}
		elseif('S' == $type) {
			$map['__SINGLE_PAGE__.sp_title'] = $likeArr;
			$map['__SINGLE_PAGE__.sp_description'] = $likeArr;
			$map['__SINGLE_PAGE__.sp_keywords'] = $likeArr;
			$map['__SINGLE_PAGE__.sp_content'] = $likeArr;
			$map['_logic'] = 'OR';

			$where = array();
			$where['_complex'] = $map;
		}

		return $where;
	}

}

?>