<?php

namespace App\Http\Controllers\V1;

use App\Http\Requests\MallIdentify;
use App\Http\Requests\UpdateUser;
use App\Models\User;
use App\Models\UserAddress;
use App\Models\WarehouseGoods;
use App\Services\Api\BalanceService;
use App\Services\Api\ErrorMsgServive;
use App\Services\Api\UserService;
use App\Services\Api\WarehouseService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use PHPUnit\Util\Exception;

class AddressController extends Controller
{
    public function __construct()
    {
        $this->user = auth('api')->user();
        $this->userId = $this->user ? $this->user->id : 0;
    }

    //添加收货地址
    public function add(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'   => 'required',
            'mobile' => 'required',
            'adress' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        if (!$res = UserService::saveAddress($request, $this->userId)) {
            return $this->error('提交失败！');
        }

        return $this->success('', '提交成功！');
    }

    //我的地址
    public function mine()
    {
        $list = UserAddress::query()->where('user_id', $this->userId)->notDelete()->get();

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

    //设为默认地址
    public function setDefault(Request $request)
    {
        DB::beginTransaction();
        try{
            UserAddress::query()->where('user_id', $this->userId)->update(['is_default' => 0]);
            $address = UserAddress::find($request->address_id);
            $address->is_default = 1;
            $address->save();
            DB::commit();
        }catch (Exception $exception){
            DB::rollBack();
            ErrorMsgServive::write($exception, $request->url());
            return $this->error('设置失败！');
        }

        return $this->success('', '设置成功！');
    }

    //删除地址
    public function  delAddress(Request $request)
    {
        $address = UserAddress::query()
            ->where('id', $request->address_id)
            ->where('user_id', $this->userId)
            ->first();

        if(!$address){
            return $this->error('删除失败！');
        }
        $address->delete();

        return $this->success('', '删除成功！');
    }

    //地址信息
    public function info(Request $request)
    {
        $info = UserAddress::find($request->address_id);

        return $this->success($info);
    }

}
