<?php

namespace App\Http\Controllers;

use App\OrderTrackingOwner;
use App\Owner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;

class OrderTrackingOwnerController extends Controller
{

    public function updateStatusApi(Request $request)
    {
        if (!Gate::allows('订单管理-跟踪-监听')) {
            return ['success' => false, 'fail_info' => '权限不足'];
        }
        if (!$request->filled('owner_id') || !$request->filled('status')) {
            return ['success' => false, 'fail_info' => '没有传入对应参数'];
        }

        $orderTrackingOwner = OrderTrackingOwner::query()->where('owner_id',$request->input('owner_id'))->first();
        if ($orderTrackingOwner ?? false) {
            $success = $orderTrackingOwner->update(['status' => $request->input('status')]);
            return ['success' => $success];
        }

        $data = ['owner_id' => $request->input('owner_id'), 'status' => $request->input('status')];
        $success = $orderTrackingOwner = OrderTrackingOwner::query()->create($data) != null;
        return ['success' => $success];
    }

    public function getAllApi()
    {
        if (!Gate::allows('订单管理-跟踪-监听')) {
            return ['success' => false, 'fail_info' => '权限不足'];
        }
        $user = Auth::user();
        $owner_ids = $user ? app('UserService')->getPermittingOwnerIds($user) : [];
        $owner = Owner::query()->with('orderTrackingOwner')
            ->whereIn('id',$owner_ids)
            ->whereHas('orderTrackingOwner',function ($query){$query->where('status','启用');})
            ->select('id')
            ->get();
        return  data_get($owner,'*.id');
    }
}


