<?php

namespace RuLong\Identity\Events;

use RuLong\Identity\Contracts\IdentityContracts;
use RuLong\Identity\Models\IdentityLog as IdentityLogModel;
use RuLong\Identity\Models\UserIdentity as UserIdentityModel;
use RuLong\Identity\Traits\Identityable;

class IdentityUpdate implements IdentityContracts
{
    use Identityable;

    public $user;
    public $identity_id;
    public $channel;
    public $other;
    public function __construct($user, array $other = null)
    {
        $this->user        = $user;
        $this->identity_id = $other['identity_id'];
        $this->channel     = $other['channel'] ?? '';
        $this->other       = $other;
    }

    /**
     * 创建及修改身份
     * @Author:<Leady>
     * @Date:2018-11-05T13:21:47+0800
     * @return [type] [description]
     */
    public function fire()
    {
        $before = 0;

        $identity_info = UserIdentityModel::where('user_id', $this->user->id)->first();
        if ($identity_info) {
            $before                     = $identity_info->identity_id;
            $identity_info->identity_id = $this->identity_id;
            $identity_info->save();
        } else {
            $data = [
                'user_id'     => $this->user->id,
                'identity_id' => $this->identity_id,
            ];
            UserIdentityModel::create($data);
        }
        $log = IdentityLogModel::create(['user_id' => $this->user->id, 'before' => $before, 'after' => $this->identity_id, 'channel' => $this->channel, 'other' => $this->other]);
    }

}
