<?php
namespace app\modules\logic\model;
use Yii;
use yii\base\Exception;
use yii\db\Query;
use yii\db\ActiveRecord;
class BaseModel extends ActiveRecord{

	public $table = NULL; //{{%lawyer_set}}
	public $pk = 'id';
	/**
	 * [__construct 数据操作-构造方法]
	 * @param [type] $table [description]
	 */
	public function __construct($table = NULL) {
		$this->table = $table;
	}
	/**
	 * [save 创建，更新数据库公用方法]
	 * @param  [type]  $data [description]
	 * @param  integer $id   [description]
	 * @return [type]        [description]
	 */
	public function saveUs($data, $id = 0) {
		if ((int) $id > 0) {
			$res = $this->_update($id, $data);
			return $res;
		} else {
			$res = $this->_create($data);
			return $res;
		}

	}
	/**
	 * [create 单个创建数据库方法]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	private function _create($data) {

		$db = Yii::$app->getDb();

		$db->createCommand()->insert($this->table, $data)->execute();

		$id = $db->getLastInsertID();

		if ($id > 0) {
			return isset($data[$this->pk]) ? $data[$this->pk] : $id;
		} else {
			return NULL;
		}

	}
	/**
	 * [remove 删除数据库方法]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	private function _remove($id) {

		$db = Yii::$app->getDb();
		$re = $db->createCommand()->delete($this->table, ["{$this->pk}" => $id])->execute();
		return boolval($re);

	}
	/**
	 * [update 更新数据库方法]
	 * @param  [type] $id   [description]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	private function _update($id, $data) {

		$db = Yii::$app->getDb();
		$tran = $db->beginTransaction();
		try {
			$db->createCommand()->update($this->table, $data, ["$this->pk" => $id])->execute();
			$tran->commit();
			return true;
		} catch (Exception $e) {
			$tran->rollBack();
			return false;
		}

	}

	/**
	 * where条件生成器
	 * @author john.chuan
	 * @param  [type]          $where [description]
	 * cols：['id','name']查询字段
	 * @param  [type]          $query [description]
	 * @return [type]                 [description]
	 */
	public function widgetWhere($where, $query) {

		if (isset($where['cols'])) {
			$query->select($where['cols']);
			unset($where['cols']);
		}

		if (isset($where['scope'])) {
			foreach ($where['scope'] as $key => $value) {
				foreach ($value as $k => $val) {
					$key == 'lt' && $query->andWhere(['>', $k, $val]);
					$key == 'ltt' && $query->andWhere(['>=', $k, $val]);
					$key == 'mt' && $query->andWhere(['<', $k, $val]);
					$key == 'mtt' && $query->andWhere(['<=', $k, $val]);
					$key == 'neq' && $query->andWhere(['<>', $k, $val]);
				}
			}
			unset($where['scope']);
		}

		if (isset($where['in'])) {

			foreach ($where['in'] as $key => $value) {
				$query->andWhere(['in', $key, $value]);
			}
			unset($where['in']);
		}

		if (isset($where['not_in'])) {
			foreach ($where['not_in'] as $key => $value) {
				$query->andWhere(['not in', $key, $value]);
			}
			unset($where['not_in']);
		}
		/*where(['between','dyn_id', 1,30])*/
		if (isset($where['between'])) {
			foreach ($where['between'] as $key => $value) {
				$query->andWhere(['between', $key, $value[0],$value[1]]);
			}
			unset($where['between']);
		}
		/*['like', 'name', 'test']*/
		if (isset($where['like'])) {
			foreach ($where['like'] as $key => $value) {
				$query->andWhere(['like', $key, $value]);
			}
			unset($where['like']);
		}
		if (isset($where['or_like'])) {
			foreach ($where['or_like'] as $key => $value) {
				$query->orWhere(['like', $key, $value]);
			}
			unset($where['or_like']);
		}
		if (isset($where['or_equal'])) {
			foreach ($where['or_equal'] as $key => $value) {
				$query->orWhere(['=', $key, $value]);
			}
			unset($where['or_equal']);
		}
		if (isset($where['group'])) {
			foreach ($where['group'] as $key => $value) {
				$group[] = $value;
			}
			$query->groupBy(implode($group, ','));
			unset($where['group']);
		}
		/*sum 为数组*/
		if (isset($where['sum'])) {
			$query->addSelect($where['sum']);
			unset($where['sum']);
		}
		//已处理
		if (isset($where['order'])) {
			$order = array();
			foreach ($where['order'] as $key => $value) {
				$order[] = $key . ' ' . $value;
			}
			$query->orderBy(implode($order, ','));
			unset($where['order']);
		}

		if (isset($where['custom'])) {
			$query->andWhere($where['custom']);
			unset($where['custom']);
		}

		if (isset($where['limit'])) {
			$query->limit($where['limit']);
			unset($where['limit']);
		}
        if (isset($where['offset'])) {
            $query->offset($where['offset']);
            unset($where['offset']);
        }
		if (!empty($where)) {
			$query->andWhere($where);
		}
	}

	/**
	 * 获取数据总数
	 *
	 * @param  array $where //查询条件
	 * @access public
	 * @copyright 20150729
	 * @return integer
	 */
	public function getWidgetTotal($where = array()) {
		$query = new Query();
		$query->from($this->table);
		$this->widgetWhere($where, $query);
		$res = $query->count();
		return $res;

	}
	/**
	 * 分页查询
	 *
	 * @param  array    $where  //查询条件
	 * @param  integer  $limit  //查询条数
	 * @param  integer  $offset //偏移量 [页码]
	 * @access public
	 * @copyright 20150729
	 * @return array
	 */
	public function getWidgetPages($where = array(), $limit = 20, $offset = 0) {
		$query = new Query();
		$query->from($this->table);

		if (isset($where['limit'])) {
			unset($where['limit']);
		}
        if (isset($where['offset'])) {
            unset($where['offset']);
        }
		$this->widgetWhere($where, $query);
		$query->limit($limit);
		$query->offset($offset);
		$res = $query->all();
        //echo $query->createCommand()->getRawSql();
        //exit();
		return $res;
	}
	/**
	 * 读取单条数据
	 *
	 * @param  integer | array $where   //唯一ID 或者 查询条件数组
	 * @access public
	 * @copyright 20150729
	 * @return array
	 */
	public function getWidgetRow($where) {
		$query = new Query();
		$query->from($this->table);
		if (is_array($where)) {
			$this->widgetWhere($where, $query);
		} else {
			$query->where(["{$this->pk}" => $where]);
		}
		$res = $query->one();
		return $res;
	}
	/**
	 * [getWidgetRows 读取多条数据]
	 * @param  [type] $where [description]
	 * @return [type]        [description]
	 */
	public function getWidgetRows($where) {
		$query = new Query();
		$query->from($this->table);
		$this->widgetWhere($where, $query);
		$res = $query->all();
        //echo $query->createCommand()->getRawSql();
        //exit();
		return $res;
	}
	/**
	 * [delWidgetRows 条件删除多条数据---慎用]
	 * @param  [type] $where [description]
	 * @return [type]        [description]
	 */
	/*public function delWidgetRows($where)
		    {
		        $this->widgetWhere($where);
		        $this->db->delete($this->table);
		        if ($this->db->affected_rows() > 0) {
		            return TRUE;
		        }
		        else {
		            return FALSE;
		        }
	*/
	/**
	 * [updateWidgetRows 按多个条件更新---慎用]
	 * @param  [type] $data  [更新内容]
	 * @param  [type] $where [更新条件]
	 * @return [type]        [description]
	 */
	/*public function updateWidgetRows($data,$where){
		        $this->widgetWhere($where);
		        $res = $this->update($this->table, $data);
		        return $res;
	*/
}
