<?php

namespace App\Jobs;

use App\Models\Message;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Overtrue\EasySms\PhoneNumber;

class SendEasySms implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $mobile, $data, $area_code;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($mobile, $data, $area_code=86)
    {
        $this->mobile = $mobile;
        $this->data = $data;
        $this->area_code = $area_code;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info("发送短信");
        $err_msg = null;
        $batch_id = "";
        if (empty($this->mobile)) throw new \Exception("发送短信失败，未获取到手机号信息");
        if (config('app.env') == 'production') {
            if(isset($this->data['code'])) {//验证码
                if ($this->area_code == 86) {
                    // $err_msg = $this->send();
                    list($batch_id, $err_msg) = $this->sendMessage();
                }else {
                    list($batch_id, $err_msg)  = $this->sendIntel();
                }
            }else {
                list($batch_id, $err_msg)  = $this->sendMessage();
            }
        }else{
            $this->data['code'] = '999999';
        }
        $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([
            'mobile'=>$this->mobile,
            'code'=>$this->data['code']??0,
            'message'=>$this->data['message'],
            'confirmed'=>0,
            'ip'=> $user_IP,
            'err_msg'=>$err_msg,
            "batch_id"=>$batch_id,
        ]);
    }

    public function sendMessage()
    {
        $batch_id = "";
        try {
            $config = config('easysms');
            $easySms = new EasySms($config);
            $res = $easySms->send($this->mobile, [
                'content' => ($this->data)['message'],
            ],['luosimao']);
            if (isset($res["luosimao"]["result"]["batch_id"])) {
                $batch_id = $res["luosimao"]["result"]["batch_id"];
            }
            $err_msg = null;
        }catch (NoGatewayAvailableException $e) {
            $error_logs = $e->getExceptions();
            $err_msg = $error_logs['luosimao']->getMessage();
        }
        return [$batch_id, $err_msg];
    }

    public function send()
    {
        try {
            $config = config('easysms');
            $easySms = new EasySms($config);
            $easySms->send($this->mobile, [
                'content' => "验证码：".($this->data['code'])."，用于手机绑定，如非本人操作，请忽略本短信！",
                'template' => 'SMS_186360996', // 模板ID
                'data' => [
                    "code" => ($this->data)['code'],
                ],
            ],['aliyun']);
            $err_msg = null;
        }catch (NoGatewayAvailableException $e) {
            $error_logs = $e->getExceptions();
            $err_msg = $error_logs['aliyun']->getMessage();
        }
        return $err_msg;
    }


    public function sendIntel()
    {
        try {
            $config = config('easysms');
            $easySms = new EasySms($config);
            $phone_number = new PhoneNumber($this->mobile, $this->area_code);
            $easySms->send($phone_number, [
                'content' => "验证码：".($this->data['code'])."，用于手机绑定，如非本人操作，请忽略本短信！",
                'template' => 'SMS_463597984', // 模板ID
                'data' => [
                    "code" => ($this->data)['code'],
                ],
            ],['aliyun']);
            $err_msg = null;
        } catch (NoGatewayAvailableException $e) {
            $error_logs = $e->getExceptions();
            $err_msg = $error_logs['aliyun']->getMessage();
        }
        $batch_id = "";
        return [$batch_id, $err_msg];
    }
}
