<?xml version="1.0" encoding="UTF-8"?>
<a:service xmlns:a="http://www.leaf-framework.org/application" xmlns:s="leaf.plugin.script" trace="true">
    <a:init-procedure>
        <s:server-script import="contract_print_path.js"><![CDATA[
            importPackage(java.io);
            importPackage(Packages.com.hand.kinggrid);
            importPackage(Packages.hls.plugin.docx4j);
            importPackage(Packages.leaf.plugin.word2pdf);
            importPackage(Packages.org.apache.commons.io);
            importPackage(Packages.hls.plugin.jacob.engine);
            importPackage(Packages.uncertain.proc);
            importPackage(Packages.com.itextpdf.text);
            importPackage(Packages.com.itextpdf.text.pdf);
            importPackage(Packages.java.io);
            importPackage(Packages.java.util);

            function copyFile(fOld, fNew) {
                var fis = new java.io.FileInputStream(fOld);
                var fos = new java.io.FileOutputStream(fNew);
                var b = new java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 1024 * 4);
                var len = -1;
                while ((len = fis.read(b)) != -1) {
                    fos.write(b, 0, len);
                }
                fis.close();
                fos.close();
            }

            //第一步生成合同文本
            $bm('cont.CON620.create_content_for_collection').update({
            contract_id: $ctx.parameter.contract_id,
            templet_code: $ctx.parameter.templet_code
            });
            //获取日期目录
            var datePath = getDate();
            $ctx.parameter.batch_flag='Y';
            FileUtils.forceMkdir(new File(datePath)); //根据日期创建目录

            var from_file_data_map = $bm('cont.CON500.con_doc_file_templet_get_atm_new').queryAsMap({
                contract_id: $ctx.parameter.contract_id,
                batch_flag:$ctx.parameter.batch_flag,
                templet_code: $ctx.parameter.templet_code
            });
            var from_file_data = from_file_data_map.getChildren();
            var sys_file_path_bm=$bm('cont.CON4000.get_sys_url');
            var parameter_code='TEMPORARY_FILES';
            var SysurlQuery = sys_file_path_bm.queryAsMap({
                                    parameter_code: parameter_code
                                });

            var sys_file_path = SysurlQuery.getChildren()[0].parameter_value;
             var now = new Date();
                y = now.getFullYear();
                m = now.getMonth() + 1;
                m = m < 10 ? "0" + m : m;
                d = now.getDate();
                d = d < 10 ? "0" + d : d;
                var to_file_path = (sys_file_path + y + "\/" + m + "\/").toString();
                 FileUtils.forceMkdir(new File(to_file_path)); //根据日期创建目录
            for (var i = 0;i < from_file_data.length;i++) {
                //var to_file_path = (sys_file_path + y + "\/" + m + "\/").toString();
                var record_data = from_file_data[i];

                var to_file_name = record_data.to_file_name;
                var from_file_path = record_data.file_path;
                var guid_file_name_path = $bm('cont.CON500.con_contract_get_guid_file_name').queryAsMap();
                var guid_file_name_tables = guid_file_name_path.getChildren();
                to_file_path = to_file_path + guid_file_name_tables[0].guid_file_name + 'con' + record_data.content_id;
                copyFile(from_file_path, to_file_path);

                $bm('cont.CON500.con_file_content_copy_update').update({
                    table_name: 'CON_CONTRACT_CONTENT',
                    content_id: record_data.content_id,
                    file_name: to_file_name.toString(),
                   file_path: to_file_path.toString()
                });
                //common直接下载原文件
                try {
                    var brwt = new BookmarksReplaceWithText($instance('leaf.database.service.IDatabaseServiceFactory'), $instance('uncertain.ocm.IObjectRegistry'), $ctx.getData());
                    brwt.replaceBookmarkFromContent(to_file_path.toString(), record_data.content_id);
                } catch (e) {
                    raise_app_error(e);
                }
                word_to_pdf_sign(record_data.content_id);

                var file_size=get_file_length(datePath+ guid_file_name_tables[0].guid_file_name + 'con' + record_data.content_id + '.pdf' );
                var download_file = datePath + guid_file_name_tables[0].guid_file_name + 'con' + record_data.content_id + ".pdf";

                var business_daily_email=$bm('cont.CON301N.insert_into_attachment_bmp').update({
                        p_file_path     :(download_file).toString(),
                        p_file_name     :($ctx.parameter.file_name+'.pdf').toString(),
                        p_file_size     :file_size,
                        p_user_id       :$ctx.session.user_id,
                        p_contract_id   :$ctx.parameter.contract_id,
                        p_file_type     :'PDF',
                        p_lease_type    :'02'
                });
                println('download_file' + download_file);
<!--                download_file(datePath + guid_file_name_tables[0].guid_file_name + 'con' + record_data.content_id + '.pdf' ,'催收函.pdf');-->
            }

            function getDate() {
                set_pdf_parameter_file_path();
                var file_path = $ctx.parameter.file_path;
                var now = new Date()
                y = now.getFullYear()
                m = now.getMonth() + 1
                m = m < 10 ? "0" + m : m
                var path = file_path + y + "/" + m + "/";
                return path;
            }
            function get_file_length(path){
                var file=new File(String(path));
                if(file.exists() && file.isFile()){
                    length=file.length();
                    return length;
                }else{
                     return 0 ;
                }
            }

            function word_to_pdf_sign(content_id) {
                importPackage(Packages.com.hl.signatures);
                importPackage(Packages.java.io);
                importPackage(Packages.java.util);
                var attachment_batch_dl = $bm('cont.CON620.con_collection_file_download');
                var attachment_update = $bm('cont.CON620.con_contract_save_pdf_atm');
                var org_flag = '';
                var qf_flag = '';
                var param = new ArrayList();
                var paramdetail;
                var result = attachment_batch_dl.queryAsMap({
                    content_id: content_id
                });
                var arr = result.getChildren();
                for (var i = 0;i < arr.length;i++) {
                    var f = arr[i];
                    var file_name = f.file_name;
                    var file_path = f.file_path;
                    if (file_name.substring(file_name.length - 4) == '.doc') {
                        file_name = file_name.substring(0, file_name.length - 4);
                    } else if (file_name.substring(file_name.length - 5) == '.docx') {
                        file_name = file_name.substring(0, file_name.length - 5);
                    }
                    var outputfilepath = file_path + '.pdf'; // 由于wordToPdf转换后pdf文件已经带有.pdf
                    var wordToPdf = new WordToPdf($instance('uncertain.ocm.IObjectRegistry'), "jacob-1.19-x64.dll");
                    wordToPdf.word2pdf(file_path, outputfilepath);

                    var con_signature_info = $bm('cont.CON620.get_con_signature_info').queryAsMap();
                    var con_signature_data = con_signature_info.getChildren();
                    var con_signature_record;

                    for (var i = 0;i < con_signature_data.length;i++) {

                        con_signature_record = con_signature_data[i];

                        println(con_signature_record.signature_code);
                        if (con_signature_record.signature_code == 'gz_flag'){
                             paramdetail = '[{ "code":"' + con_signature_record.code +
                                    '", "seal_code":"' + con_signature_record.seal_code +
                                    '", "seal_width":' + con_signature_record.seal_width +
                                    ', "fontname":"' + con_signature_record.fontname +
                                    '", "fontsize":"' + con_signature_record.fontsize +
                                    '", "fontcolor":"' + con_signature_record.fontcolor +
                                    '", "pageno":"' + con_signature_record.pageno +
                                    '", "text":"' + con_signature_record.word_code + '"}]';
                        }
                        param.add(paramdetail);
                    }

                    var con_signature_info = $bm('cont.CON620.get_kinggrid_info').queryAsMap();
                    var con_kinggrid_data = con_signature_info.getChildren()[0];
                    var server_url = con_kinggrid_data.server_url;
                    var app_id = con_kinggrid_data.app_id;
                    var app_security = con_kinggrid_data.app_security;
                    var status = new com.hand.kinggrid.ContractSignaturesNew.hl_contract_signatures(outputfilepath, 1,param.toArray(),server_url,app_id,app_security,datePath);
                    println(11111111);
                    attachment_update.update({
                        content_id: content_id,
                        table_name: 'HLS_DOC_FILE_CONTENT'
                    });
                }
            }

            function write_os_to_file(file, os) {
                var fis = new FileInputStream(file);
                var b = new java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 1024 * 64);
                var len = -1;
                while ((len = fis.read(b)) != -1) {
                    os.write(b, 0, len);
                }
                fis.close();
            }

            function download_file(file_path, file_name) {
                $ctx["__request_type__"] = 'file';
                var resp = $ctx['_instance.javax.servlet.http.HttpServletResponse'];
                resp.setHeader("Pragma", "No-cache");
                resp.setHeader("Cache-Control", "no-cache, must-revalidate");
                resp.setHeader("Content-disposition", "attachment; filename=" + encodeURI(file_name, 'utf-8'));
                resp.setDateHeader("Expires", 0);
                resp.setContentType("application/x-msdownload");
                try {
                    var os = resp.getOutputStream();
                    write_os_to_file(file_path, os);

                    os.flush();
                } catch (e) {
                    $logger("server-script").severe(e.message);
                }
            }
        ]]></s:server-script>
    </a:init-procedure>
    <a:service-output/>
</a:service>
