<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\api\controller\user;

use app\api\controller\BaseApiController;
use app\service\api\user\UserService;
use app\validate\api\UserValidator;
use app\validate\domain\UserDomainValidator;
use think\Request;


/**
 * C端用户个人中心控制器
 * 用户资料、等级、邮箱绑定、账号注销、绑定邀请
 * @package app\api\controller\user
 */
class User extends BaseApiController
{
    /**
     * 用户等级
     * @return \think\response\Json
     */
    public function levels()
    {
        return json($this->app->make(UserService::class)->levels());
    }


    /**
     * 用户信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function profile(Request $request)
    {
        $result = $this->app->make(UserService::class)->profile($request);
        $httpStatus = (int)($result['_http_status'] ?? 200);
        unset($result['_http_status']);
        return json($result, $httpStatus);
    }


    /**
     * 更新用户信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function updateProfile(Request $request)
    {
        $params = $this->requestPayload($request);
        $this->validate($params, UserValidator::class . '.update_profile');
        $this->validateDomain($this->app->make(UserDomainValidator::class), $params, 'update_profile');

        $result = $this->app->make(UserService::class)->updateProfile($request, $params);
        $httpStatus = (int)($result['_http_status'] ?? 200);
        unset($result['_http_status']);
        return json($result, $httpStatus);
    }


    /**
     * 发送邮箱验证码
     * @param Request $request
     * @return \think\response\Json
     */
    public function sendEmailCode(Request $request)
    {
        $params = $this->requestPayload($request);
        $this->validate($params, UserValidator::class . '.send_email_code');
        $this->validateDomain($this->app->make(UserDomainValidator::class), $params, 'send_email_code');

        $result = $this->app->make(UserService::class)->sendEmailCode($request, $params);
        $httpStatus = (int)($result['_http_status'] ?? 200);
        unset($result['_http_status']);
        return json($result, $httpStatus);
    }

    /**
     * 绑定邮箱
     * @param Request $request
     * @return \think\response\Json
     */
    public function bindEmail(Request $request)
    {
        $params = $this->requestPayload($request);
        $this->validate($params, UserValidator::class . '.bind_email');
        $this->validateDomain($this->app->make(UserDomainValidator::class), $params, 'bind_email');

        $result = $this->app->make(UserService::class)->bindEmail($request, $params);
        $httpStatus = (int)($result['_http_status'] ?? 200);
        unset($result['_http_status']);
        return json($result, $httpStatus);
    }

    /**
     * 注销账号
     * @param Request $request
     * @return \think\response\Json
     */
    public function cancelAccount(Request $request)
    {
        $params = $this->requestPayload($request);
        $this->validate($params, UserValidator::class . '.cancel_account');
        $this->validateDomain($this->app->make(UserDomainValidator::class), $params, 'cancel_account');

        $result = $this->app->make(UserService::class)->cancelAccount($request);
        $httpStatus = (int)($result['_http_status'] ?? 200);
        unset($result['_http_status']);
        return json($result, $httpStatus);
    }


    /**
     * 退出登录
     * @return \think\response\Json
     */
    public function logout()
    {
        return json(['code' => 0, 'msg' => '']);
    }


    /**
     * 绑定邀请码
     * @param Request $request
     * @return \think\response\Json
     */
    public function bindInvite(Request $request)
    {
        $inviteCode = trim((string)$request->post('invite_code', ''));
        if ($inviteCode === '') {
            return json(['code' => 1, 'msg' => '']);
        }

        $userId = (int)($request->user->id ?? $request->uid ?? 0);
        if ($userId <= 0) {
            return json(['code' => 1, 'msg' => ''], 401);
        }

        $result = $this->app->make(\app\service\domain\user\CoreUserService::class)
            ->bindByInviteCode($userId, $inviteCode);

        $httpStatus = (int)($result['code'] ?? 0) === 0 ? 200 : 400;
        return json($result, $httpStatus);
    }

    /**
     * 获取请求负载数据
     * 支持 form-data 和 JSON 两种格式
     * @param Request $request
     * @return array
     */
    private function requestPayload(Request $request): array
    {
        $post = $request->post();
        if (is_array($post) && !empty($post)) {
            return $post;
        }

        $rawInput = trim((string)$request->getContent());
        if ($rawInput === '') {
            return [];
        }

        $rawInput = preg_replace('/^\xEF\xBB\xBF/', '', $rawInput) ?? $rawInput;
        $input = json_decode($rawInput, true);
        if (is_array($input)) {
            return $input;
        }

        $input = [];
        parse_str($rawInput, $input);
        return is_array($input) ? $input : [];
    }
}