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

class CrontabService {

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

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

		$query = Crontab::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{
			$data = $query->get();
		}

		return $data;
	}

	public function create($request){
		$request->validate([
			'title' => 'required',
			'type' => 'required',
			'expression' => 'required',
			'command' => 'required',
		], [
			'title.required' => '请输入标题',
			'type.required' => '请选择类型',
			'expression.required' => '请输入表达式',
			'command.required' => '请输入命令',
		]);

		$crontab = new Crontab;

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

		$crontab->save();

		return $crontab;
	}

	public function update($request){
		$request->validate([
			'id' => 'required',
			'title' => 'required',
			'type' => 'required',
			'expression' => 'required',
			'command' => 'required',
		], [
			'id.required' => '参数错误',
			'title.required' => '请输入标题',
			'type.required' => '请选择类型',
			'expression.required' => '请输入表达式',
			'command.required' => '请输入命令',
		]);

		$crontab = Crontab::where('id', $request->input('id'))->first();

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

		$crontab->save();

		return $crontab;
	}

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

		$crontab = Crontab::where('id', $request->input('id'))->first();

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

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

		$crontab = Crontab::where('id', $request->input('id'))->first();

		$crontab->status = $request->input('status');

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