<?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\Refund;
use Modules\Order\Models\Order;
use Modules\Order\Models\OrderItem;
use Modules\Order\Services\OrderService;
use Modules\Order\Events\OrderRefund;
use Illuminate\Support\Str;

class RefundService {

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

		if($request->filled('title')){
			$map[] = ['title', 'like', '%'.$request->input('title').'%'];
		}
		if($request->filled('is_user')){
			$map[] = ['member_id', '=', auth('api')->user()['uid']];
		}

		$query = Refund::with(['goods', 'sku', 'order', 'item', 'member'])->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;
	}

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

		$map[] = ['id', '=', $request->input('id')];

		$query = Refund::with(['goods'])->where($map);

		$refund = $query->first();

		return $refund;
	}

	public function create($request){
		$request->validate([
			'order_id' => 'required',
			'reason' => 'required',
			'store_id' => 'required',
			'order_item_id' => 'required',
			'goods_id' => 'required',
			'goods_sku_id' => 'required',
		], [
			'order_id.required' => '订单ID不能为空！',
			'reason.required' => '退款原因不能为空！',
			'store_id.required' => '店铺ID不能为空！',
			'order_item_id.required' => '订单详情ID不能为空！',
			'goods_id.required' => '商品ID不能为空！',
			'goods_sku_id.required' => '商品规格ID不能为空！',
		]);

		$item = OrderItem::where('id', $request->input('order_item_id'))->first();

		if(!$item){
			throw new \Exception("退单订单商品不存在！", 0);
		}

		if($item->status >= 3){
			throw new \Exception("当前订单状态不能进行退款！", 0);
		}

		$refund = new Refund();

		foreach ($refund->setFilterFields(request()->all()) as $key => $value) {
			$refund->$key = $value;
		}
		$refund->member_id = auth('api')->user()['uid'];
		$refund->status = 0;
		$refund->refund_no = str_replace('-', '', Str::orderedUuid());
		$refund->amount = $item->total_price;

		if($refund->save()){
			$item->status = 4;
			$item->save();

			return $refund;
		}else{
			throw new \Exception("退款失败！", 0);
		}
	}

	public function audit($request){
		$request->validate([
			'id' => 'required',
		]);

		$refund = Refund::find($request->input('id'));

		if(!$refund){
			throw new \Exception("退款不存在！", 1);
		}

		if($refund->status == 1){
			throw new \Exception("退款已审核！", 1);
		}
		if($refund->status == 2){
			throw new \Exception("退款已拒绝！", 1);
		}

		$orderItem = $refund->item()->first();

		if($refund->status == 3){
			throw new \Exception("当前订单不能进行退款！", 1);
		}

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

		$refund->save();

		if($refund->status == 1){
			$order = Order::find($refund->order_id);
			if( !$order->detail()->where('status', '<>', 5)->exists()){
				$order->status = 5;
				$order->save();
			}
			$detail = $order->detail()->where('id', $refund->order_item_id)->first();

			$detail->status = 5;
			$detail->save();

			OrderRefund::dispatch($refund, $order, $detail);
		}
		return $refund;
	}

	public function refundSuccess($data){
		if ($data['refund_status'] == 'SUCCESS' && $data['out_refund_no']) {
			$refund = Refund::where('refund_no', $data['out_refund_no'])->first();
			if($refund){
				$refund->status = 3;
				$refund->save();
			}
			app(OrderService::class)->updateOrderStatus($refund->order_id); //更新订单状态
		}
	}
}
