<?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\Cart;
use Modules\Goods\Models\Goods;

class CartService {

	/**
	 * @title 获取购物车列表
	 *
	 * @return void
	 */
	public function getDataList($member_id){
		$data = Cart::with(['goods:id,title,price,cover,stock,sales,integral', 'store:id,title,cover', 'sku'])->where('member_id', $member_id)->get();
		return $data;
	}

	public function create($request){
		$request->validate([
			'goods_id' => 'required',
			'num' => 'required',
		], [
			'goods_id.required' => '商品不能为空',
			'num.required' => '商品数量不能为空',
		]);

		$goods = Goods::find($request->input('goods_id'));
		if(!$goods){
			throw new \Exception("商品不存在！", 1);
		}

		$cart = Cart::where('goods_id', $request->input('goods_id'))->where('member_id', auth('api')->user()['uid'])->where('goods_sku_id', $request->input('goods_sku_id'));
		if($cart->doesntExist()){
			$cart = new Cart();
			$request->merge([
				'member_id' => auth('api')->user()['uid']
			]);
			foreach ($cart->setFilterFields($request->all()) as $key => $value) {
				if($value != ''){
					$cart->$key = $value;
				}
			}
			if($cart->num > $goods->stock){
				throw new \Exception("商品库存不足！", 1);
			}
		}else{
			$cart = $cart->first();

			if($cart->num > $goods->stock){
				throw new \Exception("商品库存不足！", 1);
			}
			$cart->num = $cart->num + $request->input('num', 1);
		}

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

	public function update($request){
		$cart = Cart::where('id', $request->input('id'))->where('member_id', auth('api')->user()['uid'])->first();
		if(!$cart){
			throw new \Exception("购物车不存在！", 1);
		}

		foreach ($cart->setFilterFields($request->only(['goods_sku_id', 'num'])) as $key => $value) {
			if($value){
				$cart->$key = $value;
			}
		}

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

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

		return $cart;
	}
}
