<?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 Modules\Store\Services;

use Modules\Store\Models\Category;
use App\Support\Tree;

class CategoryService {

	/**
	 * @title 店铺分类列表
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getDataList($request){
		$map = [];

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

		$query->orderBy($request->input('order', 'id'), $request->input('sort', 'desc'));
		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{
			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{
				$data = $query->limit($request->input('limit', 10))->get();
			}
		}
		return $data;
	}

	/**
	 * @title 添加店铺分类
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function create($request){
		$data = $request->only(['title', 'parent_id', 'description', 'cover', 'icon', 'keywords', 'sort','status']);

		$category = Category::create($data);
		return $category;
	}

	/**
	 * @title 更新店铺分类
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function update($request){
		$data = $request->only(['id', 'title', 'parent_id', 'description', 'cover', 'icon', 'keywords', 'sort','status']);

		$category = Category::findOrFail($request->input('id'));

		foreach ($data as $key => $value) {
			$category->$key = $value;
		}
		$category->save();
		return $category;
	}

	public function delete($request){
		if($request->filled('id')){
			try {
				$category = Category::findOrFail($request->input('id'));
			} catch (\Throwable $th) {
				throw new \Exception("店铺分类不存在！", 1);
			}
			$category->delete();
		}
		if($request->filled('ids')){
			try {
				$category = Category::whereIn('id', $request->input('ids'));
				$category->delete();
			} catch (\Throwable $th) {
				throw new \Exception($th->getMessage(), 1);
			}
		}

		return $category;
	}
}
