<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace App\Services\System;

use App\Models\System\ClientMenu;
use App\Support\Tree;

class ClientMenuService {

	public function getDataList($request){
		$map = [];

		if($request->filled('title')){
			$map[] = ['title', 'like', '%' . $request->input('title') . '%'];
		}

		$query = ClientMenu::where($map)->orderBy('id', 'asc');

		if($request->filled('page')){
			$data = [
				'total' => $query->count(),
				'page' => $request->input('page', 1),
				'data' => $query->offset($request->input('offset', 0))->limit($request->input('limit', 10))->get(),
			];
		}else{
			if($request->filled('is_tree') && $request->filled('is_tree') == 1){
				$query = $query->get()->toArray();
				$tree = new Tree();
				$data = $tree->list_to_tree($query, 0, 'id', 'parent_id');
			}else{
				$data = $query->get();
			}
		}
		return $data;
	}

	public function create($request){
		$request->validate([
			'title' => 'required',
		]);
		$menu = new ClientMenu();

		foreach ($menu->setFilterFields($request->all()) as $key => $value) {
			$menu->$key = $value;
		}
		$menu->save();

		return $menu;
	}

	public function update($request){
		$request->validate([
			'id' => 'required',
			'title' => 'required',
		], [
			'id.required' => '参数错误',
			'title.required' => '请输入标题',
		]);

		$menu = ClientMenu::where('id', $request->input('id'))->first();

		foreach ($menu->setFilterFields($request->all()) as $key => $value) {
			$menu->$key = $value;
		}

		$menu->save();
		return $menu;
	}

	public function delete($request){
		$request->validate([
			'id' => 'required',
		], [
			'id.required' => '参数错误',
		]);

		$menu = ClientMenu::where('id', $request->input('id'))->first();

		$menu->delete();
		return $menu;
	}
}
