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

use Modules\Order\Models\Exchange;

class ExchangeService {

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

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

		$query = Exchange::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([
			'name' => 'required',
			'address' => 'required',
			'mobile' => 'required',
		], [
			'name.required' => '请填写姓名',
			'mobile.required' => '请填写手机号码',
//			'mobile.regex' => '手机号格式不正确',
			'address.required' => '请填写所在地址'
		]);
		$exchange = new Exchange();
		$info = Exchange::where(['mobile' => $request->input('mobile')])->first();
		if($info){
			throw new \Exception("此号码已填写过", 0);
		}
		$exchange->uid = auth('api')->user()['uid'];
		$exchange->name = $request->input('name');
		$exchange->mobile = $request->input('mobile');
		$exchange->status = 1;
		$exchange->address = $request->input('address');
		$exchange->remark = $request->input('remark') ?? '';
		$exchange->save();
		return $exchange;
	}
}