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

use Modules\Ads\Models\Ads;

class AdsService {

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

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

		$query = Ads::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){
		$request->validate([
			'title' => 'required',
			'group'  => 'required'
		], [
			'title.required' => '请输入广告名称',
			'group.required'  => '请输入广告位标识'
		]);

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

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

	/**
	 * @title 更新广告
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function update($request){
		$request->validate([
			'title' => 'required',
			'group'  => 'required'
		], [
			'title.required' => '请输入广告名称',
			'group.required'  => '请输入广告位标识'
		]);

		$ads = Ads::findOrFail($request->input('id'));

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

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

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

		return $ads;
	}
}
