<?php

namespace App\Services\Client;

use App\Models\CoachUser;
use App\Models\MemberUser;
use App\Models\SysConfig;
use App\Models\Wallet;
use App\Models\WalletWithdrawRecord;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class UserService
{
    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        $user = Auth::user();
        $wallet = Wallet::where('owner_id', $user->id)
            ->where('owner_type', 'USER')
            ->first();

        return [
            'user' => $user,
            'wallet' => $wallet ? [
                'id' => $wallet->id,
                'balance' => $wallet->available_balance,
            ] : null,
        ];
    }

    /**
     * 修改用户信息
     */
    public function updateUserInfo(array $data)
    {
        $user = Auth::user();
        $user->update($data);

        return ['message' => '修改成功'];
    }

    /**
     * 获取用户钱包
     */
    public function getUserWallet()
    {
        $user = Auth::user();
        $wallet = $user->wallet;
        if (! $wallet) {
            throw new \Exception('钱包不存在');
        }

        return $wallet;

    }

    /**
     * 用户提现
     */
    public function withdraw($amount, $type = 'wechat', $area_code = '')
    {
        // 获取当前用户
        $user = Auth::user();
        if (! $user || $user->state !== 'enable') {
            throw new \Exception('用户状态异常');
        }

        // 获取钱包并检查余额
        $wallet = $user->wallet;
        if ($wallet->state !== 'enable') {
            throw new \Exception('钱包已冻结');
        }

        if ($wallet->available_balance < $amount) {
            throw new \Exception('钱包余额不足');
        }

        $config = SysConfig::where('key', 'withdraw_min_amount')->first();
        $configValue = json_decode($config?->value, true);

        $minAmount = $configValue['minAmount'] ?? 1;
        $maxAmount = $configValue['maxAmount'] ?? 10000;
        $fee = $configValue['fee'] ?? 0.00;

        if ($amount < $minAmount) {
            throw new \Exception("提现金额不能小于{$minAmount}元");
        }

        if ($amount > $maxAmount) {
            throw new \Exception("提现金额不能大于{$maxAmount}元");
        }

        // 创建提现记录
        DB::transaction(function () use ($amount, $fee, $wallet, $type, $area_code) {
            WalletWithdrawRecord::create([
                'wallet_id' => $wallet->id,
                'amount' => $amount,    // 提现金额
                'withdraw_type' => $type,   // 提现方式
                'fee' => $fee,    // 提现手续费
                'area_code' => $area_code,    // 行政区划代码
                'state' => 'processing',    // 状态
            ]);

            // 扣除钱包余额
            $wallet->available_balance -= $amount;
            $wallet->total_balance -= $amount;
            $wallet->save();
        });

        return ['message' => '提现申请已提交'];
    }

    /**
     * 用户反馈
     */
    public function feedback($content)
    {
        $user = Auth::user();
        if (! $user || $user->state !== 'enable') {
            throw new \Exception('用户状态异常');
        }

        // UserFeedback::create([
        //     'owner_id' => $user->id,
        //     'owner_type' => MemberUser::class,
        //     'content' => $content
        // ]);

        return ['message' => '反馈已提交'];
    }

    /**
     * 申请成为技师
     */
    public function applyCoach($mobile = '', $gender = '', $work_years = '', $intention_city = '')
    {
        // 获取当前用户
        $user = Auth::user();

        // 检查用户状态
        if ($user->state !== 'enable') {
            throw new \Exception('用户状态异常');
        }

        // 检查是否已经申请过
        $coach = $user->coach;
        if ($coach) {
            if ($coach->state === 'pending') {
                throw new \Exception('您已提交申请，请等待审核');
            }
            if ($coach->state === 'enable') {
                throw new \Exception('您已经是技师了');
            }
            if ($coach->state === 'disable') {
                throw new \Exception('您的技师资格已被禁用');
            }
        }

        // 创建技师申请
        DB::transaction(function () use ($user, $mobile, $gender, $work_years, $intention_city) {
            // 创建技师基本信息
            $coach = CoachUser::create([
                'user_id' => $user->id,
                'state' => 'pending',  // 待审核状态
            ]);

            $coach->infoRecords()->create([
                'nickname' => $user->nickname ?? '',  // 姓名
                'mobile' => $mobile,    // 服务电话
                'avatar' => $user->avatar ?? '',  // 头像
                'gender' => $gender ?? 'unknown',  // 性别
                'work_years' => $work_years ?? '',  // 从业年份
                'intention_city' => $intention_city ?? '',   // 意向城市
                'state' => 'pending',
            ]);

        });

        return [
            'message' => '申请已提交，请等待审核',
        ];
    }
}
