<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Core\Auth;
use App\Jobs\MockThumbJob;
use App\Jobs\WelcomeJob;
use App\Models\PartnerModel;
use App\Models\User\AuthKey;
use App\Models\User\MockThumbModel;
use App\Models\User\OpenidUserModel;
use App\Models\User\UserModel;
use App\Services\Home\FeedService;
use App\Services\User\OpenidUserService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Exceptions\JWTException;

/**
 * Class OpenidUserController
 * @package App\Http\Controllers\User
 */
class OpenidUserController extends Controller
{
    /**
     * 更新用户信息
     * @param  Request  $request
     * @return array
     */
    public function update(Request $request)
    {
        $this->validate($request, ['openid' => 'required']);
        $openid = $request->get('openid', null);
        $data = $request->post();
        $ous = new OpenidUserService();
        $ous->update($openid, $data);
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 获取用户信息
     * @param  Request  $request
     * @return array
     */
    public function get(Request $request)
    {
        $this->validate($request, ['openid' => 'required']);
        $openid = $request->get('openid', null);
        $ous = new OpenidUserService();
        $data = $ous->get($openid);
        MockThumbJob::dispatch($openid)->delay(Carbon::now()->addHours(1));
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $data
        );
    }

    /**
     * 用户信息流
     * @param  Request  $request
     * @param  FeedService  $fs
     * @return array
     */
    public function feed(Request $request, FeedService $fs)
    {
        $this->validate($request, ['openid' => 'required']);
        $openid = $request->get('openid', null);

        /** @var OpenidUserModel $openuser */
        $openuser = OpenidUserModel::where('openid', $openid)->firstOrFail();

        // 滑动的性别
        if (in_array($openuser->feed_sex, [1, 2])) {
            $sxo = $openuser->feed_sex;
        } else {
            $sxo = 2;
        }

        $data = $openuser->toArray();
        $data['uid'] = $openuser->openid;
        $data['partner_id'] = 0;
        $data['feed_level'] = 'A';
        $data['only_last'] = 0;

        $res = $fs->feed($data, $sxo);

        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $res
        );
    }

    /**
     * 同步openid信息
     * @param  Request  $request
     * @return array
     */
    public function sync(Request $request)
    {
        $this->validate($request, ['openid' => 'required']);
        try {
            $openid = $request->get('openid', null);
            $uid = Auth::auth();
            $opendata = OpenidUserModel::where('openid', $openid)->firstOrFail();
            $user = UserModel::findOrFail($uid);
            empty($user->age) && $user->age = $opendata->age;
            0 == $user->sex && $user->sex = $opendata->sex;
            if (!UserModel::where('phone', $opendata->phone)->exists() && empty($user->phone)) {
                $user->phone = $opendata->phone;
            }
            $user->save();
            $opendata->sync_at = time();
            $opendata->save();
        } catch (\Exception $exception) {
        }
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 发送欢迎语
     * @param  Request  $request
     * @return array
     * @throws \Exception
     */
    public function welcome(Request $request)
    {
        $this->validate($request, ['openid' => 'required']);
        $openid = $request->get('openid', null);

        WelcomeJob::dispatch($openid)->delay(Carbon::now()->addHours(1));
        Redis::sadd("fpdx:welcome:inqueue:openids", $openid);

        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 喜欢我的
     * @param  Request  $request
     * @return array
     */
    public function likeme(Request $request)
    {
        $openid = $request->get('openid', null);

        $where = array();

        try {
            $uid = Auth::auth();
            $openid = AuthKey::where([
                ['uid', $uid],
                ['auth_type', config('miniprogram.public_id')]
            ])->value('auth_key');
        } catch (JWTException $exception) {
            $uid = null;
        }

        !is_null($openid) && array_push($where, $openid);
        !is_null($uid) && array_push($where, (string)$uid);

        $datas = array();
        try {
            /** @var MockThumbModel[] $mocks */
            $mocks = MockThumbModel::whereIn('thumb_user', $where)->distinct()->get();
            foreach ($mocks as $mock) {
                /** @var PartnerModel $partner */
                $partner = PartnerModel::where('uid', $mock->uid)->firstOrFail();
                $datas[] = array(
                    'lock' => 0,
                    'read' => 1,
                    'praise_id' => 0,
                    'id' => $partner->id,
                    'uid' => $partner->uid,
                    'photo_src' => empty($partner->photo_src) ? "" : "http://oss.pocketuniversity.cn{$partner->photo_src}",
                    'voice' => $partner->voice,
                    'photo_1' => empty($partner->photo_1) ? "" : "http://oss.pocketuniversity.cn{$partner->photo_1}",
                    'photo_2' => empty($partner->photo_2) ? "" : "http://oss.pocketuniversity.cn{$partner->photo_2}",
                    'photo_3' => empty($partner->photo_3) ? "" : "http://oss.pocketuniversity.cn{$partner->photo_3}",
                    'photo_4' => empty($partner->photo_4) ? "" : "http://oss.pocketuniversity.cn{$partner->photo_4}",
                    'praises' => $partner->praises,
                    'updated_at' => $mock->created_at->timestamp,
                    'user' => UserModel::find($mock->uid),
                );
            }
        } catch (\Exception $exception) {
        }

        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'list' => $datas,
            ]
        );
    }
}
