<?php

namespace RuLong\Identity\Traits;

use RuLong\Identity\Models\Identity;
use RuLong\Identity\Models\UserIdentity;
use \RuLong\Identity\Events\IdentityPoint;
use \RuLong\Identity\Events\IdentityUpdate;
use \RuLong\Identity\Models\IdentityPoint as IdentityPointModel;

trait UserHasIdentity
{

    /**
     * 获取身份标题
     * @Author:<C.Jason>
     * @Date:2018-11-09T17:00:39+0800
     * @return [type] [description]
     */
    public function getIdentityTextAttribute()
    {
        return Identity::where('id', $this->identity->identity_id)->value('title') ?: config('rulong_identity.default_identity');
    }

    public function getIdentityIdAttribute()
    {
        return $this->identity->identity_id;
    }

    public function getNameTextAttribute()
    {
        return Identity::where('id', $this->identity->identity_id)->value('name') ?: config('rulong_identity.default_identity');
    }

    public function pointlogs()
    {
        return $this->hasMany(IdentityPointModel::class);
    }

    public function identity()
    {
        return $this->hasOne(UserIdentity::class)->withDefault(['identity_id' => 0]);
    }

    /**
     * User模型涉及函数，辅助快速执行修改身份，
     * [identityUpdate description]
     * @Author:<Leady>
     * @Date:2018-11-07T16:24:44+0800
     * @param [type] $id [身份ID]
     * @return [type] [description]
     */
    public function identityUpdate($id, $channel = 'AutoUp', $other = [])
    {
        $data = ['identity_id' => $id, 'channel' => $channel];
        if (!empty($other)) {
            $data = array_merge($data, $other);
        }
        return IdentityUpdate::start($this, $data);
    }

    /**
     * User模型设计函数，辅助快速增加身份积分。
     * @Author:<Leady>
     * @Date:2018-11-07T16:25:45+0800
     * @param [type] $id [description]
     * @param integer $point [description]
     */
    public function addPoint($id, $point = 1)
    {
        return IdentityPoint::start($this, ['identity_id' => $id, 'point' => $point]);
    }
}
