<?php

namespace DAO;
use Mysql\LinkMySQLModel;
use Our\ApiConst;
use Our\DbNameConst;

/**
 * 数据读取模型抽象类
 *
 * @package DAO
 * @author iceup <sjlinyu@qq.com>
 */
abstract class AbstractModel {

    public $db;
    public $dbName;
    public function __construct($dbName=DbNameConst::salveDBConnectName)
    {
        $this->dbName=$dbName;
        $this->init();
    }
    public function setDb($dbLink=''){
            if( empty($dbLink) )
            {
                $this->db=LinkMySQLModel::get();
            }else{
                $this->db=LinkMySQLModel::get($dbLink);
            }
    }
    public function unsetDb(){
        unset($this->db);
       // LinkMySQLModel::unsetDbConecet();
    }
    /**
     * 捕获dao中没有的方法，直接访问mysql中相应的类的方法
     * 
     * @param string $method
     * @param array $args
     * @return mixd
     */
    public function __call($method, $args) {
        $className      = get_class($this);
        $mysqlClassName = '$mysql = ' . str_replace('DAO', '\Mysql', $className) . '::getInstance();';
        eval($mysqlClassName);

        $excutePhp = '$result = $mysql->$method(_args_);';

        $string = '';
        foreach ($args as $key => $arg) {
            $string .= '$args[' . $key . '],';
        }

        $excutePhp = str_replace('_args_', rtrim($string, ','), $excutePhp);

        eval($excutePhp);

        return $result;
    }

    public function lists($where=array(),$order='',$field='*',$pageIndex=0,$pageSize=20,$group = null){
        $this->db->from($this->_tableName);
        $this->db->where($where);
        $count=$this->db->fetchNum();
        $this->db->from($this->_tableName);
        $this->db->where($where);
        $this->db->select($field);
        if($group){
            $this->db->group($group);
        }
        if($order){
            if(is_array($order)){
                foreach($order as $key =>$value){
                    $this->db->order($key,$value);
                }
            }
        }
        $pageIndex=$pageIndex+\Our\ApiConst::one;
        $this->db->page($pageIndex,$pageSize);
        $lists=$this->db->fetchAll();
        $returnData['list']=$lists?$lists:array();
        $returnData['totalCount']=$count;
        return $returnData;
    }


    public function getListNotNull($list){
        foreach($list as &$li){
            foreach($li as &$v){
                if($v==null){
                    $v='';
                }
            }
        }
        return $list;
    }


}
