<?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
{
    use \Hyperf\Di\Aop\ProxyTrait;
    use \Hyperf\Di\Aop\PropertyHandlerTrait;
    function __construct(\Hyperf\Logger\LoggerFactory $loggerFactory)
    {
        if (method_exists(parent::class, '__construct')) {
            parent::__construct(...func_get_args());
        }
        $this->__handlePropertyHandler(__CLASS__);
    }
    #[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);
        $data = [
            'user_name' => $requireData['user_name'],
            'password' => $requireData['password'],
            'avatar' => $requireData['avatar'],
            'mobile' => $requireData['mobile'],
            'status' => isset($requireData['status']) ?? 1,
            'role_id' => $requireData['role_id'] ?? 0,
            'email' => $requireData['email'] ?? '',
            'salt' => $salt,
            'rong_token' => '',
            'level_id' => $requireData['level_id'],
            //会员等级
            'id_card' => isset($requireData['id_card']) ?? '',
            //身份证号
            'birthday' => isset($requireData['birthday']) ?? '',
            //生日
            'gender' => isset($requireData['gender']) ?? '',
            //性别
            'real_name' => isset($requireData['real_name']) ?? '',
        ];
        $this->logger->info("创建用户入参：", $data);
        $result = $this->userServiceClient->createUser($data);
        $this->logger->info("创建用户返回值：", $result);
        return $result ? Result::success($result['data']) : Result::error($result['message']);
    }
    /**
     * @return array|void
     */
    public function getUserInfo()
    {
        $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->getUserInfo((int) $requireData['id']);
        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']);
    }
}