<?php
class voucher_tplAction extends action
{
    function __construct(){
        parent::__construct();
		$this->mod = new voucher_tplMod();
    }

    function __destruct(){
    }

	/**
	 * Method 列表数据
	 */
    function list(){
		$where = '';
		if($_POST['filters']){
			$groups = json_decode(htmlspecialchars_decode($_POST['filters']),true);
			$where = $this->groups2sql($groups);
		}
		$data = $this->mod->list($where, $_POST['page'], $_POST['rows'], $_POST['sidx'], $_POST['sord']);
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}
	/**
	 * Method 通过关键字取一行数据
	 */
	function getRowByKey($key){
		$row = $this->mod->getRowByKey('*',$key);
		if($row){
			$this->exitJson(0,$row);
		}else{
			$this->exitJson(2000);
		}
	}
	/**
	 * Method 唯一值检测
	 */
	function onlyCheck(){
		$result = false;
		$vtpl_id = (empty($_REQUEST['vtpl_id'])) ? 0 : $_REQUEST['vtpl_id'];
		$vtpl_name = $_REQUEST['vtpl_name'];
		if($vtpl_name!=''){
			$where = sprintf("vtpl_id<>'%s' AND vtpl_name='%s'",$vtpl_id,$vtpl_name);
			if($this->mod->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->mod->e['key'];
		$post = $this->mod->checkValueForm($params,[$key]);//添加时,主键可以为空
		if($post['error']){
			$this->exitJson(2001,$post['error']);
		}
		$data = $post['data'];
		$this->mod->Begin();
		$lastID = $this->mod->addRow($data);
		$dbOk = $this->mod->End();
		if($dbOk && $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->mod->checkValueForm($params);
		if($post['error']){
			$this->exitJson(2001,$post['error']);
		}
		$data = $post['data'];
		$key = $data[$this->mod->e['key']];
		$this->mod->Begin();
		$this->mod->setRowByKey($data,$key);
		$dbOk = $this->mod->End();
		if($dbOk){
			$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);
		}
		$this->mod->Begin();
		$this->mod->deleteRowByKey($params['key']);
		$dbOk = $this->mod->End();
		if($dbOk){
			$this->exitJson(0);
		}else{
			$this->exitJson(2000);
		}
	}
}