<?php
namespace Qii\Driver;

use Qii\Exceptions\InvalidParams;
use stdClass;

/**
 * 使用方法
 *
 *
 */
final class EasyORM {
    protected $_easyORM = array();

    /**
     * @throws InvalidParams
     */
    public function __construct(\Qii\Base\Rules $rules) {
        $this->_easyORM = new stdClass();
        $this->clean();
        $this->cleanCondition();
        $this->_easyORM->db = \Qii::getInstance("\Qii\Driver\Model")->db;
        $this->setRules($rules);
        $this->setFields($rules->fields());
        $this->setResponse(new Response());
    }

    /**
     * 获取db属性
     *
     * @return mixed
     */
    final public function getDB() {
        return $this->_easyORM->db;
    }

    /**
     * 设置验证规则
     *
     * @param \Qii\Base\Rules $rules
     * @return void
     */
    final public function setRules(\Qii\Base\Rules $rules) {
        $this->_easyORM->rules = $rules;
        return $this;
    }

    /**
     * 返回 rules
     *
     * @return mixed
     */
    final public function getRules() {
        return $this->_easyORM->rules;
    }

    /**
     * 设置需要操作的表名称
     *
     * @param string $table 表名
     * @return mixed
     */
    final public function setTable($table) {
        $this->_easyORM->rules->setTable($table);
        return $this;
    }

    /**
     * 获取表名
     * 
     * @return mixed
     */
    final public function getTable() {
        return $this->_easyORM->rules->getTable();
    }
    /**
     * 设置表字段
     *
     * @param array $fields
     * @return void
     * @throws
     */
    final public function setFields($fields = array()) {
        if(!is_array($fields)) {
            throw new InvalidParams("数据表字段不能为空");
        }
        $this->_easyORM->fields = new Fields($fields);
        return $this;
    }

    /**
     * 设置查询的 Fields
     * @param array|string $fields
     * @return $this
     */
    final public function setQueryFields($fields) {
        if(!$fields) return $this;
        if(is_array($fields)) {
            $this->_easyORM->queryFields = join(",", $fields);
        }else{
            $this->_easyORM->queryFields = $fields;
        }
        return $this;
    }

    /**
     * 清除 fields
     * @return void
     */
    final public function cleanQueryFields() {
        $this->_easyORM->queryFields = '*';
        return $this;
    }

    /**
     * @param array $args [[key, $value],...]
     * @return EasyORM
     */
    final public function where($args) {
        if(!is_array($args)) {
            return $this;
        }
        $this->_easyORM->where = array();
        foreach ($args as $key => $val) {
            $explode = explode(":", $key)[0];
            if($this->_easyORM->fields->hasField($explode)) {
                $this->_easyORM->where[$key] = $val;
            }
        }
        return $this;
    }

    /**
     * 清除where条件
     * @return $this
     */
    final public function cleanWhere() {
        $this->_easyORM->where = array();
        return $this;
    }

    /**
     * 清除like
     *
     * @return $this
     */
    final public function cleanLike() {
        $this->_easyORM->like = array();
        return $this;
    }
    /**
     * 获取所有字段
     *
     * @return mixed
     */
    public function getFields() {
        return $this->_easyORM->fields->getFields();
    }

    /**
     * 设置表字段
     *
     * @param $name
     * @param $val
     * @return $this
     */
    public function __set($name, $val)
    {
        if($this->_easyORM->fields->hasField($name)) {
            $this->_easyORM->fields->$name = $val;
        } else {
            $this->_easyORM->$name = $val;
        }

        return $this;
    }

    /**
     * 获取field属性
     * @param string $name
     * @return void
     */
    public function __get($name) {
        if($this->_easyORM->fields->hasField($name)) return $this->_easyORM->fields->$name;
        if(isset($this->_easyORM->$name)) return $this->_easyORM->$name;
        return false;
    }
    /**
     * isset
     * @param string $name isset的key
     * @return bool
     */
    public function __isset($name) {
        if($this->_easyORM->fields->hasField($name)) return isset($this->_easyORM->fields->$name);
        if($this->_easyORM->$name) return true;
        return false;
    }
    /**
     * unset
     * @param  sting $name unset的key
     * @return void
     */
    public function __unset($name) {
        if(isset($this->_easyORM->fields->$name)) unset($this->_easyORM->fields->$name);
    }
    /**
     * 获取字段的值
     * @param string $field 字段名称
     * @return mixed
     */
    public function getFieldValue($field) {
        return $this->_easyORM->fields->getField($field);
    }

    /**
     * 获取所有字段和值
     *
     * @return mixed
     */
    public function getValues() {
        return $this->_easyORM->fields->getValues();
    }

    /**
     * 返回所有设置的值
     *
     * @return mixed
     */
    final public function getValueAsArray() {
        return $this->_easyORM->fields->getValueAsArray();
    }
    /**
     * @param Response $response
     * @return void
     */
    final public function setResponse(Response $response) {
        $this->_easyORM->response = $response;
        return $response;
    }

    /**
     * @return EasyORM
     */
    final public function clean(){
        $this->_easyORM->limit = array();
        $this->_easyORM->response = null;
        $this->_easyORM->privateKeys = array();
        $this->_easyORM->where = array();
        $this->_easyORM->like = array();
        $this->_easyORM->exclude = array();
        $this->_easyORM->orderBy = array();
        $this->_easyORM->queryFields = '*';
        $this->_easyORM->groupBy = array();
        return $this;
    }

    /**
     * 清空所有的条件和字段的值
     *
     * @return EasyORM
     */
    final public function cleanCondition() {
        $this->cleanPrivateKey();
        $this->cleanWhere();
        $this->cleanLike();
        $this->cleanLimit();
        $this->cleanExcluded();
        $this->cleanQueryFields();
        $this->cleanOrderBy();
        $this->cleanGroupBy();
        return $this;
    }

    /**
     * 清除所有设置了字段的值
     *
     * @return EasyORM
     */
    final public function cleanFieldsVal(){
        $this->_easyORM->fields->cleanAllFieldsVal();
        return $this;
    }

    /**
     * 批量设置值
     *
     * @param $values
     * @return EasyORM
     */
    final public function setValues($values) {
        if(!is_array($values)) return $this;
        foreach ($values as $key => $value) {
            $this->_easyORM->fields->hasField($key) && $this->_easyORM->fields->$key = $value;
        }
        return $this;
    }
    /**
     * 设置 private key，主键必须有设置值，否则不接收
     * @param array|string $keys
     * @return EasyORM
     */
    final public function setPrivateKey($keys = array())
    {
        if(empty($keys)) {
            return $this;
        }
        if(!is_array($keys)) {
            $this->_easyORM->fields->hasField($keys) && $this->_easyORM->privateKeys[] = $keys;
            return $this;
        }
        foreach ($keys as $key) {
            $this->_easyORM->fields->hasField($key) && $this->_easyORM->privateKeys[] = $key;
        }
        return $this;
    }

    /**
     * 返回当前设置的主键
     *
     * @return mixed
     */
    final public function getPrivateKey() {
        return $this->_easyORM->privateKeys;
    }

    /**
     * 移除主键
     *
     * @param array|string $keys
     * @return EasyORM
     */
    final public function removePrivateKey($keys = array()) {
        if(!is_array(key)) {
            if(isset($this->_easyORM->privateKeys[$keys])) unset($this->_easyORM->privateKeys[$keys]);
            return $this;
        }
        foreach ($keys as $key) {
           if(isset($this->_easyORM->privateKeys[$key])) unset($this->_easyORM->privateKeys[$key]);
        }
        return $this;
    }
    /**
     * 获取主键对应的值
     * @return array
     */
    final protected function getPrivateValue() {
        $data = array();
        foreach ($this->_easyORM->privateKeys AS $key) {
            $data[$key] = $this->_easyORM->fields->getField($key);
        }
        return $data;
    }

    /**
     * 清除主键
     *
     * @return EasyORM
     */
    final public function cleanPrivateKey() {
        $this->_easyORM->privateKeys = array();
        return $this;
    }

    /**
     * 设置排除的数据列
     *
     * @param array $values 值
     * @return EasyORM
     */
    final public function setExcluded($values = array()){
        if(!is_array($values)) {
            return $this;
        }
        foreach ($values as $key => $value) {
            $this->_easyORM->fields->hasField($key) && $this->_easyORM->exclude[$key] = $value;
        }
        return $this;
    }

    /**
     * 清除排除选项
     *
     * @return EasyORM
     */
    final public function cleanExcluded() {
        $this->_easyORM->exclude = array();
        return $this;
    }

    /**
     * 设置limit限制
     *
     * @param int $start limit start
     * @param int $size size
     * @return EasyORM
     */
    final public function setLimit($start, $size = 20) {
        $this->_easyORM->limit = [$start, $size];
        return $this;
    }

    /**
     * 清除limit限制
     * @return EasyORM
     */
    final public function cleanLimit() {
        $this->_easyORM->limit = array();
        return $this;
    }

    /**
     * @return Qii\Driver\Response|mixed
     */
    final public function save() {
        $this->_easyORM->rules->addForceValidKey($this->_easyORM->rules->getValidFieldsForSave());
        $this->_easyORM->rules->addValues($this->_easyORM->fields->getValueAsArray());
        $verify = $this->_easyORM->rules->verify();
        if(!$verify['valid']) {
            return Response::FailValidate('validate', array('_result' => \Qii::i($verify['code'], $verify['msg'])
            , 'fields' => array('field' => $verify['data'], 'message' => $verify['errorInfo']), 'message' => $verify['msg']));
        }
        if (($this->_easyORM->privateKeys || $this->_easyORM->exclude || $this->_easyORM->where) && $this->exist()->count() > 0) {
            return Response::Exist('save', array('_result' => \Qii::i(1511, join(',', $this->getPrivateValue()))));
        }
        $map = $this->_easyORM->rules->getValues();
        $result = $this->_easyORM->db->insertObject($this->_easyORM->rules->getTable(), $map);
        if($this->_easyORM->db->isError()) {
            return $this->_easyORM->db->getResponse();
        }
        return Response::Success('save', array('_result' => $result));
    }

    /**
     * like([['key' => 'value'], ...]->count() like([['key' => 'value'], ...]->lists()
     * @param $values
     * @return EasyORM
     */
    final public function like($values = array()) {
        //未指定like字段
        if(!is_array($values)) {
            return $this;
        }
        $query = array();
        foreach ($values as $key => $value) {
            if(!$this->_easyORM->fields->hasField($key)) {
                continue;
            }
            $query[$key] = $value;
        }
        $this->_easyORM->like = $query;
        return $this;
    }

    /**
     * 获取指定条件返回数据的行数
     *
     * @return Qii\Driver\Response
     */
    final public function count() {
        $query = $this->getValueAsArray();
        if($this->_easyORM->where && is_array($this->_easyORM->where)) {
            foreach ($this->_easyORM->where as $key => $value) {
                $query[$key] = $value;
            }
        }
        //字段值作为where条件, 仅list和count用
        $value = $this->getValueAsArray();
        foreach ($value as $key => $val) {
            $query[$key] = $val;
        }
        $countFields = ' COUNT(1) as count';
        if($this->_easyORM->queryFields != "*") {
            $countFields = $this->_easyORM->queryFields;
        }
        $result = $this->_easyORM->db
            ->fields($countFields)
            ->limit(1)
            ->where($query)
            ->like($this->_easyORM->like)
            ->exclude($this->_easyORM->exclude)
            ->groupBy($this->_easyORM->groupBy)
            ->selectOne($this->_easyORM->rules->getTable());
        if ($this->_easyORM->db->isError()) {
            return $this->_easyORM->db->getResponse();
        }
        return Response::Success('exist', array('_result' => $result));
    }
    /**
     * 更新数据
     *
     * @return Qii\Driver\Response
     */
    final public function update() {
        $this->_easyORM->rules->addForceValidKey($this->_easyORM->rules->getValidFieldsForUpdate());
        $this->_easyORM->rules->addValues($this->_easyORM->fields->getValueAsArray());
        $verify = $this->_easyORM->rules->verify();
        if(!$verify['valid']) {
            return Response::FailValidate('validate', array('_result' => \Qii::i($verify['code'], $verify['msg'])
            , 'fields' => array('field' => $verify['data'], 'message' => $verify['errorInfo']), 'message' => $verify['msg']));
        }
        if (($this->_easyORM->privateKeys || $this->_easyORM->exclude) && $this->exist()->count() == 0) {
            return  Response::NotExist('update', array('_result' => \Qii::i(1512, join(',', $this->getPrivateValue()))));
        }
        $where = $this->getWhereCondition();
        //merge like 字段
        if($this->_easyORM->like) {
            $where = array_merge($this->_easyORM->like, $where);
        }
        $map = $this->_easyORM->rules->getValues();
        $result = $this->_easyORM->db->updateObject($this->_easyORM->rules->getTable(), $map, $where);
        if ($this->_easyORM->db->isError()) {
            return $this->_easyORM->db->getResponse();
        }
        return Response::Success('_update', array('_result' => $result));
    }

    /**
     * 指定字段的值 + step
     *
     * $attr = new EasyDrive();
     * $attr->visit = 1;
     * $attr->where(['uid' => 1])->incr();
     *
     * @return mixed|Qii\Driver\Response
     */
    final public function incr() {
        $value = $this->_easyORM->fields->getValueAsArray();
        if(!is_array($value) || count($value) == 0) {
            return Response::FailUpdate('_incr', array('_result' => '未指定incr的key'));
        }
        $incrFields = array();
        $privateKeys = $this->getPrivateKey();
        foreach ($value as $key => $step) {
            //去掉private的值
            if(in_array($key, $privateKeys)) continue;
            if($step == 0) continue;
            if($step < 0) {
                $incrFields[$key .":minus"] = $step * -1;
                continue;
            }
            $incrFields[$key .':plus'] = $step;
        }
        if(count($incrFields) == 0){
            return Response::FailUpdate('_incr', array('_result' => '未指定incr的步长'));
        }
        $fieldsAndValues = $this->getWhereCondition();
        $result = $this->_easyORM->db
            ->set($incrFields)
            ->where($fieldsAndValues)
            ->like($this->_easyORM->like)
            ->exclude($this->_easyORM->exclude)
            ->update($this->_easyORM->rules->getTable());

        if ($this->_easyORM->db->isError()) {
            return $this->_easyORM->db->getResponse();
        }
        return Response::Success('_incr', array('_result' => $result));
    }

    /**
     * 更新数据只验证传过来的参数是否正确
     *
     * @return mixed|Qii\Driver\Response
     */
    final public function updateFields() {
        $values = $this->_easyORM->fields->getValueAsArray();
        $this->_easyORM->rules->addForceValidKey(array_keys($values));
        $this->_easyORM->rules->addValues($values);
        $verify = $this->_easyORM->rules->verify();
        if(!$verify['valid']) {
            return Response::FailValidate('validate', array('_result' => \Qii::i($verify['code'], $verify['msg'])
            , 'fields' => array('field' => $verify['data'], 'message' => $verify['errorInfo']), 'message' => $verify['msg']));
        }
        if (($this->_easyORM->privateKeys || $this->_easyORM->exclude) && $this->exist()->count() == 0) {
            return Response::NotExist('update', array('_result' => \Qii::i(1512, join(',', $this->getPrivateValue()))));
        }
        $where = $this->getWhereCondition();
        //merge like 字段
        if($this->_easyORM->like) {
            $where = array_merge($this->_easyORM->like, $where);
        }
        $map = $this->_easyORM->rules->getValues();
        $result = $this->_easyORM->db->updateObject($this->_easyORM->rules->getTable(), $map, $where);
        if ($this->_easyORM->db->isError()) {
            return $this->_easyORM->db->getResponse();
        }
        return Response::Success('_update', array('_result' => $result));
    }
    /**
     * 返回所有数据
     *
     * @return mixed
     */
    final public function lists() {
        if($this->_easyORM->limit && count($this->_easyORM->limit) > 0) {
            $this->_easyORM->db->limit($this->_easyORM->limit[0], $this->_easyORM->limit[1]);
        }
        $fieldsAndValues = $this->getWhereCondition();
        //字段值作为where条件, 仅list和count用
        $value = $this->getValueAsArray();
        foreach ($value as $key => $val) {
            $fieldsAndValues[$key] = $val;
        }
        $result = $this->_easyORM->db
            ->fields($this->_easyORM->queryFields)
            ->where($fieldsAndValues)
            ->like($this->_easyORM->like)
            ->exclude($this->_easyORM->exclude)
            ->groupBy($this->_easyORM->groupBy)
            ->orderBy($this->_easyORM->orderBy)
            ->selectRows($this->getTable());
        if ($this->_easyORM->db->isError()) {
            return $this->_easyORM->db->getResponse();
        }
        return Response::Success('lists', array('_result' => $result));
    }

    /**
     * 设置order by
     * @param $orderBy
     * @return EasyORM
     */
    final public function setOrderBy($orderBy) {
        if(!$orderBy) {
            return $this;
        }
        //@todo 验证一下 orderBy 字段
        if(!is_array($orderBy)) {
            $this->_easyORM->orderBy[] = $orderBy;
        }else{
            $this->_easyORM->orderBy = array_merge($this->_easyORM->orderBy, $orderBy);
        }
        return $this;
    }

    /**
     * 清除order by 字段
     *
     * @return EasyORM
     */
    final public function cleanOrderBy() {
        $this->_easyORM->orderBy = array();
        return $this;
    }

    /**
     * 设置group by 条件
     * @param $groupBy
     * @return $this
     */
    final public function setGroupBy($groupBy = array()) {
        if(!$groupBy) {
            return $this;
        }
        $this->_easyORM->groupBy = $groupBy;
        return $this;
    }

    /**
     * 清除 gorup 条件
     * @return $this
     */
    public function cleanGroupBy() {
        $this->_easyORM->groupBy = array();
        return $this;
    }
    /**
     * 删除指定数据
     *
     * @return \Qii\Driver\Response
     */
    final public function remove() {
        if(!$this->_easyORM->privateKeys &&  !$this->_easyORM->exclude && !$this->_easyORM->where) {
            return Response::FAIL('privateKey', \Qii::i(1513));
        }
        $fieldsAndValues = $this->getWhereCondition();

        //检查数据是否存在
        if($this->exist()->count() == 0) {
            return  Response::NotExist('update', array('_result' => \Qii::i(1512, join(',', $this->getPrivateValue()))));
        }

        $result = $this->_easyORM->db
            ->where($fieldsAndValues)
            ->like($this->_easyORM->like)
            ->exclude($this->_easyORM->exclude)
            ->remove($this->_easyORM->rules->getTable());
        if ($this->_easyORM->db->isError()) {
            return $this->_easyORM->db->getResponse();
        }
        return  Response::Success('remove', array('_result' => $result));
    }

    /**
     * 检查数据是否已经存在,并返回一行，只能根据主键查询
     * privateKey 与 exclude、where 条件互斥
     *
     * @return \Qii\Driver\Response
     */
    final public function exist() {
        if(!$this->_easyORM->privateKeys &&  !$this->_easyORM->exclude && !$this->_easyORM->where) {
            $this->setPrivateKey(array_keys($this->getValueAsArray()));
        }
        if(!$this->_easyORM->privateKeys &&  !$this->_easyORM->exclude && !$this->_easyORM->where) {
            return Response::FAIL('privateKey', \Qii::i(1513));
        }
        $fieldsAndValues = $this->getWhereCondition();
        $verify = $this->_easyORM->rules->verifyFields($fieldsAndValues);
        if(!$verify['valid']) {
            return Response::FailValidate('validate', array('_result' => \Qii::i($verify['code'], $verify['msg'])
            , 'fields' => array('field' => $verify['data'], 'message' => $verify['errorInfo'])));
        }

        if($this->_easyORM->exclude) {
            $verify = $this->_easyORM->rules->verifyFields($this->_easyORM->exclude);
            if (!$verify['valid'])  return Response::FailValidate('validate', array('_result' => \Qii::i($verify['code'],  $verify['msg'])
            , 'fields' => array('field' => $verify['data'], 'message' => $verify['errorInfo'])));
        }
        $result = $this->_easyORM->db->limit(1)
            ->fields($this->_easyORM->queryFields)
            ->where($fieldsAndValues)
            ->like($this->_easyORM->like)
            ->exclude($this->_easyORM->exclude)
            ->orderBy($this->_easyORM->orderBy)
            ->selectRow($this->_easyORM->rules->getTable());
        if ($this->_easyORM->db->isError()) {
            return $this->_easyORM->db->getResponse();
        }
        return Response::Success('exist', array('_result' => $result));
    }

    /**
     * 组合where查询条件
     *
     * @return array
     */
    final public function getWhereCondition() {
        $fieldsAndValues = $this->getPrivateValue();
        //merge where 条件的，这里不用merge，因为merge可能会merge出一个0索引的值
        if($this->_easyORM->where && is_array($this->_easyORM->where)) {
            foreach ($this->_easyORM->where as $key => $value) {
                $fieldsAndValues[$key] = $value;
            }
        }
        return $fieldsAndValues;
    }
    /**
     * 使用此方法用于查询某一条数据的某一个字段
     * @useage getXxxByXxx _getXxxByxxx
     *     _getRowById:返回所有字段; _getRowsById:通过id获取所有匹配的数据
     *     _getRowsByFields(['user_id', 'email']) 返回所有匹配的行数据，可以带参数，带参数优先使用参数的字段查询，否则使用设置的fields查询
     *     _getRowByFields(['user_id', 'email']) 返回匹配的一行数据，可以带参数，带参数优先使用参数的字段查询，否则使用设置的fields查询
     *     _getRowByUserId(1) 通过user_id查询，返回所有字段
     *     getNameById：通过id获取name的值； getEmailById：通过id获取email；
     *     getEmailAddressByUserId 通过user_id查询email_address
     *     getEmailByUserId(1) 通过user_id查询，返回email字段
     * 备注：以_开头的才会去走getRow, getRows方法去取所有字段,目前仅支持All, Row, Rows这几个方法
     * @param  string $method [description]
     * @param  mixed $args 请求的参数
     * @return Response
     */
    final public function __call($method, $args)
    {
        $selectType = 'normal';
        if (substr($method, 0, 1) == '_') {
            $selectType = 'system';
            $method = substr($method, 1);
        }
        preg_match('/^(get)(.*)(By)(.*)/', $method, $matches);

        if ($matches && count($matches) == 5 && $matches[1] == 'get') {
            //大写字母匹配下划线，字段中统一用小写字母，在查询的时候使用驼峰结构
            //如：getEmailAddressByUserId 通过user_id查询email_address
            $field = strtolower(preg_replace('/(?<!^)([A-Z])/', '_$1', $matches[2]));

            $method = 'selectRow';
            if ($field == 'rows' && $selectType == 'system') $method = 'selectRows';
            if ($field == 'row' && $selectType == 'system') $method = 'selectRow';
            if (in_array($field, array('all', 'row', 'rows')) && $selectType == 'system') {
                $field = $this->_easyORM->queryFields == '*' ? $this->getFields() : $this->_easyORM->queryFields;
            }
            $value = $this->_easyORM->db->setQuote(array_shift($args));
            $name = strtolower(strtolower(preg_replace('/(?<!^)([A-Z])/', '_$1', $matches[4])));
            $whereArray = array();
            if ($selectType == 'system' && $name == 'fields') {
                //优先使用参数，参数没有就使用设置的fields
                // _getRowsByFields() 返回所有匹配的行数据，可以带参数，带参数优先使用参数的字段查询，否则使用设置的fields查询
                // _getRowByFields() 返回匹配的一行数据，可以带参数，带参数优先使用参数的字段查询，否则使用设置的fields查询
                if(!$value) {
                    $value = $this->_easyORM->fields->getValues();
                }
                foreach ($value AS $val) {
                    $whereArray[$val] = $this->_easyORM->fields->hasField($val) ? $this->_easyORM->fields->getField($val) : '';
                }
            } else {
                $whereArray[$name] = $value;
            }
            $where = array();
            foreach ($whereArray AS $key => $val) {
                if($this->_easyORM->fields->hasField($key)) $where[$key] = $val;
            }

            $result = $this->_easyORM->db->fields($field)->where($where)->$method($this->_easyORM->rules->getTable());
            if ($this->_easyORM->db->isError()) {
                return $this->_easyORM->db->getResponse();
            }
            return Response::Success($method, array('_result' => $result));
        }

        preg_match('/^(exec)(.*)/', $method, $matches);

        if ($matches && count($matches) == 3) {
            $alias = lcfirst($matches[2]);
            if (method_exists($this->_easyORM->db, $alias)) {
                $result = $this->_easyORM->db->{$matches[2]}($this->_easyORM->rules->getTable(), $this->getFields());
                if ($this->_easyORM->db->isError()) {
                    return $this->_easyORM->db->getResponse();
                }
                return Response::Success($matches[2], array('_result' => $result));
            }
            if ($this->_easyORM->db->getAlias($method) && method_exists($this->_easyORM->db, $this->_easyORM->db->getAlias($method))) {
                $this->_easyORM->db->whereArray($this->getFields());
                $result = $this->_easyORM->db->{$this->_easyORM->db->getAlias($method)}($this->_easyORM->rules->getTable());
                if ($this->_easyORM->db->isError()) {
                    return $this->_easyORM->db->getResponse();
                }
                return Response::Success($this->_easyORM->db->getAlias($method), array('_result' => $result));
            }
        }
        //访问方法的别名
        if ($this->_easyORM->db->getAlias($method)) {
            if (method_exists($this->_easyORM->db, $this->_easyORM->db->getAlias($method))) {
                $result = call_user_func_array(array($this->_easyORM->db, $this->_easyORM->db->getAlias($method)), $args);
                if ($this->_easyORM->db->isError()) {
                    return $this->_easyORM->db->getResponse();
                }
                return Response::Success($this->_easyORM->db->getAlias($method), array('_result' => $result));
            }
            \Qii::setError(false, __LINE__, 1106, 'Model', 'Alias ' . $this->_easyORM->db->getAlias($method) . ' does not exist.', print_r($args, true));
            return Response::UndefinedMethod('__call', $this->_easyORM->db->getAlias($method));
        }
        \Qii::setError(false, __LINE__, 1106, 'Model', $method, print_r($args, true));
        return Response::UndefinedMethod('__call', $method);
    }
}