<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/13
 * Time: 9:53
 */
namespace Modules\Base\Services;

use Modules\Base\Entities\File;
use Modules\Base\Entities\Openid;
use Modules\Base\Entities\User;

class UserService extends BaseService
{
    public function __construct(User $user)
    {
        $this->model = $user;
    }

    public function update($id, $data)
    {
        if (isset($data['file_id']) && $file = File::find($data['file_id'])) {
            $data['avatar'] = $file['path'];
        }

        if (isset($data['password'])) {
            $data['password'] = \Hash::make($data['password']);
        }

        return parent::update($id, $data); // TODO: Change the autogenerated stub
    }

    /**
     * 根据OPENID获取用户
     *
     * @param $type
     * @param $openid
     * @param array     $data
     * @param User|null $assocUser
     *
     * @return User
     */
    public function openUser($type, $openid, $data = [], $openid_data = [], User $assocUser = null)
    {
        $openUser = Openid::firstOrNew(['type' => $type, 'openid' => $openid]);
        $create =false;
        if (!$openUser->user_id) {
            if (!$assocUser) {
                $data = ['password' => 'temp', 'ext' => ['type' => $type, 'openid' => $openid]] + $data;
                $data['password'] = \Hash::make($data['password']);
                $assocUser = $this->model->create($data);
            }
            $create = true;
            $openUser->user_id = $assocUser->id;
            $openUser->extra = $data + $openid_data;
            $openUser->save();
        }

        if (!$create && !empty($openid_data)) {
            $openUser->extra = array_merge((array) $openUser->extra , (array) $openid_data);
            $openUser->save();
        }

        return $openUser->user;
    }
}
