<?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>
        <a:model-query fetchAll="true" model="cont.CON500.con_contract_get_guid_file_name"
                       rootPath="guid_file_name_path"/>
        <!--<a:model-query fetchAll="true" model="cont.CON500.con_doc_file_templet_get_atm" rootPath="file_templet_get_atm_path"/>-->
        <s:server-script import="contract_print_path.js"><![CDATA[
            importPackage(java.io);
            importPackage(Packages.hls.plugin.docx4j);
            importPackage(Packages.leaf.plugin.word2pdf);
            importPackage(Packages.org.apache.commons.io);
            importPackage(Packages.com.hand.elecon.httpost);

            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();
            }
                //删除文件
            function deleteFile(filePath) {
                var file = new File(filePath);
                if (file.exists()) {
                    file.delete();
                }
            }

            //生成pdf
               function wordToPdf(word_file_path,pdf_file_path) {
                // word转pdf
                var pdf_file_path_new = pdf_file_path + '.pdf';
                var wordToPdf = new WordToPdf($instance('uncertain.ocm.IObjectRegistry'), "jacob-1.19-x64.dll");
                wordToPdf.word2pdf(word_file_path, pdf_file_path_new);
                //删除word文件
               // deleteFile(word_file_path);

                return pdf_file_path_new;
            }
            //生成pdf openoffice
            function doc2pdf(word_file_path,pdf_file_path) {
            // word转pdf
            var pdf_file_path_new = pdf_file_path + '.pdf';
            var wordToPdf = new doc2pdf2();

            wordToPdf.doc2pdf2("C:/Program Files (x86)/OpenOffice 4",word_file_path, pdf_file_path_new);
            //删除word文件

            deleteFile(word_file_path);

            return pdf_file_path_new;
            }

            //按日期创建目录
            function getDatePath() {
            set_parameter_file_path();
            var info = info_query('HL_ELE_FILE_PATH');
            var file_path = info.code_value;
            //var file_path = $ctx.parameter.pdf_path; //file_path = c:/hls_test_files/content_files/
            //var file_path = 'd:/hl_test_files/content_files/'; //file_path = c:/hls_test_files/content_files/
            var now = new Date()
            y = now.getFullYear()
            m = now.getMonth() + 1
            m = m < 10 ? "0" + m : m
            var datePath = file_path + y + "/" + m + "/";
            return datePath; //datePath = d:/hls_test_files/fileupload/2018/04/
            }
            //系统参数获取
            function info_query(parameter_code) {
                var info = new Object();
                var data = null;
                var parameter_map = $bm('wx.WX100.sys_parameter_value').queryAsMap({
                    parameter_code:parameter_code
                });
                var data = parameter_map.getChildren();
                info.code_value = data[0].code_value;
                return info;
            }
            var up_file_token_url = info_query('UP_FILE_TOKEN_URL').code_value;

            var flow_count_bm = $bm('wx.WX100.con_ele_flow_update');
            var flow_count_map = flow_count_bm.queryAsMap({
                contract_id: $ctx.parameter.contract_id
            });
            var flow_count_data = flow_count_map.getChildren();
            if(flow_count_data[0].ce_num == 0) {
                //依据合同文本签署人定义存储签署人信息
                var ele_contract_signer_bm = $bm('wx.WX100.con_ele_contract_signer_save');
/*                //第一步生成合同文本
                $bm('cont.CON505.con_ele_contract_create_content').update({
                    contract_id: $ctx.parameter.contract_id,
                    content_type: 'NORMAL'
                });*/
                //组装合同签署人信息报文
                var ele_signer_bm = $bm('wx.WX100.con_ele_contract_signer_query');
                var ele_signer_map = ele_signer_bm.queryAsMap({
                    contract_id: $ctx.parameter.contract_id,
                    esign_type: 'CE'
                });
                var ele_signer_data = ele_signer_map.getChildren();
                var userInfoList = [];
                for (var k = 0; k < ele_signer_data.length; k++) {
                    var signer_record_data = ele_signer_data[k];
                    if (signer_record_data.signer_category == 'TENANT_NP' || signer_record_data.signer_category == 'TENANT_SP' || signer_record_data.signer_category == 'GUARANTOR_NP' || signer_record_data.signer_category == 'GUARANTOR_SP') {
                        userInfoList.push({
                            "idNo": signer_record_data.id_no,
                            "name": signer_record_data.bp_name,
                            "mobile": signer_record_data.mobile,
                            "signerCategory":signer_record_data.signer_category
                        });
                    } else if (signer_record_data.signer_category == 'TENANT_ORG_SEAL') {
                        var ele_org_signer_map = ele_signer_bm.queryAsMap({
                            contract_id: $ctx.parameter.contract_id,
                            signer_category: 'TENANT_ORG_SIGN'
                        });
                        var ele_org_signer_data = ele_org_signer_map.getChildren();
                        //经办人
                        var agentName = ele_org_signer_data[0].bp_name;
                        var agentIdNo = ele_org_signer_data[0].id_no;
                        var mobile = ele_org_signer_data[0].mobile;
                        //法人
                        var legalName = signer_record_data.legal_person;
                        var legalIdNo = signer_record_data.id_card_no_leg;
                        if (agentIdNo == legalIdNo) {
                            userInfoList.push({
                                "idNo": signer_record_data.id_no,
                                "name": signer_record_data.bp_name,
                                "agentIdNo": agentIdNo,
                                "agentName": agentName,
                                "mobile": mobile,
                                "legalName": legalName,
                                "legalIdNo": legalIdNo,
                                "agentType": "1",
                                "signerCategory":signer_record_data.signer_category
                            });
                        } else {
                            userInfoList.push({
                                "idNo": signer_record_data.id_no,
                                "name": signer_record_data.bp_name,
                                "agentIdNo": agentIdNo,
                                "agentName": agentName,
                                "mobile": mobile,
                                "legalName": legalName,
                                "legalIdNo": legalIdNo,
                                "agentType": "2",
                                "signerCategory":signer_record_data.signer_category
                            });
                        }
                    } else if (signer_record_data.signer_category == 'GUARANTOR_ORG_SEAL') {
                        var ele_org_signer_map = ele_signer_bm.queryAsMap({
                            contract_id: $ctx.parameter.contract_id,
                            signer_category: 'GUARANTOR_ORG_SIGN',
                            id_no:signer_record_data.id_card_no_leg
                        });
                        var ele_org_signer_data = ele_org_signer_map.getChildren();
                        var agentName = ele_org_signer_data[0].bp_name;
                        var agentIdNo = ele_org_signer_data[0].id_no;
                        var mobile = ele_org_signer_data[0].mobile;
                        userInfoList.push({
                            "idNo": signer_record_data.id_no,
                            "name": signer_record_data.bp_name,
                            "agentIdNo": agentIdNo,
                            "agentName": agentName,
                            "mobile": mobile,
                            "legalName": agentName,
                            "legalIdNo": agentIdNo,
                            "agentType": "1",
                            "signerCategory":signer_record_data.signer_category
                        });
                    } else if (signer_record_data.signer_category == 'AGENCY_STORE_SEAL') {
                        var ele_org_signer_map = ele_signer_bm.queryAsMap({
                            contract_id: $ctx.parameter.contract_id,
                            signer_category: 'AGENCY_STORE_SIGN'
                        });
                        var ele_org_signer_data = ele_org_signer_map.getChildren();
                        //经办人
                        var agentName = ele_org_signer_data[0].bp_name;
                        var agentIdNo = ele_org_signer_data[0].id_no;
                        var mobile = ele_org_signer_data[0].mobile;
                        //法人
                        var legalName = signer_record_data.legal_person;
                        var legalIdNo = signer_record_data.id_card_no_leg;

                        userInfoList.push({
                            "idNo": signer_record_data.id_no,
                            "name": signer_record_data.bp_name,
                            "agentIdNo": agentIdNo,
                            "agentName": agentName,
                            "mobile": mobile,
                            "legalName": legalName,
                            "legalIdNo": legalIdNo,
                            "agentType": "2",
                            "signerCategory":signer_record_data.signer_category
                        });
                    }
                }
                //获取token信息
                var logs_bm = $bm('wx.WX100.con_ele_savelogs');
                try {
                    var token_sign_result = EleFileUpHttpPost.post(up_file_token_url, null, null);
                } catch (e) {
                    raise_app_error('上传文件获取token失败,请联系技术人员检查!');
                }
                var token_sign_result_ob = JSON.parse(token_sign_result);
                var access_sign_token = token_sign_result_ob.access_token;
                //校验签署人
                var info = info_query('HL_ELE_ACCOUNT_CREATE_PATH');
                var httpUrl = info.code_value;
                var Param = {
                    userInfo: userInfoList
                }
                var result = EleFileUpHttpPost.post(httpUrl, JSON.stringify(Param), access_sign_token);
                //var result = new HttpRequest().sendPost(httpUrl, JSON.stringify(signParam));
                logs_bm.insert({
                    contract_id: $ctx.parameter.contract_id,
                    httpurl: httpUrl,
                    jsonPut: JSON.stringify(Param),
                    jsonResult: result,
                    tokenResult: token_sign_result
                });
                var result_ob = JSON.parse(result); //根据返回参数形式再定
                if (result_ob.code != 0) {
                    //rollback
                    $bm('wx.WX100.rollback').update();
                    raise_app_error(result_ob.message.toString());
                }
                //生成合同文本
                var datePath = getDatePath();
                FileUtils.forceMkdir(new File(datePath)); //根据日期创建目录
                $ctx.parameter.batch_flag = 'Y';
                var from_file_data_map = $bm('cont.CON500.con_doc_file_templet_get_atm').queryAsMap({
                    contract_id: $ctx.parameter.contract_id,
                    batch_flag: $ctx.parameter.batch_flag
                });
                var from_file_data = from_file_data_map.getChildren();
                //所有文件
                var conFileList = [];
                //签署人
                var signer = [];
                for (var i = 0; i < from_file_data.length; i++) {
                    var to_file_path = $ctx.parameter.file_path;
                    var record_data = from_file_data[i];

                        if (record_data.file_exists_flag != 'Y') {
                        var to_file_name = record_data.to_file_name + '.' + record_data.file_type_code || 'doc';
                        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 + '.' + record_data.file_type_code || 'doc';

                        copyFile(from_file_path, to_file_path);

                        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转pdf
                        var pdf_file_path = datePath + guid_file_name_tables[0].guid_file_name + 'con_' + record_data.content_id;
                        var outputfilepath = wordToPdf(to_file_path, pdf_file_path);
                        var outputfilename = record_data.to_file_name + '.pdf';
                        var pdf_file = new File(outputfilepath);
                        var file_size = 0;
                        if (pdf_file.exists()) {
                            file_size = pdf_file.length();
                        }
                        //保存文本名及路径
                        $bm('cont.CON500.con_file_content_copy_update').execute({
                            table_name: 'CON_CONTRACT_CONTENT',
                            content_id: record_data.content_id,
                            file_name: outputfilename.toString(),
                            file_path: outputfilepath.toString(),
                            file_size: file_size,
                            file_type_code: 'pdf',
                            mime_type: 'application/pdf',
                            user_id: $ctx.parameter.user_id
                        });
                    }
                }
                //文件列表
                var con_ele_unsigned_file_bm = $bm('wx.WX100.con_ele_unsigned_file_query');
                var con_ele_unsigned_file_map = con_ele_unsigned_file_bm.queryAsMap({
                    contract_id: $ctx.parameter.contract_id
                });
                var con_ele_unsigned_file_data = con_ele_unsigned_file_map.getChildren();
                for (var n = 0; n < con_ele_unsigned_file_data.length; n++) {
                    conFileList.push({
                        "fileUrl": con_ele_unsigned_file_data[n].file_path.replace('X:','/mnt'),
                        "fileName": con_ele_unsigned_file_data[n].file_name,
                        "fileSize": con_ele_unsigned_file_data[n].file_size
                    });
                }
                var ele_contract_signer_map = ele_contract_signer_bm.queryAsMap({
                    contract_id: $ctx.parameter.contract_id
                });
                var ele_contract_signer_data = ele_contract_signer_map.getChildren();
                var contract_number = ele_contract_signer_data[0].contract_number;
                for (var k = 0; k < ele_contract_signer_data.length; k++) {
                    var signerFileList = [];
                    var signer_record_data = ele_contract_signer_data[k];
                    var con_ele_signer_id = signer_record_data.con_ele_signer_id;
                    var ele_signer_file_bm = $bm('wx.WX100.con_ele_signer_file_query');
                    var ele_signer_file_map = ele_signer_file_bm.queryAsMap({
                        contract_id: $ctx.parameter.contract_id,
                        con_ele_signer_id: con_ele_signer_id
                    });
                    var ele_signer_file_data = ele_signer_file_map.getChildren();
                    if (ele_signer_file_data.length == 0) {continue};
                    for (var h = 0; h < ele_signer_file_data.length; h++) {
                        signerFileList.push({
                            "fileName": ele_signer_file_data[h].file_name,
                            "fileUrl": ele_signer_file_data[h].file_path.replace('X:','/mnt'),
                            "fileSize": ele_signer_file_data[h].file_size
                        });
                    }
                    signer.push({
                        "idNo": signer_record_data.id_no,
                        "idType": signer_record_data.id_type,
                        "accountType": signer_record_data.signer_category,
                        "signOrder": signer_record_data.sign_order,
                        "key": signer_record_data.key_word,
                        "autoExecute": signer_record_data.auto_sign,
                        "signType": signer_record_data.sign_type,
                        "signerFileList": signerFileList
                    })
                }
                //调用中台签署流程
                var info = info_query('HL_SIGN_FLOW_CREATE');
                var httpUrl = info.code_value;
                var signParam = {
                    contractNo: $ctx.parameter.contract_id,
                    contractNumber: contract_number,
                    esignType: "CE",
                    userInfo: userInfoList,
                    conFileList: conFileList,
                    signer: signer
                }
                var result = EleFileUpHttpPost.post(httpUrl, JSON.stringify(signParam), access_sign_token);
                //var result = new HttpRequest().sendPost(httpUrl, JSON.stringify(signParam));
                logs_bm.insert({
                    contract_id: $ctx.parameter.contract_id,
                    httpurl: httpUrl,
                    jsonPut: JSON.stringify(signParam),
                    jsonResult: result,
                    tokenResult: token_sign_result
                });
                var result_ob = JSON.parse(result); //根据返回参数形式再定
                if (result_ob.code != 0) {
                    //rollback
                    $bm('wx.WX100.rollback').update();
                    //raise_app_error('发起签约失败,请联系技术人员检查!');
                    raise_app_error(result_ob.message.toString());
                } else if (result_ob.code == 0) {
                    var flow_id = result_ob.flowId;
                    var flow_update_bm = $bm('wx.WX100.con_ele_flow_update');
                    flow_update_bm.update({
                        contract_id: $ctx.parameter.contract_id,
                        flow_id: flow_id,
                        esign_type: 'CE'
                    })
                    var sign_url_list = result_ob.signUrlList;
                    var ele_con_info_bm = $bm('wx.WX100.con_ele_con_info_update');
                    for (var i = 0; i < sign_url_list.length; i++) {
                        ele_con_info_bm.update({
                            contract_id: $ctx.parameter.contract_id,
                            id_no: sign_url_list[i].idNo,
                            sign_url: sign_url_list[i].signUrl,
                            esign_type: 'CE'
                        })
                    }
                }
            }
            ]]></s:server-script>
    </a:init-procedure>
</a:service>