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

use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Modules\Goods\Models\Goods;
use App\Support\Tree;

class GoodsService {

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

		$query = Goods::with(['category:id,parent_id,title,icon,cover,is_recom', 'sku', 'store:id,title,cover']);

		if($request->filled('title')){
			$map[] = ['title', 'like', '%'.$request->input('title').'%'];
		}
		if($request->filled('keyword')){
			$map[] = ['title', 'like', '%'.$request->input('keyword').'%'];
		}
		if($request->filled('status')){
			$map[] = ['status', '=', $request->input('status')];
		}
		if($request->filled('brand_id')){
			$map[] = ['brand_id', '=', $request->input('brand_id')];
		}
		if($request->filled('is_recom')){
			$map[] = ['is_recom', '=', $request->input('is_recom')];
		}
		if($request->filled('is_hot')){
			$map[] = ['is_hot', '=', $request->input('is_hot')];
		}
		if($request->filled('is_new')){
			$map[] = ['is_new', '=', $request->input('is_new')];
		}

		$query = $query->where($map);

		if($request->filled('category_id')){
			$category = Tree::get_children(cache('goods_category'), $request->input('category_id'));
			$category[] = (int) $request->input('category_id');
			$query->whereHas('category', function($q) use($category) {
				$q->whereIn('category_id', $category);
			});
		}

		if($request->filled('store_id')){
			$query->where('store_id', $request->input('store_id'));
		}

		$query->orderBy($request->input('order', 'id'), $request->input('sort', '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->limit($request->input('limit', 10))->get();
		}
		return $data;
	}

	/**
	 * @title 商品详情
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getData($request){
		$request->validate([
			'id' => 'required',
		], [
			'id.required' => '商品ID不能为空！',
		]);

		$goods = Goods::with(['category:id,parent_id,title,icon,cover,is_recom', 'sku', 'store:id,title,cover'])->where('id', $request->input('id'));

		if($goods->doesntExist()){
			throw new \Exception("商品不存在！", 1);
		}
		return $goods->first();
	}

	/**
	 * @title 添加商品
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function create($request){
		$request->validate([
			'title' => 'required',
			'category_id' => 'required',
			'store_id' => 'required',
		], [
			'title.required' => '商品名称不能为空！',
			'category_id.required' => '商品分类不能为空！',
			'store_id.required' => '商品所属店铺不能为空！'
		]);
		$request->mergeIfMissing(['user_id' => auth('admin')->user()['uid']]);

		$goods = new Goods();
		foreach ($goods->setFilterFields($request->all()) as $key => $value) {
			$goods->$key = $value;
		}
		$goods->goods_sn = "G".date('YmdHis') ;

		$goods->save();
		//更新栏目
		$goods->category()->sync($request->input('category_id'));

		//更新SKU
		if($request->filled('sku') && $request->input('spec') == 1){
			$sku = $request->input('sku');
			foreach ($sku as $key => $value) {
				$sku[$key]['sku_value'] = isset($value['sku_value']) ? $value['sku_value'] : Arr::except($value, ['price', 'stock', 'cover', 'original_price', 'sales']);
				$sku[$key]['sku'] = implode(';', $value['sku_value']);
				$sku[$key]['goods_sn'] = "S".date('YmdHis') ;
			}
			$goods->sku()->createMany($sku);
		}

		return $goods;
	}

	/**
	 * @title 更新商品
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function update($request){
		$request->validate([
			'title' => 'required',
			'category_id' => 'required',
			'store_id' => 'required',
		], [
			'title.required' => '商品名称不能为空！',
			'category_id.required' => '商品分类不能为空！',
			'store_id.required' => '商品所属店铺不能为空！'
		]);
		$goods = Goods::find($request->input('id'));
		if(!$goods){
			throw new \Exception("商品不存在！", 1);
		}
		$request->mergeIfMissing(['user_id' => auth('admin')->user()['uid']]);

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

		$goods->save();
		//更新栏目
		$goods->category()->sync($request->input('category_id'));

		if($request->filled('sku') && $request->input('spec') == 1){
			$sku = $request->input('sku');
			if($sku){
				$ids = Arr::pluck($sku, 'id');
				$goods->sku()->whereNotIn('id', $ids)->delete();
				foreach ($sku as $key => $value) {
					$value['sku_value'] = isset($value['sku_value']) ? $value['sku_value'] : Arr::except($value, ['price', 'stock', 'cover', 'original_price', 'sales']);
					$value['sku'] = implode(';', $value['sku_value']);
					$value['goods_sn'] = empty($value['goods_sn'])?"S".date('YmdHi').rand(1000,9999):$value['goods_sn'];
					$goods->sku()->updateOrCreate(['id' => $value['id'] ?? 0], $value);
				}
			}else{
				$goods->sku()->delete();
			}
		}
		return $goods;
	}

	public function delete($request){
		if($request->filled('id')){
			try {
				$goods = Goods::findOrFail($request->input('id'));
			} catch (\Throwable $th) {
				throw new \Exception("商品不存在！", 1);
			}
			$goods->delete();
			$goods->category()->detach();
			$goods->sku()->delete();
		}
		if($request->filled('ids')){
			try {
				$goods = Goods::whereIn('id', $request->input('ids'));
				$goods->delete();
				$goods->category()->detach();
				$goods->sku()->delete();
			} catch (\Throwable $th) {
				throw new \Exception($th->getMessage(), 1);
			}
		}

		return $goods;
	}

	/**
	 * @title 商品营销表单
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function operateForm($request){
		$form = [
			['title' => '限时抢购', 'value' => 'rush', 'form' => []],
			['title' => '排队返现', 'value' => 'queue', 'form' => []],
			['title' => '分享返现', 'value' => 'share', 'form' => []],
		];
		foreach ($form as $key => $value) {
			$service = "\\Modules\\Operate\\Services\\" . ucfirst($value['value']) . "Service";
			$form[$key]['form'] = app($service)->getFormFields($request);
		}
		return $form;
	}
}
