<?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\Spec;

class SpecService {

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

		$query = Spec::query();

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

		$query = $query->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->limit($request->input('limit',10))->get();
		}

		return $data;
	}

	public function create($request){
		$request->validate([
			'title' => 'required|max:255',
		]);

		$spec = new Spec;

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

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

	public function update($request){
		$request->validate([
			'id' => 'required|integer',
			'title' => 'required|max:255',
		]);

		$spec = Spec::find($request->input('id'));

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

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

	public function delete($request){
		$request->validate([
			'id' => 'required|integer',
		]);

		$spec = Spec::find($request->input('id'));
		$spec->delete();
		return $spec;
	}
}