<?php

declare(strict_types=1);

namespace App\Controller;

use App\JsonRpc\UserServiceInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use App\Tools\Result;
use App\Constants\ErrorCode;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
/**
 * Class UserController
 * @package App\Controller
 */
#[AutoController]
class UserController extends AbstractController
{
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;
    /**
     * @var UserServiceInterface
     */
    #[Inject]
    private $userServiceClient;

    public function createUser()
    {
        $requireData = $this->request->all();
        $validator = $this->validationFactory->make(
            $requireData,
            [
                'user_name' => 'required',
                'password' => 'required|min:6',
                'confirm_password' => 'required',
                'email' => 'email',
                'mobile' =>'required'
            ],
            [
                'usernuser_name.required' => '用户名不能为空',
                'password.required' => '密码不能为空',
                'email.email' => '请填写一个有效的邮箱',
                'mobile.required' => '手机号码必填',
//                'mobile.telephone_number' => '请填写一个有效的手机号',
                'confirm_password.required' =>"确认密码不能为空",
                'password.min' =>"密码长度不能低于6位数",
            ]
        );
        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            return Result::error($errorMessage);
        }
        if($requireData['password']!=$requireData['confirm_password']){
            return Result::error("两次密码不一致");
        }
        $salt = rand(1, 999999);
        $requireData['salt'] = $salt;
        $loginIp = $this->request->getHeader('x-forwarded-for')[0] ?? $this->request->getHeader('x-real-ip')[0] ?? $this->request->getServerParams()['remote_addr'] ?? '0.0.0.0';
        $requireData['last_login_ip'] = $loginIp;

        $this->logger->info("创建用户入参：", $requireData);
        $result =  $this->userServiceClient->createUser($requireData);
        $this->logger->info("创建用户返回值：", $result);
        return $result['code']==200?Result::success($result['data']):Result::error($result['message']);
    }

    /**
     * 更新用户
     * @return array
     */
    public function updateUser()
    {
        $requireData = $this->request->all();
        $validator = $this->validationFactory->make(
            $requireData,
            [
                'user_name' => 'required',
                'email' => 'email',
                'mobile' =>'required'
            ],
            [
                'usernuser_name.required' => '用户名不能为空',
                'email.email' => '请填写一个有效的邮箱',
                'mobile.required' => '手机号码必填',
            ]
        );
        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            return Result::error($errorMessage);
        }
        if($requireData['password'] && $requireData['confirm_password']){
            if($requireData['password'] != $requireData['confirm_password']){
                return Result::error("两次密码不一致");
            }
        }

        $salt = rand(1, 999999);
        $requireData['salt'] = $salt;
        $loginIp = $this->request->getHeader('x-forwarded-for')[0] ?? $this->request->getHeader('x-real-ip')[0] ?? $this->request->getServerParams()['remote_addr'] ?? '0.0.0.0';
        $requireData['last_login_ip'] = $loginIp;

        $result =  $this->userServiceClient->updateUser($requireData);
        $this->logger->info("修改用户返回值：", $result);
        return $result?Result::success($result['data']):Result::error($result['message']);
    }

    /**
     * 获取用户信息
     * @return array|void
     */
    public function getUserInfo()
    {

        $result =  $this->userServiceClient->getUserInfo($this->UserId);
        if ($result['code'] != ErrorCode::SUCCESS) {
            return Result::error($result['message'],0,[]);
        }
        return Result::success($result['data']);
    }

    /**
     * 获取用户列表
     * @return array
     */
    public function getUserList(){
        $requireData = $this->request->all();
        $requireData['keyword'] = $requireData['keyword']??'';
        $result =  $this->userServiceClient->getUserList($requireData);

        if ($result['code'] != ErrorCode::SUCCESS) {
            return Result::error($result['message'],0,[]);
        }
        return Result::success($result['data']);
    }
    /**
     * 删除用户
     * @return array
     */
    public function delUser()
    {
        $requireData = $this->request->all();
        $validator = $this->validationFactory->make(
            $requireData,
            [
                'id' => 'required'
            ],
            [
                'id.required' => '用户ID不能为空'
            ]
        );
        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            return Result::error($errorMessage);
        }

        $result =  $this->userServiceClient->delUser($requireData['id']);
        if ($result['code'] != ErrorCode::SUCCESS) {
            return Result::error($result['message'],0,[]);
        }
        return Result::success($result['data']);
    }

    /**
     * 验证用户是否存在
     * @return void
     */
    public function  verifyUserInfo()
    {
        $requireData = $this->request->all();
        $result =  $this->userServiceClient->verifyUserInfo($requireData);
        if ($result['code'] != ErrorCode::SUCCESS) {
            return Result::error($result['message'],0,[]);
        }
        return Result::success($result['data']);
    }
    /**
     * 角色列表
     * @return array|void
     */
    public function roleList()
    {
        $requireData = $this->request->all();
        $result =  $this->userServiceClient->roleList($requireData);
        if($result['data']){
            foreach ($result['data']['rows'] as $k=>$v) {
                $result['data']['rows'][$k]['rule'] = $v['rule']?json_decode($v['rule']):[];
            }
        }
        if ($result['code'] != ErrorCode::SUCCESS) {
            return Result::error($result['message'],0,[]);
        }
        return Result::success($result['data']);
    }

    /**
     * 添加角色
     * @return array
     */
    public function addRole()
    {
        $requireData = $this->request->all();
        $validator = $this->validationFactory->make(
            $requireData,
            [
                'role_name' => 'required'
            ],
            [
                'role_name.required' => '角色名称不能为空'
            ]
        );
        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            return Result::error($errorMessage);
        }
        $requireData['user_id'] = $this->UserId;
        $result =  $this->userServiceClient->addRole($requireData);
        if ($result['code'] != ErrorCode::SUCCESS) {
            return Result::error($result['message'],0,[]);
        }
        return Result::success($result['data']);
    }

    /**
     * 删除角色
     * @return array
     */
    public function delRole()
    {
        $requireData = $this->request->all();
        $validator = $this->validationFactory->make(
            $requireData,
            [
                'id' => 'required'
            ],
            [
                'id.required' => '角色ID不能为空'
            ]
        );
        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            return Result::error($errorMessage);
        }
        $requireData['user_id'] = $this->UserId;
        $result =  $this->userServiceClient->delRole($requireData);
        if ($result['code'] != ErrorCode::SUCCESS) {
            return Result::error($result['message'],0,[]);
        }
        return Result::success($result['data']);
    }

    /**
     * 更新角色
     * @return array
     */
    public function updateRole()
    {
        $requireData = $this->request->all();
        $validator = $this->validationFactory->make(
            $requireData,
            [
                'role_name' => 'required',
                'id' => 'required'
            ],
            [
                'id.required' => '角色ID不能为空',
                'role_name.required' => '角色名称不能为空'
            ]
        );
        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            return Result::error($errorMessage);
        }
        $requireData['user_id'] = $this->UserId;
        $requireData['rule'] = $requireData['rule']?json_encode($requireData['rule']):[];
        $result =  $this->userServiceClient->updateRole($requireData);
        if ($result['code'] != ErrorCode::SUCCESS) {
            return Result::error($result['message'],0,[]);
        }
        return Result::success($result['data']);
    }




}