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

class Domains extends Base
{
	// 域名列表
	public function index()
	{
		if(Request::isPost())
		{
			$data = DomainsModel::whereSiteId(session('siteid'))->append(['ismain'])->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['domain'] = rtrim($data['domain'],'/');
			$this->checkData($data);
			$result = DomainsModel::create($data,true);
			adminlog(2,'新增('.DomainsModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('addtrue'));
			} else {
				$this->error(lang('addfalse'));
			}
		}
	}

	// 编辑
	public function edit()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$data['domain'] = rtrim($data['domain'],'/');
			$info = DomainsModel::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,'编辑('.DomainsModel::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 = DomainsModel::destroy($data['id']);
			adminlog(2,'删除('.DomainsModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('deltrue'));
			} else {
				$this->error(lang('delfalse'));
			}
		}
	}

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