<?php

namespace App\Http\Controllers\H5;

use App\Events\OperationLoggedEvent;
use App\Http\Controllers\Controller;
use App\Http\Requests\OfflineOrderRequest;
use App\Http\Response\ResponseJson;
use App\Models\Group;
use App\Models\Order;
use App\Services\OfflineOrderService;
use App\Validators\OfflineOrderValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class OfflineOrderController extends Controller
{
    use ResponseJson;

    private Order $order;
    private OfflineOrderService $offlineOrderService;
    public function __construct(Order $order, OfflineOrderService $offlineOrderService)
    {
        $this->order = $order;
        $this->offlineOrderService = $offlineOrderService;
    }

    public function store(OfflineOrderRequest $request)
    {
        //数据验证
        $data = $request->validated();
        $data['mobile'] = $request->get('mobile');
        $data['area_code'] = $request->get('area_code');
        $data['price'] = Order::ORDER_PRICE;
        $data['pay_type'] = 1;
        $data['chat_id'] = $request->chat_id;
        $exists = Group::where("chat_id", $data['chat_id'])->whereNotNull('chat_id')->exists();
        Log::info("当前微信企业群id {$data['chat_id']}");
        if ($exists) return $this->failure('该企业群已绑定其他订单');
        //创建线下订单
        $offline_order =  $this->offlineOrderService->createOfflineOrder($data);
//        $wechat_user = session('work_wechat_user');
//        OperationLoggedEvent::dispatch("企业微信id: ".$wechat_user['id'].",创建了虚拟订单: $offline_order->id ,主订单为 $offline_order->order_id");
        return $this->success('ok', $offline_order);
    }
}
