<?php

namespace app\controller\api\v1;

use support\Request;

use App\Utils\ApiResponse;
use hg\apidoc\annotation as Apidoc;

use Tinywan\Jwt\JwtToken;
use App\model\User;
use App\model\Message;
use App\dao\UserDao;

/**
 * @Apidoc\Title("用户控制器")
 */
class UserController
{

    /**
     * 不需要登录的方法
     */
    protected $noNeedLogin = ['login', 'register'];

    /**
     * @Apidoc\Title("1.0 登录")
     * @Apidoc\Url("api/v1/user/login")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("phone", type="string",require=true, desc="用户名|手机号")
     * @Apidoc\Param("password", type="string",require=true, desc="密码")
     * @Apidoc\Returned("user", type="object", desc="用户信息")
     * @Apidoc\Returned("token", type="object", desc="令牌")
     */
    public function login(Request $request)
    {
        // 获取请求数据
        $data = $request->post();

        // 根据手机号查询用户
        $db = User::where('phone', '=', $data['phone'])->first();

        // 如果未找到用户，返回错误
        if (!$db) {
            return ApiResponse::error(402, '用户未注册');
        }

        // 获取用户输入的密码
        $password = $data['password'];

        // 验证密码是否正确
        if (password_verify($password, $db->password)) {
            $user = [
                'id'  => $db->id,
                'nickname'  => $db->nickname,
                'phone' => $db->phone
            ];
            // 如果密码正确，生成 JWT 令牌
            $token = JwtToken::generateToken($user);

            // 返回成功响应和用户信息（可以将 token 添加到响应中）
            return ApiResponse::success(200, [
                'user' => $user,  // 返回用户信息
                'token' => $token  // 返回生成的 token
            ]);
        } else {
            // 密码错误，返回错误响应
            return ApiResponse::error(402, '密码错误');
        }
    }
    /**
     * @Apidoc\Title("1.0 注册")
     * @Apidoc\Url("api/v1/user/register")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("phone", type="string",require=true, desc="用户名|手机号")
     * @Apidoc\Param("password", type="string",require=true, desc="密码")
     * @Apidoc\Param("idcard", type="string",require=true, desc="身份证号")
     * @Apidoc\Returned("token", type="object", desc="令牌")
     */
    public function register(Request $request)
    {
        $data = $request->post();
        $user = UserDao::register($data['phone'], $data['password'], $data['idcard']);
        if ($user['code'] != 200) {
            return ApiResponse::error(402, [], $user['message']);
        }
        $db = User::where('phone', '=', $data['phone'])->first();
        $user = [
            'id'  => $db->id,
            'nickname'  => $db->nickname,
            'phone' => $db->phone
        ];
        // 如果密码正确，生成 JWT 令牌
        $token = JwtToken::generateToken($user);
        $msg = new Message();
        $msg->title ="系统提醒";
        $msg->content = "您已注册成功";
        $msg->type =0;
        $msg->userid =$db->id;
        $msg->parameters="";
        // 返回成功响应和用户信息（可以将 token 添加到响应中）
        return ApiResponse::success(200, [
            'user' => $user,  // 返回用户信息
            'token' => $token  // 返回生成的 token
        ]);
    }

    /**
     * @Apidoc\Title("1.0 修改用户信息")
     * @Apidoc\Url("api/v1/user/edi")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("nickname", type="string",require=true, desc="昵称")
     * @Apidoc\Param("oldpassword", type="string",require=true, desc="旧密码")
     * @Apidoc\Param("password", type="string",require=true, desc="密码")
     */
    public function edi(Request $request)
    {
        $data = $request->post();
        $user = $request->data;
        $userid = $user['id'];
        $db = User::where('id', '=', $userid)->first();
        if (isset($data['password']) && $data['password'] != '') {
            if (password_verify($data['oldpassword'], $db->password)) {
                UserDao::chang_passwd($userid, $data['password']);
                return ApiResponse::success(200, [], "修改密码成功");
            }
            return ApiResponse::success(402, [], "旧密码错误");
        }
        if (isset($data['nickname']) && $data['nickname'] != '') {
            UserDao::chang_nickname($userid, $data['nickname']);

            $user = [
                'id'  => $db->id,
                'nickname'  => $data['nickname'],
            ];
            // 返回成功响应和用户信息（可以将 token 添加到响应中）
            return ApiResponse::success(200, [
                'user' => $user,  // 返回用户信息
            ]);
        }
    }

    

}
