var fs = require("fs");
var request = require("request");

var api = "https://www.chandashi.com/aso/getmore.html?genreIds=6014&page=";

//登陆蝉大师后，在http请求的cookie那里把cookie拷贝过来就可以了
var cookieStr = "cds_session_id=4ngh9brjopa3bk7c2h7gah0h40; Hm_lvt_0cb325d7c4fd9303b6185c4f6cf36e36=1528850650,1529417351; Hm_lpvt_0cb325d7c4fd9303b6185c4f6cf36e36=1530517804";
cookieStr = cookieStr.split("; ").join(";");
console.log(cookieStr);

var totalPage = 1;
var result = "";
var template = fs.readFileSync("template.html", "utf8");

fetchPage(0, function(){
    template = template.replace("~~~", result);
    fs.writeFileSync("result.html", template);
    console.log("-------over--------")
})


function fetchPage(page, cb) {
    //发送带cookie的请求
    var requestOption = {
        url: api + page,
        headers: {
            'Cookie': cookieStr
        }
    };
    console.log("获取第" + page + "页")
    request(requestOption, function(err, response, body) {
        if(err || body == "null") {
            if(err) console.log(err);
            else console.log("没有更多结果了")
            if(cb) cb();
            return;
        }
        body = unescape(JSON.parse(body));
        result += body;
        if(++page >= totalPage) {
            if(cb) cb();
        } else {
            setTimeout(function() {
                fetchPage(page, cb);
            }, 100);
        }
    })
}