<?php

namespace Modules\Mall\Http\Controllers\Api;

use App\Api\Controllers\Controller;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Jason\Api\Api;
use Modules\Mall\Http\Requests\Shop\ShopRequest;
use Modules\Mall\Http\Resources\Api\Region\RegionResource;
use Modules\Mall\Http\Resources\Api\Shop\ShopCollection;
use Modules\Mall\Http\Resources\Api\Shop\ShopEditResource;
use Modules\Mall\Http\Resources\Api\Shop\ShopResource;
use Modules\Mall\Models\Region;
use Modules\Mall\Models\Shop;
use Modules\Mall\Rules\CityRule;
use Modules\Mall\Rules\DistrictRule;
use Modules\Mall\Rules\ProvinceRule;

class ShopController extends Controller
{

    /**
     * Notes   : 全部店铺列表
     * @Date   : 2021/8/26 3:40 下午
     * @Author : <Jason.C>
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $name = $request->name ?? '';

        $list = Shop::where('status', Shop::STATUS_NORMAL)
                    ->when($name, function (Builder $query) use ($name) {
                        $query->where('name', 'like', "%{$name}%");
                    })
                    ->paginate();

        return $this->success(new ShopCollection($list));
    }

    /**
     * Notes   : 店铺详情
     * @Date   : 2021/5/6 3:28 下午
     * @Author : <Jason.C>
     */
    public function show(Shop $shop): JsonResponse
    {
        if ($shop->status !== Shop::STATUS_NORMAL) {
            return $this->failed('店铺不存在或已关闭');
        }

        return $this->success(new ShopResource($shop));
    }

    /**
     * Notes   : 申请的前置判断和基础数据
     * @Date   : 2021/5/6 3:29 下午
     * @Author : <Jason.C>
     */
    public function create()
    {
        $user      = Api::user();
        $checkShop = Shop::firstWhere('user_id', $user->id);
        if ($checkShop) {
            return $this->failed('用户已有店铺，不能重复申请');
        }
        $regions = Region::where('depth', 1)->get();

        return $this->success(RegionResource::collection($regions));
    }

    /**
     * Notes   : 申请一个店铺
     * @Date   : 2021/5/6 3:29 下午
     * @Author : <Jason.C>
     */
    public function store(ShopRequest $request)
    {
        $user = Api::user();

        if (Shop::firstWhere('user_id', $user->id)) {
            return $this->failed('用户已有店铺，不能重复申请');
        }
        $result = Shop::create([
            'name'        => $request->name,
            'user_id'     => $user->id,
            'mobile'      => $request->mobile,
            'description' => $request->description,
            'province_id' => $request->province_id,
            'city_id'     => $request->city_id,
            'district_id' => $request->district_id,
            'cover'       => $request->cover,
            'address'     => $request->address,
            'status'      => Shop::STATUS_APPLYING,
        ]);
        if ($result) {
            return $this->success('操作成功');
        } else {
            return $this->failed('失败');
        }
    }

    /**
     * Notes   : 编辑店铺需要的数据
     * @Date   : 2021/5/7 10:26 上午
     * @Author : <Jason.C>
     */
    public function edit()
    {
        $user = Api::user();
        $shop = Shop::firstWhere('user_id', $user->id);
        if (!$shop) {
            return $this->failed('用户没有店铺，不能编辑');
        }
        if ($shop->status == Shop::STATUS_NORMAL) {
            return $this->failed('用户已通过审核，不能编辑');
        }

        return $this->success(new ShopEditResource($shop));
    }

    /**
     * Notes   : 更新店铺数据
     * @Date   : 2021/5/7 10:27 上午
     * @Author : <Jason.C>
     */
    public function update(Request $request)
    {
        $user = Api::user();
        $shop = Shop::firstWhere('user_id', $user->id);
        if (!$shop) {
            return $this->failed('用户没有店铺，不能编辑');
        }
        if ($shop->status == Shop::STATUS_NORMAL) {
            return $this->failed('用户已通过审核，不能编辑');
        }
        $validator = Validator::make(
            $request->all(),
            [
                'name'        => ['required', Rule::unique('mall_shops', 'name')->ignore($shop->id)],
                'mobile'      => [
                    'required', 'phone:CN', Rule::unique('mall_shops', 'mobile')->ignore($shop->id),
                ],
                'description' => 'required',
                'province_id' => ['required', 'integer', new ProvinceRule()],
                'city_id'     => ['required', 'integer', new CityRule()],
                'district_id' => ['required', 'integer', new DistrictRule()],
                'address'     => 'required',
                'cover'       => 'required',
            ], [
                'name.required'        => '店铺名称必须填写',
                'name.unique'          => '店铺名称不能重复',
                'mobile.required'      => '联系方式必须填写',
                'mobile.phone'         => '联系方式格式不正确',
                'mobile.unique'        => '联系方式不能重复',
                'description.required' => '店铺简介必须填写',
                'province_id.required' => '店铺所在省份必须选择',
                'province_id.integer'  => '店铺所在省份格式不正确',
                'city_id.required'     => '店铺所在城市必须选择',
                'city_id.integer'      => '店铺所在城市格式不正确',
                'district_id.required' => '店铺所在地区必须选择',
                'district_id.integer'  => '店铺所在地区格式不正确',
                'address.required'     => '店铺详细地址必须填写',
                'cover.required'       => '店铺封面图必须上传',
            ]
        );
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first(), 422);
        }
        $result = $shop->update([
            'name'        => $request->name,
            'mobile'      => $request->mobile,
            'description' => $request->description,
            'province_id' => $request->province_id,
            'city_id'     => $request->city_id,
            'district_id' => $request->district_id,
            'cover'       => $request->cover,
            'address'     => $request->address,
            'status'      => Shop::STATUS_APPLYING,
        ]);
        if ($result) {
            return $this->success('操作成功');
        } else {
            return $this->failed('失败');
        }
    }

    /**
     * Notes   : 关闭店铺
     * @Date   : 2021/5/6 3:29 下午
     * @Author : <Jason.C>
     */
    public function destroy(Shop $shop)
    {
        if ($shop->user()->isNot(Api::user())) {
            return $this->failed('', '404');
        }
        if ($shop->close()) {
            return $this->success('店铺关闭成功');
        } else {
            return $this->failed('失败');
        }
    }

}
