<?php

namespace App\Http\Controllers\User;


use App\Consts\ErrorConst;
use App\Libs\ApiResponse;
use App\Libs\TikTok\Kernel\Exceptions\Exception;
use App\Libs\Utils;
use App\Services\Book\BookService;
use App\Services\OpenApi\OpenService;
use App\Services\Report\ReportService;
use App\Services\User\UserService;
use App\Transformer\User\UserTransformer;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use App\Exceptions\ApiException;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Validator;

class UserController extends BaseController
{
    use ApiResponse;

    protected $userService;
    protected $openService;
    protected $bookService;
    protected $reportService;

    public function __construct(
        UserService   $userService,
        OpenService   $openService,
        BookService   $bookService,
        ReportService $reportService
    )
    {
        $this->userService   = $userService;
        $this->openService   = $openService;
        $this->bookService   = $bookService;
        $this->reportService = $reportService;
    }

    /**
     * 登录接口
     *
     * @param Request $request
     * @return mixed
     * @throws ApiException
     * @throws GuzzleException
     */
    public function login(Request $request)
    {
        $params        = $request->all();
        $sendOrderId   = (int)getProp($params, 'send_order_id');
        $code          = trim(getProp($params, 'code'));
        $anonymousCode = trim(getProp($params, 'anonymous_code'));
        if (empty($code)) {
            Utils::throwError(ErrorConst::PARAM_ERROR_CODE);
        }

        dLog('login')->info('params', $params);

        // 授权
        $user = $this->openService->getInstance()->code2Session($sendOrderId, $code, $anonymousCode);

        // 绑定邀请码
        try {
            $this->userService->bindUser($params);
        } catch (\Exception $e) {
            dLog('exception')->info('login-bind-fail', [
                'params'        => $params,
                'user'          => $user,
                'exception_msg' => $e->getMessage()
            ]);
        }

        // 上报注册
        try {
            $this->reportService->reportRegister($user, $params);
        } catch (\Exception $e) {
            dLog('exception')->info('login-report-register-fail', [
                'params'        => $params,
                'user'          => $user,
                'exception_msg' => $e->getMessage()
            ]);
        }

        return $this->success($user);
    }

    /**
     * 我的书架
     *
     * @param Request $request
     * @return mixed
     */
    public function shelfBooks(Request $request)
    {
        $data = $request->all();

        $result = $this->userService->getShelfBooks($data);
        return $this->success($result, [new UserTransformer(), 'newBuildUserShelfBooks']);
    }

    /**
     * 添加书架
     *
     * @param Request $request
     * @return mixed
     */
    public function addShelf(Request $request)
    {
        $data = $request->all();

        $result = $this->userService->addShelf($data);
        return $this->success(['success' => $result ? 1 : 0]);
    }

    /**
     * 删除书架
     *
     * @param Request $request
     * @return mixed
     */
    public function deleteShelf(Request $request)
    {
        $data = $request->all();

        $result = $this->userService->batchDeleteShelf($data);
        return $this->success(['success' => $result ? 1 : 0]);
    }

    /**
     * 获取用户阅读记录
     *
     * @param Request $request
     * @return mixed
     */
    public function recentBooks(Request $request)
    {
        $data = $request->all();

        $result = $this->userService->getRecentBooks($data);
        return $this->success(['list' => $result]);
    }

    /**
     * 用户信息
     *
     * @param Request $request
     * @return mixed
     */
    public function userInfo(Request $request)
    {
        $data = $request->all();

        $result = $this->userService->getUserInfo($data);
        return $this->success($result);
    }

    /**
     * 绑定用户
     *
     * @param Request $request
     * @return mixed
     */
    public function bindUser(Request $request)
    {
        $data = $request->all();

        $result = $this->userService->bindUser($data);
        return $this->success(['success' => $result ? 1 : 0]);
    }

    /**
     * 福利页
     *
     * @param Request $request
     * @return mixed
     */
    public function welfare(Request $request)
    {
        $data = $request->all();

        $result = $this->userService->welfare($data);
        return $this->success($result);
    }

    /**
     * 我的收益
     *
     * @param Request $request
     * @return mixed
     */
    public function earnings(Request $request)
    {
        $data = $request->all();

        $result = $this->userService->earnings($data);
        return $this->success($result, [new UserTransformer(), 'newBuildEarnings']);
    }

    /**
     * 提现档位
     *
     * @param Request $request
     * @return mixed
     */
    public function withdrawConfigs(Request $request)
    {
        $data = $request->all();

        $result = $this->userService->withdrawConfigs($data);
        return $this->success($result);
    }

    /**
     * 提现
     *
     * @param Request $request
     * @return mixed
     */
    public function withdraw(Request $request)
    {
        $data      = $request->all();
        $validator = Validator::make($data, [
            'withdraw_type'   => 'required|in:WECHAT,ZHIFUBAO',
            'amount'          => 'required|numeric',
            'alipay_username' => 'required_if:withdraw_type,ZHIFUBAO',
            'alipay_account'  => 'required_if:withdraw_type,ZHIFUBAO',
        ], [
            'withdraw_type.required'      => '请选择提现方式',
            'withdraw_type.in'            => '提现方式不正确',
            'amount.required'             => '请填写提现额度',
            'amount.numeric'              => '提现额度格式不正确',
            'alipay_username.required_if' => '请填写用户名',
            'alipay_account.required_if'  => '请填写手机号或邮箱',
        ]);
        if ($validator->fails()) {
            Utils::throwError('1002:' . $validator->errors()->all()[0]);
        }

        $result = $this->userService->withdraw($data);
        return $this->success(['success' => $result ? 1 : 0]);
    }

    /**
     * 当前阅读
     *
     * @return mixed
     */
    public function currentBook()
    {
        $result = $this->bookService->getCurrentBook();
        return $this->success($result, [new UserTransformer(), 'newBuildCurrentBook']);
    }

    /**
     * 同步用户数据
     *
     * @param Request $request
     * @return mixed
     * @throws ApiException
     */
    public function syncUserInfo(Request $request)
    {
        $iv            = $request->get('iv', '');
        $signature     = $request->get('signature', '');
        $encryptedData = $request->get('encryptedData', '');
        $rawData       = $request->get('rawData', '');
        $userInfo      = $request->get('userInfo', []);
        $result        = $this->userService->syncUserInfo($iv, $signature, $encryptedData, $rawData, $userInfo);
        return $this->success(compact('result'));
    }

    /**
     * 绑定派单链接
     *
     * @param Request $request
     * @return mixed
     */
    public function bindSendOrder(Request $request)
    {
        $data   = $request->all();
        $result = $this->userService->bindSendOrder($data);
        return $this->success(['success' => $result ? 1 : 0]);
    }
}
