<?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 Illuminate\Support\Str;
use Modules\Goods\Models\GoodsSku;
use Modules\Order\Models\Cart;
use Modules\Goods\Models\Goods;
use Modules\Order\Models\Order;
use Modules\Order\Models\OrderItem;

class CashierService {

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

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

		$goods_id = $request->input('goods_id');
		$goods_sku_id = $request->input('goods_sku_id');

		//通过扫码获取商品编号
		if(!empty($request->input('goods_sn'))){
			$goods_sn=$request->input('goods_sn');
			$goodsSN=Goods::where(['goods_sn' => $goods_sn])->first();
			if(!empty($goodsSN)){
				$goods_id = empty($goodsSN)?$goods_id:$goodsSN->id;
			}else{
				$goodsSKUSN=GoodsSku::where(['goods_sn' => $goods_sn])->first();
				if(!empty($goodsSKUSN)){
					$goods_id = empty($goodsSKUSN)?$goods_id:$goodsSKUSN->goods_id;
					$goods_sku_id = empty($goodsSKUSN)?$goods_id:$goodsSKUSN->id;
				}
			}
			/*$firstChar = substr($goods_sn, 0, 1); // 截取第一个字符
			if($firstChar == "G"){
				$goodsSN=Goods::where(['goods_sn' => $goods_sn])->first();
				$goods_id = empty($goodsSN)?$goods_id:$goodsSN->id;
			}else if($firstChar == "S"){
				$goodsSKUSN=GoodsSku::where(['goods_sn' => $goods_sn])->first();
				$goods_id = empty($goodsSKUSN)?$goods_id:$goodsSKUSN->goods_id;
				$goods_sku_id = empty($goodsSKUSN)?$goods_id:$goodsSKUSN->id;
			}*/

		}
		/////////////////////////////////////////////////////////

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

		$cart = Cart::where('goods_id', $goods_id)->where('admin_id', auth('admin')->user()['uid'])->where('goods_sku_id', $goods_sku_id);
		if($cart->doesntExist()){
			$cart = new Cart();
			$request->merge([
				'admin_id' => auth('admin')->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->goods_id = $goods_id;

		$cart->goods_sku_id = $goods_sku_id;

		$cart->store_id = $goods->store_id;

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

	public function update($request){
		$cart = Cart::where('id', $request->input('id'))->where('admin_id', auth('admin')->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;
	}

	/**
	 * @title 添加订单
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function simple($request){
		$request->validate([
			'carts' => 'required',
		], [
			'carts.required' => '请选择商品',
		]);
		$order = new Order();

		$request->mergeIfMissing(['admin_id' => auth('admin')->user()['uid']]);

		if($request->filled('carts')){
			$cartsQuery = Cart::with(['goods', 'sku'])->whereIn('id', $request->input('carts'))->where('admin_id', '=', $request->input('admin_id'));
		}

		if($cartsQuery->doesntExist()){
			throw new \Exception("请先加入购物车！", 0);
		}

		$orderGoods = [];
		$carts = $cartsQuery->get()->map(function($item) use (&$orderGoods, $request) {
			if(!$item->goods){
				throw new \Exception("商品不存在！", 0);
			}
			if($item->goods->status != 1){
				throw new \Exception("商品已下架！", 0);
			}
			if(!$item->goods->is_repeat_buy){
				$orderGoodsQuery = OrderItem::where('goods_id', '=', $item->goods_id)->where('admin_id', '=', $request->input('admin_id'))->where('status', '>=', 3);
				if($orderGoodsQuery->exists()){
					throw new \Exception("您已购买过此商品，当前产品不能复购！", 0);
				}
			}
			if($item->sku){
				if($item->sku->stock < $item->num){
					throw new \Exception("商品库存不足！", 0);
				}
				$item->amount = $item->sku->price * $item->num;
				$item->integral = $item->sku->integral * $item->num;
			}else{
				if($item->goods->stock < $item->num){
					throw new \Exception("商品库存不足！", 0);
				}
				$item->amount = $item->goods->price * $item->num;
				$item->integral = $item->goods->integral * $item->num;
			}
			$orderGoods[] = new OrderItem([
				'member_id' =>0,
				'store_id' => $item->store_id,
				'goods_id' => $item->goods_id,
				'goods_sku_id' => $item->goods_sku_id,
				'title' => $item->goods->title,
				'cover' => $item->goods->cover,
				'price' => $item->goods->price,
				'integral' => $item->goods->integral,
				'total_price' => $item->amount,
				'total_integral' => $item->integral,
				'num' => $item->num,
				'status' => 0,
			]);
			return $item;
		});

		$order->order_no = str_replace('-', '', Str::orderedUuid());
		$order->member_id =0;
		$order->invite_uid = $request->input('invite_uid') ?? 0;
		$order->pay_type = $request->input('pay_type') ?? 'wechat';
		$order->amount = $carts->sum('amount');
		$order->integral = $carts->sum('integral');
		$order->status = 0;
		$order->admin_id = auth('admin')->user()['uid'];



		$order->save();

		//下单完成后，删除购物车
		$cartsQuery->delete();

		$order->detail()->saveMany($orderGoods);
		return $order;
	}
}
