<?php

namespace App\Services\Client;

use App\Models\MemberUser;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserAddressService
{
    /**
     * 获取默认地址
     */
    public function getDefault($userId)
    {
        try {
            // 根据用户编号查询用户数据
            $user = MemberUser::findOrFail($userId);
            if ($user->state != 'enable') {
                return ['code' => 400, 'message' => '用户状态异常'];
            }

            // 查询用户地址列表,返回用户默认地址
            $address = $user->addresses()
                ->where('is_default', 1)
                ->first();

            return ['code' => 200, 'message' => 'success', 'data' => $address];
        } catch (\Exception $e) {
            Log::error('获取默认地址失败', [
                'user_id' => $userId,
                'error' => $e->getMessage(),
            ]);

            return ['code' => 500, 'message' => '获取默认地址失败'];
        }
    }

    /**
     * 添加地址
     */
    public function store($userId, array $data)
    {
        DB::beginTransaction();
        try {
            // 根据用户编号查询用户数据
            $user = MemberUser::findOrFail($userId);
            if ($user->state != 'enable') {
                return ['code' => 400, 'message' => '用户状态异常'];
            }

            // 如果用户只有一个地址，或者传入的is_default为true，则设置为默认地址
            $isFirst = $user->addresses()->count() == 0 || ($data['is_default'] ?? false);
            if ($isFirst) {
                $data['is_default'] = 1;
                // 将用户其他地址设为非默认
                $user->addresses()->update(['is_default' => 0]);
            }

            // 保存用户地址
            $user->addresses()->create($data);

            DB::commit();

            return ['code' => 200, 'message' => '添加成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('添加地址失败', [
                'user_id' => $userId,
                'data' => $data,
                'error' => $e->getMessage(),
            ]);

            return ['code' => 500, 'message' => '添加地址失败'];
        }
    }

    /**
     * 修改地址
     */
    public function update($userId, $id, array $data)
    {
        DB::beginTransaction();
        try {
            // 根据用户编号查询用户数据
            $user = MemberUser::findOrFail($userId);
            if ($user->state != 'enable') {
                return ['code' => 400, 'message' => '用户状态异常'];
            }

            // 根据地址编号查询地址数据
            $address = $user->addresses()
                ->where('id', $id)
                ->firstOrFail();

            // 如果用户只有一个地址，或者传入的is_default为true，则设置为默认地址
            $isFirst = $user->addresses()->count() == 1 || ($data['is_default'] ?? false);
            if ($isFirst) {
                $data['is_default'] = 1;
                // 将用户其他地址设为非默认
                $user->addresses()->update(['is_default' => 0]);
            }

            // 修改地址信息
            $address->update($data);

            DB::commit();

            return ['code' => 200, 'message' => '修改成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('修改地址失败', [
                'user_id' => $userId,
                'id' => $id,
                'data' => $data,
                'error' => $e->getMessage(),
            ]);

            return ['code' => 500, 'message' => '修改地址失败'];
        }
    }

    /**
     * 删除地址
     */
    public function destroy($userId, $id)
    {
        DB::beginTransaction();
        try {
            // 根据用户编号查询用户数据
            $user = MemberUser::findOrFail($userId);
            if ($user->state != 'enable') {
                return ['code' => 400, 'message' => '用户状态异常'];
            }

            // 根据地址编号查询地址数据
            $address = $user->addresses()
                ->where('id', $id)
                ->firstOrFail();

            // 删除地址
            $address->delete();

            DB::commit();

            return ['code' => 200, 'message' => '删除成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('删除地址失败', [
                'user_id' => $userId,
                'id' => $id,
                'error' => $e->getMessage(),
            ]);

            return ['code' => 500, 'message' => '删除地址失败'];
        }
    }

    /**
     * 设置默认地址
     */
    public function setDefault($userId, $id)
    {
        DB::beginTransaction();
        try {
            // 根据用户编号查询用户数据
            $user = MemberUser::findOrFail($userId);
            if ($user->state != 'enable') {
                return ['code' => 400, 'message' => '用户状态异常'];
            }

            // 根据地址编号查询地址数据
            $address = $user->addresses()
                ->where('id', $id)
                ->firstOrFail();

            // 将所有地址设为非默认
            $user->addresses()->update(['is_default' => 0]);

            // 设置为默认地址
            $address->update(['is_default' => 1]);

            DB::commit();

            return ['code' => 200, 'message' => '设置成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('设置默认地址失败', [
                'user_id' => $userId,
                'id' => $id,
                'error' => $e->getMessage(),
            ]);

            return ['code' => 500, 'message' => '设置默认地址失败'];
        }
    }
}
