<?php

namespace App\Http\Controllers\Home;


use App\Consts\ErrorConst;
use App\Facade\Site;
use App\Libs\ApiResponse;
use App\Libs\Utils;
use App\Models\User\User;
use App\Services\Book\BookService;
use App\Services\User\UserService;
use App\Transformer\Home\HomeTransformer;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Log;

class HomeController extends BaseController
{
    use ApiResponse;
    protected $bookService;
    protected $userService;

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

    /**
     * 首页
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $data = $request->all();
        Log::info('首页入参: '.json_encode($data, 256));
        $gender = getProp($data, 'book_gender');
        $result = [];
        $result['current_book'] = $this->bookService->getCurrentBook();
        $result['book_gender'] = $result['current_book'] ? $result['current_book']['gender'] : 1;
        if ($gender) $result['book_gender'] = $gender;
        $result['banners'] = $this->bookService->getBanners($result['book_gender']);
        $result['feature_books'] = $this->bookService->getFeatureBooks($result['book_gender']);
        $result['favorite_books'] = $this->bookService->getFavoriteBooks($result['book_gender']);

        // 获取分享链接中的隐藏参数(如果存在隐藏参数邀请码则绑定)
        $invite_code = getProp($data, 'invite_code');
        $uid = Site::getUid();
        $from_uid = User::where('invite_code', $invite_code)->value('id');
        if ($from_uid && $uid) {
            $info = $this->userService->bind($from_uid, $uid);  // 绑定邀请码
            Log::info('首页邀请码绑定结果-----from_uid: '.$from_uid.';uid: '.$uid.';info: '.$info);
        }

        // 获取分享链接中的隐藏参数(如果存在隐藏参数派单id则绑定)
        $send_order_id = getProp($data, 'send_order_id');
        $uid = Site::getUid();
        if ($send_order_id && $uid) {
            $info = $this->userService->bindSendOrder($send_order_id);  // 绑定派单链接
            Log::info('首页派单链接绑定结果-----send_order_id: '.$send_order_id.';uid: '.$uid.';info: '.$info);
        }

        return $this->success($result, [new HomeTransformer(), 'newBuildHomeList']);
    }

    /**
     * 抖音投放第三方监测链接
     * @param Request $request
     * @return mixed
     */
    public function listenData(Request $request) {
        $data = $request->all();
        dLog('listen_data')->info('监测链接入参: ', $data);
        return $this->success(['success'=>1]);
    }
}
