<?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\Order;
use Modules\Order\Models\OrderItem;
use Modules\Order\Models\Cart;
use Modules\Goods\Models\Goods;
use Modules\Goods\Models\GoodsSku;
use Modules\Store\Models\Store;
use Modules\Member\Models\MemberAddress;
use Modules\Member\Models\Member;
use Modules\Member\Models\MemberSocial;
use Modules\Wechat\Services\MessageService;
use Modules\Wechat\Services\ShippingService;
use tensent\yspay\Client;
use Illuminate\Support\Str;
use Carbon\Carbon;

class OrderService {

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

		$query = Order::with(['member:uid,username,nickname,mobile,avatar', 'detail', 'detail.sku', 'detail.store:id,title,cover', 'refund']);

		if($request->filled('order_no')){
			$map[] = ['order_no', 'like', '%'.$request->input('order_no').'%'];
		}
		if($request->filled('status')){
			$map[] = ['status', '=', $request->input('status')];
		}
		if($request->filled('pro_status')){
			switch ($request->input('pro_status')) {
				case '0':
					$query->where('status', '>', 0);
					break;
				case "1":
					$query->whereIn('status', [1, 2]);
					break;
				case "2":
					$query->whereIn('status', [3, 4]);
					break;
				case "3":
					$query->whereIn('status', [5, 6]);
					break;
				default:
					$query->where('status', '>', 0);
					break;
			}
		}

		if($request->filled('member_id')){
			$map[] = ['member_id', '=', $request->input('user_id')];
		}
		if($request->filled('is_user')){
			$map[] = ['member_id', '=', auth('api')->user()['uid']];
		}
		if($request->filled('is_master')){
			$store_id = Store::where('member_id', '=', auth('api')->user()['uid'])->value('id');
			if(!$store_id){
				throw new \Exception('您未开通店铺！', 0);
			}
			$request->mergeIfMissing(['store_id' => $store_id]);
			$map[] = ['store_id', '=', $store_id];
		}
		if($request->filled('store_id')){
			$map[] = ['store_id', '=', $request->input('store_id')];
		}

		if($request->filled('username')){
			$query->whereIn('member_id', function($q) use ($request){
				$q->from('member')->where('username', 'like', '%' . $request->input('username') . '%')->select('uid');
			});
		}

		if($request->filled('is_invite') && $request->input('is_invite') == 1  && auth('api')->user()){
			$query->whereIn('member_id', function($q) use ($request){
				$q->from('member')->where('invite_uid', '=', auth('api')->user()['uid'])->select('uid');
			});
		}

		if($request->filled('date')){
			$query->whereDate('created_at', '>=', $request->input('date')[0])->whereDate('created_at', '<=', $request->input('date')[1]);
		}
		$query->where($map)->orderBy('id', 'desc');

		if($request->filled('goods_id')){
			$query->whereIn('id', function($q) use ($request){
				$q->select('order_id')->from('goods_order_item')->where('goods_id', '=', $request->input('goods_id'));
			});
		}

		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()->map(function($item){
					if(!request()->is('admin/*')){
						$item->member->mobile = str()->limit($item->member->mobile, 4, '****');
						$item->member->nickname = str()->limit($item->member->nickname, 4, '****');
						$item->member->username = str()->limit($item->member->username, 4, '****');
					}
					return $item;
				}),
			];
		}else{
			$data = $query->limit($request->input('limit', 30))->get()->map(function($item){
				if(!request()->is('admin/*')){
					$item->member->mobile = str()->limit($item->member->mobile, 4, '****');
					$item->member->nickname = str()->limit($item->member->nickname, 4, '****');
					$item->member->username = str()->limit($item->member->username, 4, '****');
				}
				return $item;
			});
		}
		return $data;
	}

	public function getList($request){
		$query = OrderItem::with(['member:uid,username,nickname,mobile,avatar', 'order', 'sku']);

		if($request->filled('order_no')){
			$query->whereHas('order', function($q) use ($request) {
				$q->where('order_no', 'like', '%'.$request->input('order_no').'%');
			});
		}
		if($request->filled('status')){
			$query->where('status', '=', $request->input('status'));
		}
		if($request->filled('pro_status')){
			switch ($request->input('pro_status')) {
				case '0':
					$query->where('status', '>', 0);
					break;
				case "1":
					$query->whereIn('status', [1, 2]);
					break;
				case "2":
					$query->whereIn('status', [3, 4]);
					break;
				case "3":
					$query->whereIn('status', [5, 6]);
					break;
				default:
					$query->where('status', '>', 0);
					break;
			}
		}

		if($request->filled('is_marster') && $request->input('is_marster') == 1){
			$store_id = Store::where('member_id', '=', auth('api')->user()['uid'])->value('id');
			if(!$store_id){
				throw new \Exception('您未开通店铺！', 0);
			}
			$request->mergeIfMissing(['store_id' => $store_id]);
			$query->where('store_id', $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', 30))->get();
		}
		return $data;
	}

	public function getData($request){
		$map = [];
		$map[] = ['id', '=', $request->input('id')];
		$data = Order::with(['member', 'detail', 'detail.goods:id,title,price,integral', 'detail.sku', 'detail.store:id,title,cover'])->where($map)->first();
		if(!$data){
			throw new \Exception("订单不存在！", 0);
		}
		return $data;
	}



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

		$request->mergeIfMissing(['member_id' => auth('api')->user()['uid']]);

		if($request->filled('carts')){
			$cartsQuery = Cart::with(['goods', 'sku'])->whereIn('id', $request->input('carts'))->where('member_id', '=', $request->input('member_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('member_id', '=', $request->input('member_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;
			}
			//使用聚物通资金不可用积分
			$item->goods->integral = $item->integral = $request->input('pay_way')=="integral" ? $item->integral:0;

			$orderGoods[] = new OrderItem([
				'member_id' => auth('api')->user()['uid'],
				'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 = auth('api')->user()['uid'];
		$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->pay_way =$request->input('pay_way');
		$order->status = 0;

		if($request->input('pay_way') == "polymer_money"){
			if(auth('api')->user()['polymer_money'] >= $order->amount){
				$order->polymer_money = $order->amount;//聚物通
			}else{
				$order->polymer_money = auth('api')->user()['polymer_money'];
			}
		}

		if($order->integral > auth('api')->user()['score']){
			throw new \Exception("积分不足！", 0);
		}

		if($request->filled('address_id')){
			$address = MemberAddress::where('id', '=', $request->input('address_id'))->where('member_id', '=', $order->member_id)->first();
			if(!$address){
				throw new \Exception("地址不存在！", 0);
			}
			$order->delivery_info = $address->toArray();
		}
		$order->save();

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

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

	public function simpleCreate($request){
		$request->validate([
			'goods_id' => 'required',
		], [
			'goods_id.required' => '请选择商品',
		]);

		$pay_way=$request->input('pay_way') ?? 'wechat';//付款方式

		$order = new Order();

		$goods = Goods::where('id', '=', $request->input('goods_id'))->first();

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

		if($goods->status != 1){
			throw new \Exception("商品已下架！", 0);
		}

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

		if ($goods->goods_type == 0 && !$goods->is_repeat_buy){
			$orderGoodsQuery = OrderItem::where('goods_id', '=', $goods->id)->where('member_id', '=', auth('api')->user()['uid'])->where('status', '>=', 3);
			if($orderGoodsQuery->exists()){
				throw new \Exception("您已购买过此商品，当前产品不能复购！", 0);
			}
		}

		$num = $request->input('num', 1);
		if($goods['spec'] == 1){
			$request->validate([
				'goods_sku_id' => 'required',
			], [
				'goods_sku_id.required' => '请选择商品规格',
			]);
			$sku = GoodsSku::where('id', '=', $request->input('goods_sku_id'))->first();
			if(!$sku){
				throw new \Exception("商品规格不存在！", 0);
			}
			//使用聚物通资金不可用积分
			$sku->integral = $pay_way == "integral"?$sku->integral:0;

			$orderGoods = new OrderItem([
				'member_id' => auth('api')->user()['uid'],
				'store_id' => $goods->store_id,
				'goods_id' => $goods->id,
				'goods_sku_id' => $sku->id,
				'title' => $goods->title,
				'cover' => $goods->cover,
				'price' => $sku->price,
				'integral' => $sku->integral,
				'total_price' => $sku->price,
				'total_integral' => $sku->integral,
				'num' => $num ? $num : 1,
				'status' => 0,
			]);
			$amount = $sku->price;
			$integral = $sku->integral;
		}else{
			//使用聚物通资金不可用积分
			$goods->integral = $pay_way == "integral"?$goods->integral:0;

			$orderGoods = new OrderItem([
				'member_id' => auth('api')->user()['uid'],
				'store_id' => $goods->store_id,
				'goods_id' => $goods->id,
				'goods_sku_id' => 0,
				'title' => $goods->title,
				'cover' => $goods->cover,
				'price' => $goods->price,
				'integral' => $goods->integral,
				'total_price' => $goods->price,
				'total_integral' => $goods->integral,
				'num' => $num ? $num : 1,
				'status' => 0,
			]);
			$amount = $goods->price;
			$integral = $goods->integral;
		}

		$order->order_no = str_replace('-', '', Str::orderedUuid());
		$order->member_id = auth('api')->user()['uid'];
		$order->invite_uid = $request->input('invite_uid') ?? 0;
		$order->pay_type = $request->input('pay_type') ?? 'wechat';
		$order->delivery_type = $request->input('delivery_type') ?? 1;
		$order->amount = $amount;
		$order->integral = $integral;//积分
		$order->pay_way =$pay_way;
		$order->status = 0;

		if($pay_way == "polymer_money"){
			if(auth('api')->user()['polymer_money'] >= $amount){
				$order->polymer_money = $amount;//聚物通
			}else{
				$order->polymer_money = auth('api')->user()['polymer_money'];
			}
		}

		if($order->integral > auth('api')->user()['score']){
			throw new \Exception("积分不足！", 0);
		}

		if($request->filled('address_id')){
			$address = MemberAddress::where('id', '=', $request->input('address_id'))->where('member_id', '=', $order->member_id)->first();
		}else{
			$address = MemberAddress::where('member_id', '=', $order->member_id)->first();
		}
		if(!$address){
			throw new \Exception("地址不存在！", 0);
		}
		$order->delivery_info = $address->toArray();

		$order->save();

		$order->detail()->save($orderGoods);

		return $order;
	}

	/**
	 * @title 更新订单
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function update($request){
		$order = Order::where('id', '=', $request->input('id'))->first();
		if(!$order){
			throw new \Exception("订单不存在！", 0);
		}

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

		$goods = null;
		if($request->filled('goods_ids')){
			$goods = Goods::whereIn('id', $request->input('goods_ids'))->get();
		}
		if($request->filled('goods_id')){
			$goods = Goods::where('id', '=', $request->input('goods_id'))->get();
		}
		if(!$goods){
			throw new \Exception("商品不存在!", 0);
		}

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

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

	public function delete($request){
		if($request->filled('id')){
			$order = Order::where('id', $request->input('id'))->where('status', '<=', 0);
			if ($order->doesntExist()) {
				throw new \Exception("订单不存在或已支付！", 1);
			}
			$order->delete();
		}
		if($request->filled('ids')){
			try {
				$order = Order::whereIn('id', $request->input('ids'))->where('status', 0);
				$order->delete();
			} catch (\Throwable $th) {
				throw new \Exception($th->getMessage(), 1);
			}
		}

		return $order;
	}

	public function cancel($request){
		$order = Order::where('id', '=', $request->input('id'))->first();
		if(!$order){
			throw new \Exception("订单不存在！", 0);
		}
		if($order->member_id != auth('api')->user()['uid']){
			throw new \Exception("您没有权限操作！", 0);
		}
		if($order->status != 0){
			throw new \Exception("订单状态不正确！", 0);
		}
		$order->status = -1;

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

	public function setNumber($request){
		$order = Order::where('id', '=', $request->input('id'))->first();
		if(!$order){
			throw new \Exception("订单不存在！", 0);
		}
		if($order->member_id != auth('api')->user()['uid']){
			throw new \Exception("您没有权限操作！", 0);
		}

		$goods = null;
		if($request->filled('goods_id')){
			$goods = Goods::where('id', '=', $request->input('goods_id'))->first();
		}
		if(!$goods){
			throw new \Exception("商品不存在!", 0);
		}
		if($goods->can_up_number == 0){
			throw new \Exception("该商品不允许修改数量!", 0);
		}
		if($request->filled('num')){
			$order_goods = $order->detail()->where('goods_id', '=', $request->input('goods_id'))->first();

			if($order_goods){
				$order_goods->num = $request->input('num');
				$order_goods->total_price = bcmul($order_goods->discount_price, $request->input('num'));
				$order_goods->save();
			}
		}

		$order->amount = $order->detail()->sum('total_price');
		$order->save();

		return $order;
	}

	/**
	 * @title 支付成功
	 *
	 * @param [type] $param
	 * @return void
	 */
	public function paySuccess($order_no){
		$order = Order::with(['member'])->where('order_no', '=', $order_no)->first();

		if($order && $order->status == 0){
			$order->status = 1;
			$order->pay_time = date('Y-m-d H:i:s');
			$order->save();

			$itemCount = $order->detail()->count();

			//扣除聚物通资金
			if($order->polymer_money > 0){
				app(\Modules\Member\Services\PolymerService::class)->createPolymer(store_id: 0, order_id: $order->id, member_id: $order->member['uid'], type: 'pay', account_type: 'order', amount: $order->polymer_money, remark: '订单支付');
			}

			// 订单详情商品处理
			$order->detail()->with(['goods', 'sku'])->get()->each(function($item,$key) use ($order, $itemCount) {
				// 积分商品积分扣除
				if($item->total_integral > 0){
					app(\Modules\Member\Services\ScoreService::class)->createScore(store_id: $item->store_id, order_id: $item->id, member_id: $order->member['uid'], type: 'pay', account_type: 'order', amount: $item->total_integral, remark: '订单支付');
				}
				if($item->goods->goods_type == 0){
					$item->status = 3;
					$item->save();
					if($itemCount == 1){
						$order->status = 3;
						$order->save();
					}

					\Modules\Order\Events\OrderTake::dispatch($order, $item);
					// app(ShippingService::class)->pushShipping($order->order_no, $item->member_id, $item->title, 3);   // 发货推送
				}else{
					$item->status = $order->status;
					$item->save();
				}
			});
		}
	}

	/**
	 * @title 订单退款回调处理
	 *
	 * @param [type] $orderno
	 * @return void
	 */
	public function orderRefundNotify($order_no){
		$order = Order::with(['member', 'store'])->where('order_no', '=', $order_no)->first();

		if($order){
			$order->status = 4;
			$order->save();
			OrderRefunds::where('order_id', '=', $order['id'])->update(['refund_status' => 'processed']);

			$openid = MemberSocial::where('member_id', '=', $order['member']['uid'])->value('openid');
			if(isset($openid)){
				app(MessageService::class)
					->sendMessage(
						$openid,
						'0HGXt38KQIadluhsPnZNudYJsYAz-A8_XV8Vcew3DUU',
						'https://mobile.jxszkj.com.cn/#/pages/ucenter/order/index?status=4',
						[
							'thing3' => ['value' => $order['order_no']],
							'amount1' => ['value' => $order['amount']],
							'time2' => ['value' => date('Y-m-d H:i:s')],
						]
					);
			}
		}
	}

	/**
	 * @title 订单发货
	 *
	 * @param [type] $params
	 * @return void
	 */
	public function orderSend($request){
		// 输入验证
		if(!$request->filled('order_id')){
			throw new \Exception("订单不存在！", 1);
		}
		$order = Order::find($request->input('order_id'));
		if(!$order){
			throw new \Exception("订单不存在!", 0);
		}

		if(!$order['pay_time']){
			throw new \Exception("订单未付款!", 0);
		}

		if($order['status'] == 3){
			throw new \Exception("订单已收货!", 0);
		}

		$item = $order->detail()->where('id', $request->input('id'))->first();

		if ($request->is('api/*') && auth('api')->user()){
			//判断是否为店主
			$store = \Modules\Store\Models\Store::where('id', $item['store_id'])->where('status', 1)->select(['id', 'member_id', 'status'])->first();
			if($store->member_id != auth('api')->user()->uid){
				throw new \Exception("您不是店主，无权发货!", 0);
			}
		}

		if(!$item){
			throw new \Exception("订单详情不存在!", 0);
		}

		if($item['status'] >= 2){
			throw new \Exception("订单详情已收货!", 0);
		}

		$item->status = 2;
		$item->delivery_time = date('Y-m-d H:i:s');
		$item->delivery_no = $request->input('delivery_no');
		$item->delivery_type = $request->input('delivery_type', 'express');
		$item->save();

		$this->updateOrderStatus($order->id); //更新订单状态

		\Modules\Order\Events\OrderSend::dispatch($order, $item);

		return $order;
	}

	/**
	 * @title 订单收货
	 *
	 * @param [type] $param
	 * @return void
	 */
	public function orderTake($request){
		$member = auth('api')->user();
		$order = Order::where('id', $request->input('id'))->first();
		if(!$order){
			throw new \Exception("订单不存在!", 0);
		}
		if($order['status'] == 3){
			throw new \Exception("订单已收货!", 0);
		}
		if($order['member_id'] != $member['uid']){
			throw new \Exception("订单不属于您，您无权操作!", 0);
		}

		$item = $order->detail()->with(['goods', 'sku'])->where('id', $request->input('detail_id'))->first();
		if(!$item){
			throw new \Exception("订单详情不存在!", 0);
		}
		if($item['status'] == 3){
			throw new \Exception("订单详情已收货!", 0);
		}
		if($item->goods->goods_type == 0){
			throw new \Exception("积分商品不允许收货!", 0);
		}
		$item->status = 3;
		$item->save();

		$this->updateOrderStatus($order->id); //更新订单状态

		\Modules\Order\Events\OrderTake::dispatch($order, $item);

		return $order;
	}

	/**
	 * @title 订单自动收货
	 *
	 * @return void
	 */
	public function orderTakeTask(){
		$config = cache('config');
		$auto_take_time = (isset($config['auto_take_time']) && $config['auto_take_time']) ? $config['auto_take_time'] : 7;
		$time = Carbon::now()->subDays($auto_take_time);
		$order = Order::where('status', '=', 2)->where('pay_time', '<', $time)->orderBy('pay_time', 'asc')->first();
		if(!$order){
			return;
		}
		$order->status = 3;
		$order->confirm_time = date('Y-m-d H:i:s');
		$order->save();

		$item = $order->detail()->where('status', '=', 2)->get();
		foreach ($item as $key => $value) {
			$value->status = 3;
			$value->save();
			\Modules\Order\Events\OrderTake::dispatch($order, $value);
		}
	}

	/**
	 * @title 订单扫描核销
	 *
	 * @param [type] $param
	 * @return void
	 */
	public function orderScan($request){
		$order = Order::where('order_no', '=', $request->input('order_no'))->first();
		if(!$order){
			throw new \Exception("订单不存在!", 0);
		}

		$item = $order->detail()->where('id', $request->input('detail_id'))->first();
		if(!$item){
			throw new \Exception("订单详情不存在!", 0);
		}

		if ($request->is('api/*') && auth('api')->user()){
			//判断是否为店主
			$store = \Modules\Store\Models\Store::where('id', $item['store_id'])->where('status', 1)->select(['id', 'member_id', 'status'])->first();
			if($store->member_id != auth('api')->user()->uid){
				throw new \Exception("您不是店主，无权发货!", 0);
			}
		}else{
			throw new \Exception("请先登录!", 0);
		}

		$order->status = 3;
		$order->confirm_time = date('Y-m-d H:i:s');
		$order->save();

		$item->status = 3;
		$item->delivery_time = date('Y-m-d H:i:s');
		$item->delivery_type = $request->input('delivery_type', 'pickup');
		$item->save();

		\Modules\Order\Events\OrderTake::dispatch($order, $item);

		return $order;
	}

	/**商家订单详情
	 * @param $request
	 * @return \Illuminate\Database\Concerns\TValue|null
	 * @throws \Exception
	 */
	public function getDetailsData($request){
		$map = [];
		$map[] = ['order_no', '=', $request->input('order_no')];
		$data = Order::with(['member', 'detail', 'detail.goods:id,title,price,integral', 'detail.sku', 'detail.store:id,title,cover'])->where($map)->first();
		if(!$data){
			throw new \Exception("订单不存在！", 0);
		}
		return $data;
	}

	/**
	 * @title 订单退款
	 *
	 * @param [type] $param
	 * @return void
	 */
	public function orderRefund($request){
		$order = Order::find($request->input('order_id'));
		if(!$order){
			throw new \Exception("订单不存在!", 0);
		}

		$refund = $order->refund()->first();
		if(!$refund){
			throw new \Exception("订单退款不存在!", 0);
		}
		if($refund['status'] > 0){
			throw new \Exception("订单退款已处理!", 0);
		}
		$refund->status = $request->input('status');
		$refund->save();
		$this->updateOrderStatus($order->id); //更新订单状态

		\Modules\Goods\Events\OrderRefund::dispatch($order);

		return $refund;
	}

	public function getjsPayData($request, $type){
		$order = Order::with(['member:uid,username'=> ['social']])->find($request->input('order_id'));
		if(!$order){
			throw new \Exception("订单不存在!", 0);
		}
		if(isset($order['member']['social'])){
			foreach ($order['member']['social'] as $value) {
				$order->social = $value['type'] == $type ? $value : [];
			}
		}

		\Modules\Order\Events\PayData::dispatch($order);
		return $order;
	}

	/**
	 * @title 订单结算
	 *
	 * @param array $order    店铺订单信息
	 * @param array $goods    店铺订单商品信息
	 * @param array $member   商品购买者信息
	 * @return void
	 */
	public function orderBalance($order, $goods, $member){
	}

	public function addAddress($request){
		$order = Order::find($request->input('id'));

		if(!$order){
			throw new \Exception("无此订单！", 0);
		}

		$address = MemberAddress::find($request->input('address_id'));

		if(!$address){
			throw new \Exception("无此收货地址地址！", 0);
		}

		$order->delivery_info = [
			'id' => $address->id,
			'name' => $address->name,
			'mobile' => $address->mobile,
			'address' => $address->address,
		];

		$order->save();
	}

	public function updateOrderStatus($order_id){
		$order = Order::where('id', $order_id)->first();

		// 获取订单详情最低的状态值
		$detail = $order->detail()->orderBy('status', 'desc')->first();

		if($detail){
			$order->status = $detail->status;
		}
		$order->save();
	}
}
