<?php
class testAction extends action
{
    function __construct(){
        parent::__construct();
    }

    function __destruct(){
    }

    function index(){
		/*
		$db = new LibDb();
		$data = [];
		for($i=0;$i<1000;$i++){
			$data[$i] = [
				'name'=> 'name'.($i+1),
				'email'=> 'e'.($i+1).'@qq.com',
				'mb'=> '1862008'. str_pad($i+1,4,'0'),
				'height'=> ($i+1).'01',
				'date'=> date('Y-m-d h:i:s',time()-$i*1000),
			]; 
		}
		$db->Insert('jqgrid',$data);
		print_r($db->Table("select * from jqgrid"));
		*/
    }

    function jqgrid(){
		$t = time();
		$this->set('t',$t);
		$this->put();
    }
	function rules2sql($rules,$groupOp){
		$op = ["eq"=>"='%s'","ne"=>"<>'%s'","le"=>"<='%s'","lt"=>"<'%s'","gt"=>">'%s'","ge"=>">='%s'","cn"=>"like '%%%s%%'","nc"=>"not like'%%%s%%'","nu"=>"=''","nn"=>"<>''"];
		$arr=[];
		foreach($rules as $rule){
			if($rule['op']=='nu'){
				$arr[] = sprintf("(%s='' or %s is null)",$rule['field'],$rule['field']); 
			}else{
				if($rule['data']!='' || $rule['op']=='nn')
					$arr[] = $rule['field'] .' '. sprintf($op[$rule['op']],$rule['data']);
			}
		}
		if(count($arr)>0)
			$where = implode(' '.$groupOp.' ',$arr);
		return $where;
	}
	function groups2sql($groups){
		$where = '';
		$rulesWhere = '';
		$groupsWhere = '';
		$rulesCount = count($groups['rules']);
		$groupsCount = count($groups['groups']);
		if($rulesCount==0 && $groupsCount==0) 
			return '';
		if($rulesCount) 
			$where = $this->rules2sql($groups['rules'], $groups['groupOp']);
		if($groupsCount){
			$arr = [];
			foreach($groups['groups'] as $group){
					$arr[] = '('.$this->groups2sql($group).')';
			}
			$groupsWhere .= implode(' '.$groups['groupOp'].' ',$arr);
		}
		if($groupsWhere){
			if($where=='')
				$where =  $groupsWhere;
			else
				$where .= ' '.$groups['groupOp'] .' '. $groupsWhere;
		}
		return $where;
	}
    function jqgrid_ajax(){
/*
Array
(
    [_search] => false
    [nd] => 1583475097363
    [rows] => 20
    [page] => 1
    [sidx] => 
    [sord] => asc
)
*/		$where = '';
		if($_POST['filters']){
			$groups = json_decode(htmlspecialchars_decode($_POST['filters']),true);
			$where = $this->groups2sql($groups);
			if($where!='') $where = ' AND '.$where;
		}
		$db = new LibDb();
		$sql = "select * from jqgrid where 1=1" . $where;
		$pages = $db->PageLimit($sql,$_POST['page'],$_POST['rows']);
		if($_POST['sidx']){
			$sql.= sprintf(' ORDER BY %s %s',$_POST['sidx'],$_POST['sord']);
		}
		$table = $db->Table($sql.$pages['limit']);
		$rows = '';
		foreach($table as $row){
			$rows[] = $row;
		}
		$footerData = ['mb'=>'合计:','height'=>'23345.00'];
		
		$data = [
			'page'=> $pages['page'],
			'total'=> $pages['total'],
			'records' => $pages['records'],
			"userdata"=> $footerData,
			'rows' => $rows
		];
		echo json_encode($data);
	}
}