
const PDFUI = UIExtension.PDFUI;
const Events = UIExtension.PDFViewCtrl.Events;
const pdfui = new PDFUI({
    viewerOptions: {
        libPath: '../../../lib',
        jr: {
            readyWorker: readyWorker
        },
        viewerUI: new class extends UIExtension.XViewerUI {
            createDateTimePicker(format) {
                // 创建并返回一个 IDateTimePicker 实例
                return new CustomDateTimePicker(this, format);
            }
        }
        // customs: {
        //     getDocPermissions: function () {
        //         return 0;
        //     }
        // }
    },
    renderTo: '#pdf-ui',
    appearance: UIExtension.appearances.adaptive,
    addons: UIExtension.PDFViewCtrl.DeviceInfo.isMobile ?
    '../../../lib/uix-addons/allInOne.mobile.js':
    '../../../lib/uix-addons/allInOne.js'
});

pdfui.addUIEventListener('fullscreenchange', function (isFullscreen) {
    if (isFullscreen) {
        document.body.classList.add('fv__pdfui-fullscreen-mode');
    } else {
        document.body.classList.remove('fv__pdfui-fullscreen-mode');
    }
});

function openLoadingLayer() {
    // return pdfui.getRootComponent()
    // .then(function(root) {
    //     return root.getComponentByName('pdf-viewer')
    // }) .then(function(viewerComponent) {
    //     return pdfui.loading(viewerComponent.element);
    // });
    return pdfui.loading();
}
var loadingComponentPromise;
var openFileError = null
var passwordErrorCode = PDFViewCtrl.PDF.constant.Error_Code.password
function startLoading() {
    if(openFileError&&openFileError.error===passwordErrorCode)return
    if (loadingComponentPromise) {
        loadingComponentPromise = loadingComponentPromise
            .then(function (component) {
                component.close();
            })
            .then(openLoadingLayer);
    } else {
        loadingComponentPromise = openLoadingLayer();
    }
}
pdfui.addViewerEventListener(Events.beforeOpenFile, startLoading);
pdfui.addViewerEventListener(Events.openFileSuccess, function () {
    openFileError = null;
    loadingComponentPromise.then(function (component) {
        component.close();
    });
});
pdfui.addViewerEventListener(Events.openFileFailed, function (data) {
    openFileError = data
    if(openFileError&&openFileError.error===passwordErrorCode)return
    loadingComponentPromise.then(function (component) {
        component.close();
    });
});

var queryParaPairs = location.search.slice(1).split('&');
var queryParameters = queryParaPairs.reduce(function(map, pair) {
    var kv = pair.split('=');
    map[kv[0]] = decodeURIComponent(kv[1] || '');
    return map;
}, {});

if(queryParameters.file) {
    var reg = /^.+?\/([^\/]+?)(#[^\?#]*)?(\?.*)*$/;
    var result = reg.exec(queryParameters.file);
    var fileName = result? result[1] : document.title + '.pdf';
    pdfui.openPDFByHttpRangeRequest({
        range: {
            url: queryParameters.file,
        }
    }, { fileName: fileName })
} else if (!('file' in queryParameters)) {
    pdfui.openPDFByHttpRangeRequest({
        range: {
            url: '../../../docs/FoxitPDFSDKforWeb_DemoGuide.pdf',
        }
    }, { fileName: 'FoxitPDFSDKforWeb_DemoGuide.pdf' })
}


//signature handlers
var requestData = function(type, url, responseType, body){
    return new Promise(function(res, rej){
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open(type, url);

        xmlHttp.responseType = responseType || 'arraybuffer';
        var formData = new FormData();
        if (body) {
            for (var key in body) {
                if (body[key] instanceof Blob) {
                    formData.append(key, body[key], key);
                } else {
                    formData.append(key, body[key]);
                }
            }
        }
        xmlHttp.onloadend = function(e) {
            var status = xmlHttp.status;
            if ((status >= 200 && status < 300) || status === 304) {
                res(xmlHttp.response);
            }else{
                rej(new Error('Sign server is not available.'));
            }
        };
        
        xmlHttp.send(body ? formData : null);
    });
};

var workflowService = pdfui.getSignatureWorkflowService();
var engineSignatureService = pdfui.getSignatureService();

engineSignatureService.setVerifyHandler(function (signatureField, plainBuffer, signedData){
    return Promise.all([
        signatureField.getFilter(),
        signatureField.getSubfilter(),
        signatureField.getSigner()
    ]).then((params) => {
        var filter = params[0];
        var subfilter = params[1];
        var signer = params[2];
        return requestData('post', location.origin+'/signature/verify', 'text', {
            filter: filter,
            subfilter: subfilter,
            signer: signer,
            plainContent: new Blob([plainBuffer]),
            signedData: new Blob([signedData])
        });
    })
});
workflowService.addSigningSettings({
    filter: 'Adobe.PPKLite',
    subfilter: 'adbe.pkcs7.sha1',
    flag: 0x100,
    distinguishName: 'e=support@foxitsoftware.cn',
    location: 'FZ',
    reason: 'Test',
    signer: 'web sdk',
    showTime: true,
    sign: function(setting, plainContent) {
        return requestData('post', location.origin+'/signature/digest_and_sign', 'arraybuffer', {
            plain: plainContent
        })
    }
});
// Prevent iPhone from Auto Zoom in Input text fields.
window.onload = function () {
    if(!UIExtension.PDFViewCtrl.DeviceInfo.isIPHONE)return
    var lastTouchEnd = 0;
    document.addEventListener('touchend', function (event) {
    var now = (new Date()).getTime();
    if (now - lastTouchEnd <= 300) {
        event.preventDefault();
    }
    lastTouchEnd = now;
    }, false);
};