<?php

namespace App\Http\Controllers;

use App\OrderIssue;
use App\Services\OrderIssueRejectedBillService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class OrderIssueRejectedBillController extends Controller
{
    public function joinRejectedBillApi(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) return ['success'=>false,'error'=>'没有对应权限'];
        if(!$request->has('logistic_number_return'))return ['success' => false,'error'=>'参数为空'];
        /** @var OrderIssue $orderIssue */
        $orderIssue = OrderIssue::query()->find($request['id']);
        if(!$orderIssue)return ['success' =>false,'error'=>'参数为空'];
        $result =  app(OrderIssueRejectedBillService::class)->joinRejectedBill($orderIssue,$request['logistic_number_return']);
        if(is_null($result))return ['success' => false,'error' => '已有对应的关联关系'];
        if(!$result)return ['success' => false,'error' => '创建关联关系时出现异常'];
        return ['success' => true,'data' => ['orderIssueRejectedBill' => $result,'orderIssue' => $orderIssue]];
    }

    public function unJoinRejectedBillApi(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) return ['success'=>false,'error'=>'没有对应权限'];
        if(!$request->has('logistic_number_return') || !$request->has('id')) return ['success' => false,'error'=>'参数为空'];
        /** @var OrderIssue $orderIssue */
        $orderIssue = OrderIssue::query()->where('id',$request->id)->first();
        if(!$orderIssue)return ['success' => false, 'message'=>'没有找到对应的记录'];
        $result =  app(OrderIssueRejectedBillService::class)->unJoinRejectedBill($orderIssue,$request['logistic_number_return']);
        if(is_null($result))return ['success' => false,'message' => '没有相对应的连接关系！请刷新页面后重试'];
        return ['success' => true , 'orderIssue' => $orderIssue];
    }

    public function reviseJoinRejectedBillApi(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) return ['success'=>false,'error'=>'没有对应权限'];
        if (!$request->has('logistic_number_return_update'))
            return ['success' => false,'error' => '退回单号为空'];
        /** @var OrderIssue $orderIssue */
        $orderIssue = OrderIssue::query()->where('id',$request->id)->first();
        if(!$orderIssue)return ['success' => false,'error' => '没有找到对应的记录'];
        $result = app(OrderIssueRejectedBillService::class)->unJoinRejectedBill($orderIssue,$request['logistic_number_return'],$request['logistic_number_return_update']);
        if(is_null($result))return ['success' => false,'error' =>  '需更新的对应关系不存在！请刷新页面后重试'];
        if(!$result)return ['success' => false,'error' => '更新关联关系时出现异常'];
        return ['success' => true,'data' => ['orderIssueRejectedBill' => $result,'orderIssue' => $orderIssue]];
    }
}
