<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Traits\ModelTimeFormat;
use Illuminate\Support\Facades\Cache;

use App\Traits\ModelLogChanging;

class UserDetail extends Model
{
    use ModelLogChanging;

    use ModelTimeFormat;
    protected $primaryKey='user_id';
    public $incrementing=false;

    protected $fillable=[
        'user_id','full_name','gender','identity_number','mobile_phone','type','procurement_wechat_open_id'
    ];
    protected $appends=[
        'user_labor_company'
    ];

    public function user(){
        return $this->belongsTo('App\User','user_id','id');
    }
    public function userLabor(){
        return $this->belongsTo('App\UserLabor','user_id','user_id');
    }
    public function userDutyChecks(){
        return $this->hasMany('App\UserDutyCheck','user_id','user_id');
    }
    public function updateUserName(){
        if ($this['mobile_phone']==$this['user']['name'])
            $this['user']->update(['name'=>$this['full_name']]);
    }

    public function getUserLaborCompanyAttribute()
    {
        $laborCompanyId=$this['userLabor']['labor_company_id']??0;
        $laborCompany=LaborCompany::find($laborCompanyId);
        return $this['user_labor_company']=$laborCompany['name'];
    }
    public function getDutyCheckToken($expireTime)
    {
        if(!$expireTime){
            $expireTime=config('users.token_check_in_expire_minutes');
        }
        $token=Cache::get('dutyCheckTokenUser_'.$this['user_id']);
        if($token){
            Cache::put('dutyCheckTokenUser_'.$this['user_id'],$token,$expireTime);
            Cache::put('dutyCheckTokenStr_'.$token,$this['user_id'],$expireTime);
            return $token;
        }
        $token=md5(rand(1,intval(microtime(true)*10000)).'baoshi');
        Cache::put('dutyCheckTokenUser_'.$this['user_id'],$token,$expireTime);
        Cache::put('dutyCheckTokenStr_'.$token,$this['user_id'],$expireTime);
        return $token;
    }

    public function hasDutyCheckToken()
    {
        return Cache::has('dutyCheckTokenUser_'.$this['user_id']);
    }
    public function markDutyCheckToken()
    {
    }


}
