<?php

namespace addons\exam\controller;

use addons\exam\library\CacheService;
use addons\exam\library\WechatService;
use addons\exam\model\UserInfoModel;
use addons\exam\model\UserModel;
use app\common\library\Token;
use think\Validate;

/**
 * 会员接口
 */
class User extends Base
{
    protected $noNeedLogin = ['login', 'userLogin', 'register'];
    protected $noNeedRight = '*';
    protected $visibleFields = ['id', 'avatar', 'gender', 'nickname', 'mobile', 'birthday', 'status', 'createtime', 'logintime'];

    /**
     * 授权登录
     * @ApiMethod   (POST)
     * @param string $code     授权code
     * @param string $userInfo 授权后拿到的用户信息
     */
    public function login()
    {
        $user_info    = input('userInfo/a', []);
        $code         = input('code/s', '');
        $from_user_id = input('from_user_id/d', 0);

        if (!$code) {
            fail('缺少小程序参数code');
        }
        if (!$user_info) {
            fail('缺少小程序参数userInfo');
        }

        $service     = new WechatService();
        $wechat_user = $service->miniLogin($code);
        if (!isset($wechat_user['openid'])) {
            fail('获取小程序用户信息失败');
        }

        $open_id     = $wechat_user['openid'];
        $session_key = $wechat_user['session_key'] ?? '';

        $user = UserModel::get(['username' => $open_id]);
        if (empty($user)) {
            $user = UserModel::fastRegister($open_id, $user_info['nickName'] ?? '', $user_info['avatarUrl'] ?? '', $user_info['gender'] ?? 0);
            if (!$user) {
                fail('注册用户失败');
            }
        } else {
            $data = [
                // 'nickname'  => $user_info['nickName'],
                // 'avatar'    => $user_info['avatarUrl'],
                'logintime' => time(),
            ];

            // if (!$user->parent_id) {
            //     $data['parent_id'] = $from_user_id;
            // }

            $user->isUpdate(true)->save($data);
        }

        // 记录session_key，用于后续获取手机号码等功能
        CacheService::setWechatUserSessionKey($user->id, $session_key);

        // 清除之前的token
        Token::clear($user->id);

        // 直接登录
        $this->auth->direct($user->id);

        // 用户扩展信息
        $info = UserInfoModel::getUserInfo($user->id);

        $this->success('', [
            'token' => $this->auth->getToken(),
            'user'  => array_merge($user->only($this->visibleFields), ['info' => $info->toArray()]),
        ]);
    }

    /**
     * 用户信息
     */
    public function info()
    {
        $user         = $this->auth->getUser()->visible($this->visibleFields)->toArray();
        $user['info'] = UserInfoModel::getUserInfo($this->auth->id);
        $this->success('', $user);
    }

    /**
     * 获取微信绑定的手机号码
     */
    public function getWechatPhone()
    {
        $iv            = input('iv/s', '');
        $encryptedData = input('encryptedData/s', '');

        if (!$iv) {
            fail('缺少小程序参数iv');
        }
        if (!$encryptedData) {
            fail('缺少小程序参数encryptedData');
        }
        if (!$session_key = CacheService::getWechatUserSessionKey($this->auth->id)) {
            fail('微信sessionKey丢失，请重新登录再试');
        }

        // try {
        $service = new WechatService();
        $data    = $service->decryptedData($session_key, $iv, $encryptedData);
        succ($data);
        // } catch (\Exception $exception) {
        //     fail('sessionKey失效，请重新登录再试：' . $exception->getMessage());
        // }
    }

    /**
     * 保存个人信息
     */
    public function save()
    {
        $update_fields = ['avatar', 'nickname', 'mobile', 'gender', 'birthday'];
        $data          = ['updatetime' => time()];
        foreach ($update_fields as $field) {
            $value = input("{$field}/s", '');
            if ($value !== '') {
                $data[$field] = $value;
            }
        }

        $user = $this->auth->getUser();
        if ($user->save($data)) {
            succ(['user' => $user->visible($this->visibleFields)]);
        }

        fail('保存失败，请重试');
    }

    /**
     * 账号密码注册
     */
    public function register()
    {
        if (!$username = input('username/s')) {
            fail('请填写登录账号');
        }
        if (!$password = input('password/s')) {
            fail('请填写登录密码');
        }
        if (!$nickname = input('nickname/s')) {
            fail('请填写昵称');
        }
        if (!$mobile = input('mobile/s')) {
            fail('请填写手机号码');
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            fail(__('Mobile is incorrect'));
        }
        $gender = input('gender/d', 1);

        // 注册
        $user = UserModel::fastRegister($username, $nickname, '', $gender, $password, $mobile);
        // 用户扩展信息
        $info = UserInfoModel::getUserInfo($user->id);
        // 接口层登录
        $this->auth->direct($user->id);
        succ([
            'user'  => array_merge($user->only($this->visibleFields), ['info' => $info->toArray()]),
            'token' => $this->auth->getToken()
        ]);
    }

    /**
     * 账号密码登录
     */
    public function userLogin()
    {
        if (!$username = input('username/s')) {
            fail('请填写登录账号');
        }
        if (!$password = input('password/s')) {
            fail('请填写登录密码');
        }

        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }

        $user = UserModel::get(['username' => $username]);
        if (!$user) {
            fail('登录失败，账号或密码错误');
        }
        if ($user->password != $this->auth->getEncryptPassword($password, $user->salt)) {
            fail('登录失败，账号或密码错误');
        }
        if ($user->status != 1) {
            fail('登录失败，账号已被禁用登录');
        }

        // 用户扩展信息
        $info = UserInfoModel::getUserInfo($user->id);
        // 接口层登录
        $this->auth->direct($user->id);
        succ([
            'user'  => array_merge($user->only($this->visibleFields), ['info' => $info->toArray()]),
            'token' => $this->auth->getToken()
        ]);
    }

    /**
     * 保存用户常用题库设置
     */
    // public function saveMyCate()
    // {
    //     if (!$cate_id = input('cate_id/d', 0)) {
    //         fail('请选择常用题库类型');
    //     }
    //     if (!$cate = CateModel::get($cate_id)) {
    //         fail('题库类型不存在，请重新选择');
    //     }
    //
    //     $cate_ids   = [$cate['id']];
    //     $cate_names = [$cate['name']];
    //
    //     // 上级
    //     if ($cateParent1 = CateModel::where('id', $cate['parent_id'])->find()) {
    //         array_unshift($cate_ids, $cateParent1['id']);
    //         array_unshift($cate_names, $cateParent1['name']);
    //
    //         // 上上级
    //         if ($cateParent2 = CateModel::where('id', $cateParent1['parent_id'])->find()) {
    //             array_unshift($cate_ids, $cateParent2['id']);
    //             array_unshift($cate_names, $cateParent2['name']);
    //         }
    //     }
    //
    //     $info                     = UserInfoModel::getUserInfo($this->auth->id);
    //     $info->default_cate_ids   = $cate_ids;
    //     $info->default_cate_names = $cate_names;
    //
    //     if ($info->save()) {
    //         succ($info->toArray());
    //     }
    //
    //     fail('保存失败，请重试');
    // }
}
