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

class Sitekey extends Base
{
	// 关键词列表
	public function index()
	{
		if(Request::isPost())
		{
			$data = SitekeyModel::order('torder asc,id desc')->select();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data,'count'=>count($data)]);
		}
		return $this->fetch();
	}

	// 添加
	public function add()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$data['name'] = str_replace(',', '', trim($data['name']));
			$this->checkData($data);
			$result = SitekeyModel::create($data,true);
			adminlog(2,'新增('.SitekeyModel::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 = SitekeyModel::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,'编辑('.SitekeyModel::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 = SitekeyModel::destroy($data['id']);
			adminlog(2,'删除('.SitekeyModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('deltrue'));
			} else {
				$this->error(lang('delfalse'));
			}
		}
	}

	// 数据验证
	private function checkData($data)
	{
		if(!isset($data['list_switch'])) { // 如果不是switch开关操作
			$validate = new \app\admin\validate\Sitekey;
			if(!$validate->check($data)) {
				$this->error($validate->getError());
			}
		}
	}
}