<?php


namespace Heanup\Library;


class Book
{
    private static $instance;
    private $domain = [
        'index' => "https://scxs.pigqq.com/prov8/base/man2.html",
        'search' => 'https://souxs.pigqq.com/search.aspx?key=%s&page=%d&siteid=%s',
        'image' => 'https://imgapixs.pigqq.com/BookFiles/BookImages/%s',
        'detail' => 'https://infosxs.pigqq.com/BookFiles/Html/%d/%d/info.html',
        'chapter' => 'https://infosxs.pigqq.com/BookFiles/Html/%d/%d/index.html',
        'content_info' => 'https://contentxs.pigqq.com/BookFiles/Html/%d/%d/%d.html',
    ];


    /**
     * 搜索小说
     * @return false|string
     */
    public function getIndexData()
    {
        $url = $this->domain['index'];
        return Curl::get($url);
    }
    /**
     * 搜索小说
     * @param $keyword
     * @param int $page
     * @return false|string
     */
    public function search($keyword, $page = 1)
    {
        $siteid = "app2";
        $url = sprintf($this->domain['search'], urlencode($keyword), $page, $siteid);
        return Curl::get($url);
    }


    /**
     * 获取小说详情
     * @param $book_id
     * @return false|string
     */
    public function getBookDetail($book_id)
    {
        $pre = (int)ceil($book_id / 1000);
        $url = sprintf($this->domain['detail'], $pre, $book_id);
        return Curl::get($url);
    }

    /**
     * 获取章节内容
     * @param $book_id
     * @return false|string
     */
    public function getChapter($book_id)
    {
        $pre = (int)ceil($book_id / 1000);
        $url = sprintf($this->domain['chapter'], $pre, $book_id);
        $result=Curl::get($url);
        $result=str_replace("},]", "}]", $result);
        return $result;
    }

    /**
     * 获取章节内容
     * @param $book_id
     * @param $chapter_id
     * @return false|string
     */
    public function getContent($book_id,$chapter_id){
        $pre = (int)ceil($book_id / 1000);
        $url = sprintf($this->domain['content_info'], $pre, $book_id,$chapter_id);
        return Curl::get($url);
    }

    /**
     * 获取完整图片URL
     * @param $img
     * @return string
     */
    public function getImageUrl($img)
    {
        return $url = sprintf($this->domain['image'], $img);
    }


    public function __construct()
    {
        Curl::get("https://scxs.pigqq.com/prov8/base/initconf.html");//初始化接口配置
    }

    public static function getInstance(): Book
    {
        if (!isset(self::$instance)) {
            $instance = new self();
            self::$instance = $instance;
        } else {
            $instance = self::$instance;
        }
        return $instance;
    }


}