<?php 
defined('IN_DESTOON') or exit('Access Denied');
class jiaose {
	var $id;
	var $db;
	var $table;
	var $fields;
	var $errmsg = errmsg;

    function jiaose() {
		global $db;
		$this->table = $db->pre.'game_jiaose';
		$this->db = &$db;
		$this->fields = array('id','gamename','dengji','zhiye','gameid','username','listorder');
    }

	function pass($post) {
		global $L;
		if(!is_array($post)) return false;
		if(!$post['gamename']) return "角色名称不能为空";
		if(!$post['dengji']) return "角色等级不能为空";
		if(!$post['zhiye']) return "角色职业不能为空";
		return true;
	}

	function set($post) {
		global $DT_TIME, $_username;
		$post['edittime'] = $DT_TIME;
		$post['username'] = $_username;
		$post['listorder'] = intval($post['listorder']);
		if($this->id) {
			//$post['editor'] = $_username;
		} else {
			$post['addtime'] = $DT_TIME;
		}
		$post = dhtmlspecialchars($post);		
		return array_map("trim", $post);
	}

	function get_one($condition = '') {
        return $this->db->get_one("SELECT * FROM {$this->table} WHERE id=$this->id $condition");
	}

	function get_list($condition, $order = 'listorder ASC,id ASC') {
		global $MOD, $pages, $page, $pagesize, $offset, $sum;
		if($page > 1 && $sum) {
			$items = $sum;
		} else {
			$r = $this->db->get_one("SELECT COUNT(*) AS num FROM {$this->table} WHERE $condition");
			$items = $r['num'];
		}
		$pages = pages($items, $page, $pagesize);
		$lists = array();
		$result = $this->db->query("SELECT * FROM {$this->table} WHERE $condition ORDER BY $order LIMIT $offset,$pagesize");
		while($r = $this->db->fetch_array($result)) {
			$r['adddate'] = timetodate($r['addtime'], 5);
			$r['editdate'] = timetodate($r['edittime'], 5);
			$lists[] = $r;
		}
		return $lists;
	}

	function add($post) {
		global $MOD, $L;
		$post = $this->set($post);
		$sqlk = $sqlv = '';
		foreach($post as $k=>$v) {
			if(in_array($k, $this->fields)) { $sqlk .= ','.$k; $sqlv .= ",'$v'"; }
		}
        $sqlk = substr($sqlk, 1);
        $sqlv = substr($sqlv, 1);
		$this->db->query("INSERT INTO {$this->table} ($sqlk) VALUES ($sqlv)");
		$this->id = $this->db->insert_id();		
		return $this->id;
	}

	function edit($post) {
		$post = $this->set($post);
		$sql = '';
		foreach($post as $k=>$v) {
			if(in_array($k, $this->fields)) $sql .= ",$k='$v'";
		}
        $sql = substr($sql, 1);
	    $this->db->query("UPDATE {$this->table} SET $sql WHERE id=$this->id");
		return true;
	}

	function delete($id, $all = true) {
		global $MOD, $L;
		if(is_array($id)) {
			foreach($id as $v) { $this->delete($v); }
		} else {
			$this->id = $id;
			$this->db->query("DELETE FROM {$this->table} WHERE id=$id");
		}
	}

	function _($e) {
		$this->errmsg = $e;
		return false;
	}
}
?>