<?php

namespace Modules\User\Http\Controllers\Api\Identity;

use App\Api\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Jason\Api\Api;
use Modules\Mall\Http\Resources\Api\Activity\ActivityBaseResource;
use Modules\Mall\Http\Resources\Api\Activity\ActivityResource;
use Modules\Mall\Models\Activity;
use Modules\User\Models\Identity;
use Modules\User\Models\Order;

class PartnerController extends Controller
{

    /**
     * Notes: 开通合伙人
     *
     * @Author: 玄尘
     * @Date: 2022/8/4 15:21
     * @return JsonResponse
     */
    public function create(): JsonResponse
    {
        $user = Api::user();

        $activity     = Activity::find(2);
        $activityInfo = $activity ? new ActivityResource($activity) : [];
        $text         = '开通合伙人';
        $order        = Order::ByUser($user)->where('identity_id', 0)->first();
        $value        = true;
        if ($order) {
            $value = false;

            if ($order->state == Order::STATE_INIT) {
                $text = '等待审核';
            } else {
                $text = '您已开通';
            }
        }
        $data = [
            'activity' => $activityInfo,
            'status'   => [
                'value' => $value,
                'text'  => $text,
            ]
        ];

        return $this->success($data);

    }

    /**
     * Notes: 开通会员
     *
     * @Author: 玄尘
     * @Date  : 2021/6/4 10:02
     * @param  Request  $request
     * @return JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'name'    => 'required',
            'card_no' => 'required|numeric',
            'cover'   => 'required',
        ], [
            'name.required'    => '缺少姓名',
            'card_no.required' => '缺少银行卡号',
            'card_no.numeric'  => '银行卡号只能是数字',
            'cover.required'   => '缺少打款凭证',
        ]);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $user = Api::user();

        $data = [
            'user_id'     => $user->id,
            'identity_id' => 0,
            'year'        => 1,
            'type'        => 1,
            'name'        => $request->name,
            'card_no'     => $request->card_no,
            'cover'       => $request->cover,
            'state'       => Order::STATE_INIT,
            'price'       => 0,
        ];

        $order = Order::create($data);

        if ($order) {
            return $this->success('提交成功，请等待后台审核');
        } else {
            return $this->failed('创建订单失败，请稍后再试');
        }
    }

}
