<?php
class productAction extends action
{
	private $product = null;
    function __construct(){
        parent::__construct();
		$this->product = new productMod();
    }

    function __destruct(){
    }

	/**
	 * Method 列表数据
	 */
    function list(){
		$where = '';
		if($_POST['filters']){
			$groups = json_decode(htmlspecialchars_decode($_POST['filters']),true);
			$where = $this->groups2sql($groups);
		}
		$data = $this->product->list($where, $_POST['page'], $_POST['rows'], $_POST['sidx'], $_POST['sord']);
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}
	/**
	 * Method 通过关键字取一行数据
	 */
	function getRowByKey($key){
		$row = $this->product->getRowByKey('*',$key);
		if($row){
			$this->exitJson(0,$row);
		}else{
			$this->exitJson(2000);
		}
	}
	/**
	 * Method 唯一值检测
	 */
	function onlyCheck(){
		$result = false;
		$p_id = (empty($_REQUEST['p_id'])) ? 0 : $_REQUEST['p_id'];
		$p_parent_id = $_REQUEST['p_parent_id'];
		$p_name = $_REQUEST['p_name'];
		if($p_id!='' && $p_parent_id!='' && $p_name!=''){
			$where = sprintf("p_id<>'%s' AND p_parent_id='%s' AND p_name='%s'",$p_id, $p_parent_id,$p_name);
			if($this->product->getOne('1',$where)){
				$result = true;
			}
		}
		echo ($result) ? 'false' : 'true'; //存在不通过，不存在通过
	}
	/**
	 * Method 添加操作
	 */
	function add(){
		$input = file_get_contents('php://input');
		$params = json_decode($input,true);
		$key = $this->product->e['key'];
		$post = $this->product->checkValueForm($params,[$key]);//添加时,主键可以为空
		if($post['error']){
			$this->exitJson(2001,$post['error']);
		}
		$data = $post['data'];
		$lastID = $this->product->addRow($data);
		if($lastID>0){
			$this->exitJson(0,['key'=>$lastID]);
		}else{
			$this->exitJson(2000);
		}
	}
	/**
	 * Method 修改操作
	 */
	function edit(){
		$input = file_get_contents('php://input');
		$params = json_decode($input,true);
		$post = $this->product->checkValueForm($params);
		if($post['error']){
			$this->exitJson(2001,$post['error']);
		}
		$data = $post['data'];
		$key = $data[$this->product->e['key']];
		if($this->product->setRowByKey($data,$key)){
			$this->exitJson(0,['key'=>$key]);
		}else{
			$this->exitJson(2000);
		}
	}
	/**
	 * Method 删除操作
	 */
	function delete(){
		$input = file_get_contents('php://input');
		$params = json_decode($input,true);
		if(empty($params['key'])){
			$this->exitJson(2001);
		}
		if($this->product->deleteRowByKey($params['key'])){
			$this->exitJson(0);
		}else{
			$this->exitJson(2000);
		}
	}
}