<?php

namespace App\Console\Commands;

use App\Libs\AliSMS;
use GuzzleHttp\Client;
use Illuminate\Console\Command;

class ZsyAlert extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'zsyalert';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->start();
    }

    private function start(){
        $check_status = $this->check();
        if(!$check_status){
            $this->sendAndSave();
        }
    }

    public function getRes(){
        $c = \GuzzleHttp\Cookie\CookieJar::fromArray(['web_user_auth'=>'eyJpdiI6IjU4V1lLMTQ0N2hSWGhLY0RMNTlJa1E9PSIsInZhbHVlIjoiVUVhbnFJVk9EcFVtQit1SFwvd2NjMmc9PSIsIm1hYyI6ImQyZjc2ODVhZTNlZmJhZjk3NzNhNmQ4YjQ0OWVmY2U1ZTA0ZjRhZTMxYWFmM2JiNDUyMWVmNzM5NjE5ZWM4YWMifQ%3D%3D'],'site20qv9n7g2qgkzyxw.leyuee.com');
        $client = new client(['timeout'=>5,'cookies'=>$c]);
        $url = "https://site20qv9n7g2qgkzyxw.leyuee.com/";
        
        try{
            $result = $client->request('get',$url)->getBody()->getContents();
            return $result;
        }catch (\Exception $e){
            \Log::info($e);
        }
       return null;
    }

    function parseHtml($html){
        $xml = new \DOMDocument();
        try{
            $xml->loadHTML($html);
        }catch (Exception $e){

        }
        $status = $xml->getElementsByTagName('script')->item(6)->nodeValue;
        $options = str_ireplace(['window.options = ',';'],'',$status);
        $res = json_decode($options,true);
        if($res){
            return true;
        }
        return false;
    }

    function check(){
        $res = $this->getRes();
        if(!$res){
            sleep(2);
            $res = $this->getRes();
        }
        if(!$res) return false;

        $status = $this->parseHtml($res);
        if($status){
            return true;
        }
        return false;
    }

    function sendAndSave(){
        $file = '/tmp/wangduyun/last.txt';
        $last = file_get_contents($file);
        //不发
        if($last && (time()-$last)<=1800 ){
            return false;
        }
        $phones = ['18668029091','15868100210','18668420256','15158009976','13858057394'];
        //$phones = ['18668029091'];
        $record = '/tmp/wangduyun/'.date('Y-m-d').'.txt';
        foreach($phones as $phone){
            $sta = AliSMS::send($phone,'site_remind',['site_name'=>'网读云H5']);
            file_put_contents($record,'['.date('Y-m-d H:i:s').'] send:'.$phone.' status is '.$sta."\r\n",FILE_APPEND);
        }
        file_put_contents($file,time());
    }

}