<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-04
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use app\common\model\Tkdtemp as TkdtempModel;
use think\Controller;
use Request;

class Tkdtemp extends Base
{
	protected $class;
	protected function initialize()
    {
    	parent::initialize();
        $this->class = TkdtempModel::distinct('class')->column('class');
        $this->assign('class',$this->class);
    }

	// 模板列表
	public function index($formname='')
	{
		if(Request::isPost())
		{
			$type = Request::post('type');
			$data = TkdtempModel::when(!empty($type) && $type!=='全部',function($query)use($type) {
				$query->whereClass($type);
			})->order('torder')->select();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data,'count'=>count($data)]);
		}
		if(empty($formname)) {
			return $this->fetch('');
		} else {
			return $this->fetch('show',compact('formname'));
		}
		
	}

	// 添加
	public function add()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkData($data);
			$result = TkdtempModel::create($data,true);
			adminlog(2,'新增('.TkdtempModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('addtrue'));
			} else {
				$this->error(lang('addfalse'));
			}
		}
	}

	// 编辑
	public function edit()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$info = TkdtempModel::get($data['id']);
			if(empty($info)) $this->error(lang('norecord'));
			$this->checkData($data);
			unset($data['create_time']);
			unset($data['update_time']);
			$result = $info->allowField(true)->save($data);
			adminlog(2,'编辑('.TkdtempModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('edittrue'));
			} else {
				$this->error(lang('editfalse'));
			}
		}
	}

	// 删除
	public function del()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$result = TkdtempModel::destroy($data['id']);
			adminlog(2,'删除('.TkdtempModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('deltrue'));
			} else {
				$this->error(lang('delfalse'));
			}
		}
	}

	// 数据验证
	private function checkData($data)
	{
		$validate = new \app\admin\validate\Tkdtemp;
		if(!$validate->check($data)) {
			$this->error($validate->getError());
		}
	}
}