<?php

namespace App\Mail;

use App\Facades\CommonService;
use App\Models\EmailMessage;
use App\Models\Message;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class SendEmailCode extends Mailable
{
    use Queueable, SerializesModels;

    protected $email;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($email)
    {
        $this->email = $email;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $code = CommonService::random(6,1);
        $message = "您的验证码：$code, 十分钟有效【友福同享】";
        $user_IP = (isset($_SERVER["HTTP_VIA"]) &&  $_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : ($_SERVER["REMOTE_ADDR"]??null);
        $user_IP = ($user_IP) ?: ($_SERVER["REMOTE_ADDR"]??null);
        Message::create(['email'=>$this->email, 'mobile'=>'', 'message'=>$message, 'code'=>$code, 'confirmed'=>0, 'ip'=>$user_IP]);
        $data = [
            'message'=>$message,
            'title'=>"验证码",
        ];
        return $this->subject($data['title'])
            ->to($this->email)->view('email.text',compact('data'));
    }
}
