<?php

namespace App\Services\Goodnight;

use App\Models\Goodnight\SubscribeModel;
use App\Models\Goodnight\UserModel;
use App\Services\Service;

/**
 * Class UserService
 * @package App\Services\Goodnight
 */
class UserService extends Service
{
    /**
     * 获取用户信息
     * @param  \App\Models\User\UserModel  $user
     */
    public function getUser(&$user)
    {
        $guser = UserModel::firstOrCreate(['uid' => $user->uid]);
        UserModel::where('uid', $guser->uid)->update(['login_at' => time()]);
        $user->like_sex = $guser->like_sex ?? 0;
        $user->cover = $guser->cover ?? "";
        $user->gnight_coin = $guser->gnight_coin ?? 0;
        $user->like_tone_1 = $guser->like_tone_1 ?? "";
        $user->like_tone_2 = $guser->like_tone_2 ?? "";
        $user->like_tone_3 = $guser->like_tone_3 ?? "";
        $user->subscribed_at = $guser->subscribed_at ?? 0;
        $user->get_like = $guser->get_like ?? 0;
        $user->voice = $guser->voice ?? "";
        $user->get_like_headimgurl = json_decode(
            empty($guser->get_like_headimgurl) ? json_encode([]) : $guser->get_like_headimgurl,
            true
        );
        $user->today_fish_cnt = 10 - SubscribeModel::where([
                ['uid', $user->uid],
                ['type', 2],
            ])->whereBetween('created_at', [mktime(0, 0, 0), mktime(0, 0, 0) + 86400])->count();
    }

    /**
     * 更新用户配置
     * @param $user
     * @param  array  $data
     * @return bool
     */
    public function updateUser(&$user, array $data)
    {
        $guser = UserModel::firstOrCreate(['uid' => $user->uid]);
        isset($data['cover']) && $guser->cover = $data['cover'];
        isset($data['like_sex']) && $guser->like_sex = $data['like_sex'];
        isset($data['like_tone_1']) && $guser->like_tone_1 = $data['like_tone_1'];
        isset($data['like_tone_2']) && $guser->like_tone_2 = $data['like_tone_2'];
        isset($data['like_tone_3']) && $guser->like_tone_3 = $data['like_tone_3'];
        isset($data['voice']) && $guser->voice = $data['voice'];
        if ($guser->save()) {
            $user->like_sex = $guser->like_sex;
            $user->cover = $guser->cover;
            $user->like_tone_1 = $guser->like_tone_1;
            $user->like_tone_2 = $guser->like_tone_2;
            $user->like_tone_3 = $guser->like_tone_3;
            $user->subscribed_at = $guser->subscribed_at;
            $user->voice = $guser->voice;

            return true;
        } else {
            return false;
        }
    }
}
