<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use App\Notifications\ResetPasswordNotification;

class Member extends Authenticatable
{
    protected $table = 'members';
    protected $fillable = ['phone','name','password','avatar','remember_token','uuid'];
    protected $hidden = ['password','remember_token'];

    /**
     * 上传用户基本信息头像
     *
     * @access public
     * @return String
     */
    public function updateHeader($member_id)
    {
        // 规定上传格式
        $allowedType = ["png", "jpg", "gif"];
        $allowedExtensions = ["image/jpg","image/jpeg","image/png","image/pjpeg","image/gif","image/bmp","image/x-png"];
        // 最大为 100 Kb
        $maxSize = 102400;
        // 获取上传文件
        $img = $_FILES['img'];
        // 获取上传文件格式并转换为小写
        $imgType = strtolower(substr($img['name'],strrpos($img['name'],".") + 1));
        // 判断格式是否符合要求
        if (!in_array($imgType, $allowedType) || !in_array(strtolower($img['type']), $allowedExtensions)) {
            return toJson(-40001);
        }
        if ($img['size'] > $maxSize) {
            return toJson(-40002);
        }
        // 修改文件名
        $imgName = strtotime('now') + rand(10000, 99999);
        $filePath = ROOT_PATH . '/images/header/';
        $imgPath = '/Public/images/header/' . $imgName . ".png";
        if (move_uploaded_file($img['tmp_name'], $filePath . $imgName . ".png")) {
            $oldImg = $this->where('id',$member_id)->select('avatar')->first();
            if(!empty($old_avatar)){
                $old_avatar->toArray();
                // 删除以前的文件
                unlink(ROOT_PATH . $oldImg ->avatar);
            }
            return $imgPath;
        } else {
            return "";
        }
    }

    /*
     * 更改用户信息
     */
    public function editorMemberDetails($member_id,$data){
        $update = $this->where('id',$member_id)->update($data);
        if($update){
            return 1;
        }
        return -20006;
    }


}
