<?php

namespace App\Api\Controllers\Area;

use App\Api\Controllers\Controller;
use App\Api\Resources\Area\AreaCodeResource;
use App\Models\AreaCode;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AreaCodeController extends Controller
{

    /**
     * Notes: 查看提货码数据
     *
     * @Author: 玄尘
     * @Date: 2023/1/12 11:03
     * @param  AreaCode  $code
     * @return JsonResponse
     */
    public function show(AreaCode $code)
    {
        return $this->success(new AreaCodeResource($code));
    }

    /**
     * Notes: 根据提货码查询信息
     *
     * @Author: 玄尘
     * @Date: 2023/1/16 9:48
     * @param  Request  $request
     * @return JsonResponse
     */
    public function info(Request $request)
    {
        $code = AreaCode::query()->where('code', $request->code)->first();
        if (! $code) {
            return $this->failed('未查询到此提货码信息');
        } else {
            return $this->success(new AreaCodeResource($code));
        }
    }

    /**
     * Notes: 核销提货码
     *
     * @Author: 玄尘
     * @Date: 2023/1/16 10:56
     * @param  Request  $request
     * @return JsonResponse|mixed
     */
    public function verify(Request $request)
    {
        $code = $request->code ?? '';
        if (! $code) {
            return $this->failed('缺少提货码');
        }
        $areaCode = AreaCode::query()->where('code', $code)->first();
        if ($areaCode->status != AreaCode::STATUS_USED) {
            return $this->failed('此提货码已提货');
        }
        try {
            $areaCode->sign();
            return $this->success('提货成功');
        } catch (\Exception $exception) {
            return $this->failed($exception->getMessage());
        }
    }

}
