<?php

namespace app\dao;

use App\model\Users;
use App\model\BankLog;
use App\Utils\FunctionResponse;


class UserDao
{
    /**
     * 用户注册函数
     *
     * @param string $phone 手机号
     * @param string $password 密码
     * @param string $idcard 身份证号
     * @return mixed
     */
    public static function register($phone, $password, $idcard)
    {
        // 检测手机号是否唯一
        if (Users::where('phone', $phone)->count() > 0) {
            return FunctionResponse::error(400, [], '手机号已存在');
        }

        // 检测身份证号码 并提取信息
        $idCardInfo = self::getDetailsFromIdCard($idcard);
        if ($idCardInfo['code'] !== 200) {
            return $idCardInfo;  // 返回错误信息
        }

        // 你可以在此处添加更多的注册逻辑,例如:存储用户信息到数据库

        // 假设我们通过 Users 模型来创建用户
        $user = new Users();
        $user->phone = $phone;
        $user->password = password_hash($password, PASSWORD_DEFAULT);  // 密码加密
        $user->cardid = $idcard;
        $user->birthday = $idCardInfo['data']['birthDate'];  // 出生日期
        $user->gender = $idCardInfo['data']['gender'];  // 性别
        $user->avatar = '';  // 头像
        $user->save();

        return FunctionResponse::success(200, ['$phone' => $phone], '注册成功');
    }

    /**
     * 检查身份证号,提取身份证号信息
     *
     * @param string $idCard
     * @return array
     */
    private static function getDetailsFromIdCard($idCard)
    {
        $birthDate = '';
        $gender = '';

        // 校验并处理18位身份证
        if (strlen($idCard) === 18) {
            // 提取出生日期
            $birthDate = substr($idCard, 6, 8);  // 获取出生日期(YYYYMMDD)

            // 性别判断:顺序码第17位奇数为男,偶数为女
            $genderCode = (int) $idCard[16];
            $gender = $genderCode % 2;
        } else {
            return FunctionResponse::error(400, [], '身份证格式不对');
        }

        // 格式化出生日期
        $birthYear = substr($birthDate, 0, 4);
        $birthMonth = substr($birthDate, 4, 2);
        $birthDay = substr($birthDate, 6, 2);
        $formattedBirthDate = $birthYear . '-' . $birthMonth . '-' . $birthDay;

        return FunctionResponse::success(200, [
            'birthDate' => $formattedBirthDate,  // 出生日期格式化
            'gender' => $gender,  // 性别
        ]);
    }
    /**
     * 手机号是否唯一
     * @param [string] $phone
     * @return [bole] 有手机号返回 true 没有返回flase
     */
    private static function isThePhoneNumberUnique($phone)
    {
        return Users::where('phone', $phone)->count() > 0;
    }
    /**
     * 修改密码
     * @param [int] $userid 用户id
     * @param [string] $phone 密码
     */
    public static function chang_passwd($userid,$password){
        //哈希密码
        $hasa_password=password_hash($password, PASSWORD_DEFAULT);
        Users::where('id', $userid)->update(['password' => $hasa_password]);
    }
    /**
     * 修改用户名
     * @param [int] $userid  用户id
     * @param [string] $nickname 用户名
     */
    public static function chang_nickname($userid,$nickname){
        Users::where('id', $userid)->update(['nickname' => $nickname]);
    }
}