<?php

namespace App\Models;

use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;

/**
 * App\Models\User
 *
 * @property int $id
 * @property string $nickname
 * @property string $avatar
 * @property string $password
 * @property string $email
 * @property string $mobile
 * @property string $open_id
 * @property string $union_id
 * @property int $status
 * @property string|null $email_verified_at
 * @property string|null $remember_token
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
 * @property-read int|null $notifications_count
 * @method static \Illuminate\Database\Eloquent\Builder|User newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|User newQuery()
 * @method static \Illuminate\Database\Query\Builder|User onlyTrashed()
 * @method static \Illuminate\Database\Eloquent\Builder|User query()
 * @method static \Illuminate\Database\Eloquent\Builder|User whereAvatar($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereEmail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereEmailVerifiedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereMobile($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereNickname($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereOpenId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User wherePassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereRememberToken($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereUnionId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|User withTrashed()
 * @method static \Illuminate\Database\Query\Builder|User withoutTrashed()
 * @mixin \Eloquent
 * @property \Illuminate\Support\Carbon|null $deleted_at
 * @property-read \App\Models\UserInfo|null $info
 * @method static \Illuminate\Database\Eloquent\Builder|User whereDeletedAt($value)
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\UserConsumeRecord[] $consumeRecords
 * @property-read int|null $consume_records_count
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\UserRechargeRecord[] $rechargeRecords
 * @property-read int|null $recharge_records_count
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\UserVipRecord[] $vipRecords
 * @property-read int|null $vip_records_count
 * @property int $parent_id 上级推荐用户
 * @property string|null $become_child_at 成为下线时间
 * @property string $income 收入
 * @method static \Illuminate\Database\Eloquent\Builder|User whereBecomeChildAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereIncome($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereParentId($value)
 * @property string $is_share 是否分销
 * @property string $share_qrcode 分享二维码
 * @property string $scene_code 情景CODE
 * @method static \Illuminate\Database\Eloquent\Builder|User whereIsShare($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereSceneCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|User whereShareQrcode($value)
 * @property-read User|null $parent
 * @property string $total_income 收入
 * @method static \Illuminate\Database\Eloquent\Builder|User whereTotalIncome($value)
 * @property string|null $become_share_at 成为分销商时间
 * @method static \Illuminate\Database\Eloquent\Builder|User whereBecomeShareAt($value)
 * @property-read User|null $child
 * @property-read \App\Models\UserShare|null $childOrder
 */
class User extends Authenticatable implements JWTSubject
{
    use Notifiable,HasDateTimeFormatter;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'nickname',
        'email',
        'password'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'updated_at',
        'deleted_at',
    ];

    protected $casts = [
        'total_income' => 'decimal:2',
        'income' => 'decimal:2'
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey(); // TODO: Implement getJWTIdentifier() method.
    }

    public function getJWTCustomClaims()
    {
        return [
            'role' => 'user'
        ];  // TODO: Implement getJWTCustomClaims() method.
    }

    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }


    /**
     * 设置密码加密
     * @param $value
     * @return string
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }


    public function parent()
    {
        return $this->belongsTo(User::class,'parent_id');
    }

    public function child()
    {
        return $this->belongsTo(User::class,'id', 'parent_id');
    }

    public function childOrder()
    {
        return $this->hasMany(UserShare::class,'child_id', 'id');
    }

    public function info()
    {
        return $this->belongsTo(UserInfo::class,'id','user_id');
    }

    public function consumeRecords()
    {
        return $this->hasMany(UserConsumeRecord::class,'user_id','id');
    }

    public function rechargeRecords()
    {
        return $this->hasMany(UserRechargeRecord::class,'user_id','id');
    }

    public function vipRecords()
    {
        return $this->hasMany(UserVipRecord::class,'user_id','id');
    }

    public function beComeShare($id)
    {
        $user = self::find($id);
        if(!$user->is_share){
            $config = ShareConfig::first();
            $isBecome = false;
            if($config->become_type == 1) {// 无条件
                $isBecome = true;
            }else if($config->become_type == 2){ // 成为对应的会员
                $vipRecords = UserVipRecord::where('combo_id' , $config->become_vip_id)
                    ->where('user_id', $user->id)
                    ->where('status', 1)
                    ->count();
                if($vipRecords){
                    $isBecome = true;
                }
            }else{ // 充值一定金币
                $RechargeGold = UserRechargeRecord::where('user_id', $user->id)
                    ->where('status', 1)
                    ->sum('gold');
                if($RechargeGold >= $config->become_gold){
                    $isBecome = true;
                }
            }

            if($isBecome){
                $user->is_share = 1;
                $user->become_share_at = Carbon::now()->toDateTimeString();
                $user->save();
            }
        }
    }
}
