<?php


namespace Heanup\Library\Sms;


use Heanup\App\Api\Config\Code;
use Heanup\App\Api\Package\Database\Num;
use Heanup\Config\Proxy;
use Heanup\Library\Curl;
use QL\QueryList;

class ReceiveSmsFree implements Sms
{


    /**
     * @return string[]
     */
    public function getCountry(): array
    {
        $data = [];
        for ($i = 1; $i <= 3; $i++) {
            $url = "https://receive-sms-free.net/regions/" . $i . ".html";
            $ql = (new QueryList)->get($url);
            $range = "#ul> .wow";
            $rules = [
                'country' => ["h2", "text"],
                'link' => ["a", "href"]
            ];
            $_data = $ql->range($range)->rules($rules)->query()->getData()->all();
            if ($_data) {
                $data = array_merge($data, $_data);
            }
        }
        $data = array_map(function ($item) {
            $item['country'] = trim($item['country']);
            return $item;
        }, $data);
        return $data;
    }

    /**
     * @param $link
     * @return array
     */
    public function getPhoneNums($link): array
    {
        $ql = (new QueryList)->get($link);
        $end_page_link = $ql->find(".pagination  a:contains(End)")->attr("href");
        preg_match("#\d+#", $end_page_link, $all_page);
        $all_page = $all_page[0];
        $data = $ql->find(".h2 span")->texts()->all();
        $this->insert($link, $data);
        if ($all_page > 0) {
            for ($i = 2; $i <= $all_page; $i++) {
                $url = sprintf($link . "%s.html", $i);
                $_ql = (new QueryList)->get($url);
                $_data = $_ql->find(".h2 span")->texts()->all();
                if ($_data) {
                    $this->insert($link, $_data);
                    $data = array_merge($data, $_data);
                } else {
                    echo "总页数：" . $all_page;
                    echo "处理异常: " . $url . PHP_EOL;
                }
            }
        }
        return $data;
    }

    public function getMessage($country, $phone_num): array
    {
        $info = Num::getOne(['country' => $country, 'phone' => $phone_num]);
        if ($info) {
            $response = Curl::get($info['url'],Proxy::getData());
            $off_line=substr_count($response, "Offline")>0;
            if ($off_line){
                Num::update(['status' => 0], ['id'=>$info['id']]);
            }
            $ql = (new QueryList)->setHtml($response);
            $range = ".row:gt(0)";
            $rules = [
                'from' => [".col-xs-12  > .mobile_hide", "text"],
                'time' => [".col-xs-0", "text"],
                'message' => [".col-md-8", "text"]
            ];
            $ql->find(".mobile_hide:contains(ADS)")->parent()->parent()->remove();
            $msgs = $ql->range($range)->rules($rules)->query()->getData()->all();
            return $msgs;
        }
    }

    private function insert($link, $data)
    {
        foreach ($data as $val) {
            echo sprintf("正在写入号码：\t\t %s", $val) . PHP_EOL;
            $num = explode(" ", $val);
            $_num = str_replace(['+', ' '], ['', ''], $val);
            $config=Code::getData($num[0]);
            $insert = [
                'country' => $num[0],
                'country_name_zh' => $config['cn'],
                'country_name_en' => $config['en'],
                'phone' => $num[1],
                'site' => 'receive-sms-free.net',
                'url' => $link . $_num . "/"
            ];
            Num::insert($insert);
        }
    }
}