<?php

namespace App\Dao\User;

use App\Models\User\User;

class UserDao
{
    /**
     * @param $uid
     * @return array
     */
    public function getUserById($uid): array
    {
        if (empty($uid)) {
            return [];
        }

        $result = User::where('id', $uid)->first();
        return $result ? $result->toArray() : [];
    }

    /**
     * 根据openid获取用户数据
     *
     * @param string $openId
     * @return array
     */
    public function getUserByOpenId(string $openId): array
    {
        if (empty($openId)) {
            return [];
        }

        $result = User::where('openid', $openId)->first();
        return $result ? $result->toArray() : [];
    }

    /**
     * 根据openid和unionid获取用户数据
     *
     * @param string $openId
     * @param string $unionId
     * @return array
     */
    public function getUserByOpenIdAndUnionId(string $openId, string $unionId): array
    {
        if (empty($openId) || empty($unionId)) {
            return [];
        }

        $result = User::where('openid', $openId)->where('unionid', $unionId)->first();
        return $result ? $result->toArray() : [];
    }

    /**
     * 根据unionid获取用户数据（多个）
     *
     * @param string $unionId
     * @return array
     */
    public function getUsersByUnionId(string $unionId): array
    {
        if (empty($unionId)) {
            return [];
        }

        $result = User::where('unionid', $unionId)->get();
        return $result ? $result->toArray() : [];
    }

    /**
     * 设置登录用户信息
     *
     * @param $openId
     * @param $unionId
     * @param $data
     * @return mixed
     */
    public function setUser($openId, $unionId, $data)
    {
        return User::updateOrCreate(['openid' => $openId, 'unionid' => $unionId], $data);
    }

    /**
     * @param $data
     * @return mixed
     */
    public function createUser($data)
    {
        return User::create($data);
    }

    /**
     * 更新用户
     *
     * @param $id
     * @param $data
     * @return bool
     */
    public function updateUserById($id, $data): bool
    {
        if (empty($id) || empty($data)) {
            return false;
        }

        return User::where('id', $id)->update($data);
    }
}