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

use Modules\Goods\Models\Brand;

class BrandService {

	/**
	 * @title 商品列表
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getDataList($request){
		$map = [];

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

		$query = Brand::where($map)->orderBy('id', 'desc');

		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->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']);

		$brand = Brand::create($data);
		return $brand;
	}

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

		$brand = Brand::findOrFail($request->input('id'));
		foreach($data as $key => $value){
			$brand->$key = $value;
		}
		$brand->save();
		return $brand;
	}

	public function delete($request){
		if($request->filled('id')){
			try {
				$brand = Brand::findOrFail($request->input('id'));
			} catch (\Throwable $th) {
				throw new \Exception("商品不存在！", 1);
			}
			$brand->delete();
		}
		if($request->filled('ids')){
			try {
				$brand = Brand::whereIn('id', $request->input('ids'));
				$brand->delete();
			} catch (\Throwable $th) {
				throw new \Exception($th->getMessage(), 1);
			}
		}

		return $brand;
	}
}
