<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\BaseService;
use App\Services\JwtService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\Admin as AdminModel;
use Exception;
use Illuminate\Validation\ValidationException;
use function Symfony\Component\HttpFoundation\Session\Storage\Handler\commit;
use App\Services\AdminService;
use Illuminate\Validation\Rule;

/**
 * @apiDefine result
 * @apiSuccess (成功) {Number} code=0 错误代码 0-请求成功 详见  <a href="javascript:;" onclick="toMenu('Error','GetGeterrorcode')">错误代码</a>
 * @apiSuccess (成功) {Number} timestamp 服务器时间戳
 * @apiSuccess (成功) {String} msg 错误信息 OK为成功
 * @apiSuccess (成功) {Array} [data] 数据 若code!=0 则为错误数据，code=101009 该值为验证失败的详情
 *
 *
 */
/**
 * @apiDefine header
 * @apiHeader {String} Authorization "Bearer "+ token
 *
 */

/**
 * @api {get} /getErrorCode 错误代码
 * @apiGroup Error
 * @apiSampleRequest off
 * @apiDescription 下面列出一些常见的错误代码：
 * | code    | 说明                                                                              |
 * |---------|-----------------------------------------------------------------------------------|
 * |-1       |  未知错误，联系开发人员                                                             |
 * |0        |  OK 请求成功                                                                       |
 * |101001   |  用户不存在                                                                        |
 * |101002   |  密码错误                                                                          |
 * |101003   |  验证码错误                                                                        |
 * |101004   |  验证码已过期                                                                      |
 * |101005   |  密码不一致                                                                        |
 * |101006   |  用户名已存在，请直接登录                                                           |
 * |101007   |  邮箱已存在，请直接登录                                                             |
 * |101008   |  用户名错误                                                                       |
 * |101009   |  参数验证失败，具体错误信息见 data                                                  |
 * |101010   |  系统错误                                                                         |
 * |101011   |  没有登录，请检查登录状态                                                           |
 * |101012   |  禁止收藏自己                                                                     |
 * |101013   |  先填写基本信息                                                                   |
 * |101014   |  请求地址不存在，请检查请求地址是否正确                                              |
 * |101015   |  上传的头像必须是正方形的，如果用户所选的图片不是方形的，请裁剪后上传                   |
 * |101016   |  没有匹配到合适的对象                                                              |
 * |101017   |  可收藏数达到最大值，完善资料可获取更多数量                                           |
 * |101018   |  发送失败                                                                        |
 * |101019   |  手机号码不正确                                                                    |
 * |101020   |  帖子不存在                                                                        |
 * |101021   |  文件上传错误                                                                      |
 * |101022   |  邀请码错误                                                                       |
 * |101023  |  用户已在其他设备登录                                                                |
 * |101024   |  剩余抽奖次数不足                                                                   |
 * |101025   |  地址数量最多10条                                                                   |
 * |101026   | post请求错误 |
 * |101027   | IM 错误 |
 * |101028   | 手机号已存在或已绑定其他账号，请直接登录或绑定其它手机号 |
 * |101029   | 谷歌登录错误 |
 * |101030   | 聊天余额不足 |
 * |101031   | 钱包余额不足 |
 * |101032   | Facebook 错误 |
 * |101033   | 资料验证失败，请检查当前是否是待验证状态 |
 *
 * @apiVersion 1.0.0
 */
class Admin extends Controller
{
    protected $jwtService;

    public function __construct(JwtService $jwtService)
    {
        $this->jwtService = $jwtService;
    }

    /**
     * @api {post} /admin/setPassword 修改密码
     * @apiGroup 管理员
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {string} oldPassword 旧密码
     * @apiParam {string} password 新密码
     * @apiParam {string} password_confirmation 确认密码
     *
     */
    public function setPassword()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'oldPassword' => ['required', 'string', 'min:1'],
                'password' => ['required', 'string', 'min:8', 'max:20', 'confirmed'],
            ]);

            $user = request()->user;
            $oldPassword = request()->input('oldPassword', '');
            $password = request()->input('password', '');
            if (!password_verify($oldPassword, $user->password)) {
                throw new Exception('', HttpStatus::PASSWORDS_ERROR);
            }
            $user->password = password_hash($password, PASSWORD_DEFAULT);
            $user->save();
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(intval($e->getCode()));
        }
        return $this->success();
    }

    public function logout()
    {
        Auth::logout();
        session()->regenerateToken();
        return $this->success();
    }

    /**
     * @api {post} /admin/login 登录
     * @apiGroup 管理员
     * @apiUse result
     * @apiVersion 1.0.0
     * @apiParam {string} username
     * @apiParam {string} password
     *
     * @apiSuccess (成功) data
     * @apiSuccess (成功) data.token
     */
    function login()
    {
        try {
            $username = request()->input('username');
            $password = request()->input('password');
            $user = AdminModel::login($username, $password);
            $token = $this->jwtService->generateToken($user);
            Cache::put("user_{$user->getId()}_jwt", $token);


        } catch (Exception $e) {
            return $this->error(intval($e->getCode()));
        }
        $data = [
            'token' => "Bearer $token",
            'userInfo' => $user
        ];
        return $this->success($data);
    }

    function test()
    {
        return $this->success('ok');
    }

    /**
     * @api {get} /admin/index 人员列表
     * @apiGroup 管理员
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} [page=1]
     * @apiParam {int} [limit=10]
     * @apiParam {string} [username] 账号
     * @apiParam {string} [nickname] 昵称
     *
     * @apiSuccess (data) {Object} data
     * @apiSuccess (data) {int} data.total 数量
     * @apiSuccess (data) {Object[]} data.data 列表
     * @apiSuccess (data) {int} data.data.id
     * @apiSuccess (data) {string} data.data.username 账号
     * @apiSuccess (data) {string} data.data.nickname 昵称
     * @apiSuccess (data) {array} data.data.roles_ids 账号的角色
     * @apiSuccess (data) {array} data.data.roles_names 账号的角色名称
     * @apiSuccess (data) {string} data.data.updated_at
     * @apiSuccess (data) {string} data.data.created_at
     */
    public function index()
    {
        // try {
        request()->validate([
            'username' => ['nullable', 'string'],
            'nickname' => ['nullable', 'string'],
        ]);
        $search = request()->all();
        $result = AdminService::paginate($search);
        // } catch (ValidationException $e) {
        //     return $this->error(HttpStatus::VALIDATION_FAILED, '', $e->errors());
        // } catch (Exception $e) {
        //     return $this->error(intval($e->getCode()));
        // }
        return $this->success($result);
    }


    /**
     * @api {post} /admin/submit 修改账号
     * @apiGroup 管理员
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} id 角色ID
     * @apiParam {string} username 账号
     * @apiParam {string} nickname 昵称
     * @apiParam {string} password 密码
     * @apiParam {array} roles_ids 账号角色
     */
    public function store()
    {
        try {
            $id = request()->input('id');
            $validator = [
                'username' => 'required|string|min:5|max:50|alpha_dash|unique:admin,username',
                'nickname' => 'required|string|max:100',
                'password' => ['nullable', 'string', 'min:6', 'max:20'],
                'cellphone' => ['required', 'string'],
                'email' => ['required', 'email'],
                'remarks' => ['nullable', 'string'],
                'roles_ids' => ['nullable', 'array'],
                'id' => ['nullable', 'integer', 'min:1'],

            ];
            if (!empty($id)) {
                if ($id == 1) {
                    unset($validator['username'], $validator['password'],$validator['roles_ids']);
                } else {
                    $validator['roles_ids'] = ['required', 'array', 'min:1'];
                    $validator['roles_ids.*'] = ['required', 'integer', 'min:1'];
                    $validator['username'] = ['required', 'string', 'max:50', 'alpha_dash',
                        Rule::unique('admin', 'username')->ignore($id), // 忽略当前 ID
                    ];
                }
            }
            $params = request()->validate($validator);
            if ($id == 1) $params['roles_ids'] = [];
            $ret = AdminService::submit($params);
            if ($ret['code'] == BaseService::NOT) {
                throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
            }
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getCode(), $e->getMessage());
        }
        return $this->success();
    }

    /**
     * @api {post} /admin/delete 删除账号
     * @apiGroup 管理员
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} id 角色ID
     */
    public function destroy()
    {
        $id = request()->post('id');
        if ($id == 1) {
            return $this->error(HttpStatus::CUSTOM_ERROR, '超级管理员禁止操作');
        }
        // 示例：通过 ID 删除菜单
        $info = AdminService::findOne(['id' => $id]);
        if (!$info) {
            return $this->error(0, '账号不存在');
        }

        $info->delete();

        return $this->success([], '删除成功');
    }
}
