// var system = require('system');
var fs = require('fs');
function replaceIllegal(str) {
    console.log("replace->", str);
    if(str){
      string = str.replace('\\','');
      string = string.replace('\?','');
      string = string.replace('\*','');
      string = string.replace('\&','');
      string = string.replace('|','');
      string = string.replace(' ','');
    }
    console.log("to->", string);
    return string
}
  
function trans2pdf(queryString) {
    var url = queryString ? queryString.split('url=')[1] : '';
    if (url == '') return;

    var page = require('webpage').create();
    // var templatePath = "https://www.baidu.com";
    var width = 2048;
    var height = 1400;
    page.viewportSize = {
        width: width,
        height: height
    };
    page.paperSize = {
        format: 'A3', //A4 纸张 21*29.7cm
        // width:"1024px",
        // height:"768px",
        orientation: 'portrait',
        // margin: '0.84cm'
    };

    page.zoomFactor = 0.5;//放大比例
    page.settings.loadImages = true;
    
    page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36';

    page.open(url, function (status) {
        if (status == 'success') {
            console.log('load html ' + url + ' success');
            window.setTimeout(function () {
                var filename = 'export/'+replaceIllegal(page.title.length > 8 ? page.title.substring(0, 8): page.title) + new Date().getTime();
                page.render(filename + '.pdf~', {format: 'pdf', quality: '100'});
                fs.move(filename + '.pdf~', filename + '.pdf');
                console.log('create ' + filename + '.pdf' + ' success');
                page.close();
            }, 1000);

        } else {
            page.close();
            console.log('faild');
        }
    });
}

var webserver = require('webserver');
var server = webserver.create();
var port = 8080;
var service = server.listen(port, function(request, response) {
    var cmd = (request.url + '?').split('?')[0];
    var queryString = request.url.substring(cmd.length);
    switch (cmd) {
        case "/trans2pdf":
            trans2pdf(queryString);
            break;
        default:
            break;
    }

  response.statusCode = 200;
  response.write('<html><body>cmd-->' + cmd + '  params-->' + queryString + '</body></html>');
  console.log("request", JSON.stringify(request));
  response.close();
});

if (service) {
    console.log('Web server running on port ' + port);
} else {
    console.log('Error: Could not create web server listening on port ' + port);
    phantom.exit();
}