<?xml version="1.0" encoding="UTF-8"?>
<!--
	&author:zwg
	$date:2018/08/21
	$purpose:业务联络函的编辑、发送
-->
<a:screen xmlns:a="http://www.leaf-framework.org/application">
    <a:init-procedure>
        <a:model-query fetchAll="true" model="sys.SYS405.get_zj_sys_mailing_list_id" rootPath="mail_list_id_rp"/>
        <a:model-query fetchAll="true" model="sys.SYS405.exp_employees_mail" rootPath="emp_mail_list"/>
        <a:model-query fetchAll="true" model="sys.SYS405.hls_bp_contact_mail" rootPath="bp_contact_mail_list"/>
    </a:init-procedure>
    <a:view>
        <a:link id="bmLink_send_sms" model="sys.SYS405.sys_mail_list" modelaction="execute"/>
        <a:link id="uploadFile_link" url="${/request/@context_path}/uploadFile.lview"/>
        <a:link id="upload_filename_link" model="sys.SYS405.get_attach_file_name" modelaction="update"/>
        <a:link id="user_prompts_link" model="contact.business_user_prompts" modelaction="query"/>
        <script charset="utf-8" src="${/request/@context_path}/kindeditor/kindeditor-min.js" type="text/javascript"/>
        <script charset="utf-8" src="${/request/@context_path}/kindeditor/lang/zh_CN.js" type="text/javascript"/>
        <script src="${/request/@context_path}/javascripts/hap/hlap-all-hty.js" type="text/javascript"/>
        <script type="text/javascript"><![CDATA[
        var mailEditorList = [];
        var businessApproveWin;


        function lock_window() {
            Leaf.Masker.mask(Ext.getBody(), '正在提交');
        }

        function unlock_window() {
            Leaf.Masker.unmask(Ext.getBody());
        }

        function mailEditorWriteBack(record) {
            var list = mailEditorList;

            for (var i = 0; i < list.length; i++) {
                var value = list[i]['value'].html();
                var name = list[i]['name'];
                record.set(name, value);
            }
        }

        function clearMail() {
            location.reload();
        }

        function saveMail() {
            lock_window();
            var ds = $('mailCreateDs');

            var record = ds.getAt(0);
            if (!record) {
                unlock_window();
                Leaf.showErrorMessage('提示', '请填充内容');
                return;
            }

            // mailEditorWriteBack(record);

            if (Ext.isEmpty(record.get('body'))) {
                Leaf.showMessage('${l:PROMPT}', '邮件正文不能为空!');
                unlock_window();
                return;
            }

            if (!ds.validate()) {
                unlock_window();
                return;
            }

            var data = HapHty.humpObject({
                business_id: record.get('business_id'),
                business_recs: record.get('mail_to_id'),
                business_recs_n: record.get('mail_to'),
                business_ccs: record.get('mail_cc_id'),
                business_ccs_n: record.get('mail_cc'),
                business_subject: record.get('subject'),
                business_text: record.get('body'),
                business_contact_number: record.get('business_contact_number'),
                business_attachment: record.get('attachment_file')
            });
            $jq.ajax({
                url: '${/request/@context_path}/business/contacts/savecontact',
                type: 'post',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(data),
                success: function (datas) {
                    unlock_window();
                    if (datas.success) {
                        Leaf.SideBar.show({
                            msg: '保存成功',
                            duration: 2000
                        });

                        $('mailCreateDs').data[0].set('business_id', datas.rows[0].businessId);
                        $('mailCreateDs').data[0].set('business_status', datas.rows[0].businessStatus);
                        $('mailCreateDs').data[0].set('business_contact_number', datas.rows[0].businessContactNumber);

                    } else {
                        Leaf.showErrorMessage('提示', datas.message);
                    }
                }
            })
        }

        function submitMail() {
            lock_window();
            var ds = $('mailCreateDs');

            var record = ds.getAt(0);

            // mailEditorWriteBack(record);

            if (Ext.isEmpty(record.get('body'))) {
                Leaf.showMessage('${l:PROMPT}', '邮件正文不能为空!');
                unlock_window();
                return;
            }

            if (!ds.validate()) {
                unlock_window();
                return;
            }

            var data = HapHty.humpObject({
                business_id: record.get('business_id'),
                business_recs: record.get('mail_to_id'),
                business_recs_n: record.get('mail_to'),
                business_ccs: record.get('mail_cc_id'),
                business_ccs_n: record.get('mail_cc'),
                business_subject: record.get('subject'),
                business_text: record.get('body'),
                business_contact_number: record.get('business_contact_number'),
                business_attachment: record.get('attachment_file')
            });

            unlock_window();
            // Leaf.showConfirm('${l:HLS.PROMPT}', '是否确认提交邮件?', function() {
            lock_window();
            $jq.ajax({
                url: '${/request/@context_path}/business/contacts/sendnotice',
                method: 'post',
                dataType: "json",
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(data),
                success: function (args) {
                    unlock_window();
                    if (args.success) {
                        Leaf.SideBar.show({
                            msg: '提交成功',
                            duration: 2000
                        });
                        $('mailCreateDs').data[0].set('business_id', args.rows[0].businessId);
                        backMail();
                    } else {
                        Leaf.showErrorMessage('提示', '发送失败' + args.message);
                    }
                    // businessQueryWin.close();
                },
                failure: function () {
                    unlock_window();
                    Leaf.SideBar.show({
                        msg: '提交失败',
                        duration: 2000
                    });
                },
                error: function () {
                    unlock_window();
                    Leaf.SideBar.show({
                        msg: '提交失败',
                        duration: 2000
                    });
                },
                scope: this
            });
            // }, function() {});

        }


        //上传附件
        function attachMail() {
            if (!$('mailCreateDs').data[0] || !$('mailCreateDs').data[0].get('business_id')) {
                Leaf.showErrorMessage('提示', '请先保存!');
                return;
            }
            url = $('uploadFile_link').getUrl() + '?table_name=BUSINESS_CONTACTS&useSubFolder=Y&header_id=' + $('mailCreateDs').data[0].get('business_id');
            var win = new Leaf.Window({
                url: url,
                title: '附件上传',
                id: 'uploadFile_win',
                width: 850,
                height: 400
            });
            win.on('close', function () {
                var record = $('mailCreateDs').getCurrentRecord();
                var mail_list_id = record.get('mail_list_id');
                Leaf.request({
                    url: $('upload_filename_link').getUrl(),
                    para: {
                        mail_list_id: mail_list_id
                    },
                    success: function (args) {
                        var file_name = args.result.file_name;
                        record.set('attachment_file', file_name);
                    }
                });
            });
            if (window === top ||
                ($('mailCreateDs').data[0].get('created_user') != '${/session/@user_id}' &&
                    $('mailCreateDs').data[0].get('created_user')) ||
                $('mailCreateDs').data[0].get('business_status')) {
                win.on('load', function () {
                    $jq('input[type="file"]').hide();
                    $jq('.item-btn-upload').hide();
                    $jq('.up_card .l').hide();
                })
            }
        }

        //审批或驳回
        function approvalMail() {
            lock_window();
            var ds = $('mailCreateDs');
            var record = ds.getAt(0);
            if (!ds.validate()) {
                unlock_window();
                return;
            }
            var businessContactNumber = record.get('businessContactNumber')
            var noticeNumber = record.get('noticeNumber')
            unlock_window();

            businessApproveWin = new Leaf.Window({
                params: {
                    business_id: $('mailCreateDs').data[0].get('business_id')
                },
                url: "${/request/@context_path}/modules/contact/business_contact_approve.lview",
                title: '业务联络函审批',
                width: 800,
                height: 200
            })
        }


        function backMail() {
            location.href = '${/request/@context_path}/modules/contact/business_contact_query.lview?layout_code=BUSINESS_CONCAT&function_code=BIZ100';
        }

        function contact_query_data(ds, qpara) {
            qpara['business_id'] = '${/parameter/@instance_id}' || -1;
        }

        //初始化user_to_ds user_cc_ds
        function init_user_ds() {

            $('user_to_ds').removeAll();
            $('user_cc_ds').removeAll();

            $('user_to_ds').create();
            $('user_cc_ds').create();

            $('user_to_ds').data[0].set('user_ids', ($('mailCreateDs').data[0].get('mail_to_id') || '').split(';'));
            $('user_to_ds').data[0].set('descriptions', ($('mailCreateDs').data[0].get('mail_to') || '').split(';'));

            $('user_cc_ds').data[0].set('user_ids', ($('mailCreateDs').data[0].get('mail_cc_id') || '').split(';'));
            $('user_cc_ds').data[0].set('descriptions', ($('mailCreateDs').data[0].get('mail_cc') || '').split(';'));
        }

        function contact_loader(ds) {
            init_user_ds();
            if ('${/parameter/@instance_id}') {
                users_prompt(ds.data[0].get('mail_to_id'), 'to');
                users_prompt(ds.data[0].get('mail_cc_id'), 'cc');
            }
            if ($('mailCreateDs').data[0].get('business_status')) {
                $jq('#letter_commit').hide();
                $jq('#letter_save').hide();
            }
            if (window === top || $('mailCreateDs').data[0].get('created_user') != '${/session/@user_id}') {

                $jq('#letter_commit').hide();
                $jq('#letter_save').hide();
                // $jq('#letter_approval').show();
                if (window === top) {
                    $jq('#letter_back').hide();
                }
            }
            var business_confirm_user = $('mailCreateDs').data[0].get('business_recs');
            if (business_confirm_user && $('mailCreateDs').data[0].get('business_status') === 'SEND') {
                var users = business_confirm_user.split(';');
                if (users.some(function (value) {
                    return value == '${/session/@user_id}';
                })) {
                    $jq('#letter_approval').show();
                }
            }

        }

        function users_prompt(strs, type) {
            var user_ids = (strs || '').split(';').filter(function (value) {
                return value !== undefined && value !== '';
            }).join(',');
            Leaf.request({
                url: $('user_prompts_link').getUrl(),
                para: {
                    user_ids: user_ids || -1
                },
                scope: this,
                success: function (res) {
                    var results = res.result.record;
                    if (!(results instanceof Array)) {
                        results = new Array(results);
                    }
                    var descriptions = (results || []).map(function (value) {
                        return value && value.description;
                    }).join(';');
                    if (type === 'to') {
                        $('mailCreateDs').data[0].set('mail_to', descriptions);
                    } else {
                        $('mailCreateDs').data[0].set('mail_cc', descriptions);
                    }
                    if (window === top || $('mailCreateDs').data[0].get('created_user') != '${/session/@user_id}') {
                        $('mail_to').initReadOnly(true);
                        $('mail_cc').initReadOnly(true);
                        $('subject').initReadOnly(true);
                        $('body').initReadOnly(true);
                    }
                }
            })
        }

        ]]></script>
        <a:dataSets>
            <a:dataSet id="user_to_ds">
                <a:fields>
                    <a:field name="user_ids"/>
                    <a:field name="descriptions"/>
                </a:fields>
            </a:dataSet>
            <a:dataSet id="user_cc_ds">
                <a:fields>
                    <a:field name="user_ids"/>
                    <a:field name="descriptions"/>
                </a:fields>
            </a:dataSet>
            <a:dataSet id="mailCreateDs" autoCreate="true" model="contact.business_mail" autoQuery="true">
                <a:fields>
                    <a:field name="subject" required="true"/><!-- 必输-->
                    <a:field name="business_contact_number"/>
                    <a:field name="business_id"/>
                    <a:field name="business_status"/>
                    <a:field name="business_recs"/>
                    <a:field name="noticeNumber"/>
                    <a:field name="mail_to_id"/>
                    <a:field name="mail_cc_id"/>
                    <a:field name="created_user"/>
                    <a:field name="mail_to" required="true" lovWidth="500" title="用户"
                             lovUrl="${/request/@context_path}/modules/contact/business_contact_list.lview?type=to">
                        <a:mapping>
                            <a:map from="user_desc" to="mail_to"/>
                            <a:map from="user_id" to="mail_to_id"/>
                        </a:mapping>
                    </a:field>
                    <a:field name="mail_cc" lovWidth="500" title="用户"
                             lovUrl="${/request/@context_path}/modules/contact/business_contact_list.lview?type=cc">
                        <a:mapping>
                            <a:map from="user_desc" to="mail_cc"/>
                            <a:map from="user_id" to="mail_cc_id"/>
                        </a:mapping>
                    </a:field>
                </a:fields>

                <a:events>
                    <a:event name="query" handler="contact_query_data"/>
                    <a:event name="load" handler="contact_loader"/>
                </a:events>
            </a:dataSet>
            <a:dataSet id="empMailDs">
                <a:datas dataSource="/model/emp_mail_list"/>
            </a:dataSet>
            <a:dataSet id="bpContactMailDs">
                <a:datas dataSource="/model/bp_contact_mail_list"/>
            </a:dataSet>
        </a:dataSets>
        <a:screenBody>
            <a:screenTopToolbar>
                <a:screenTitle/>
                <a:gridButton id="letter_back" click="backMail" text="返回"/>
                <!--<a:gridButton id="letter_clear" click="clearMail" text="清空"/>-->
                <a:gridButton id="letter_attach" click="attachMail" text="附件"/>
                <a:gridButton id="letter_save" click="saveMail" text="保存"/>
                <a:gridButton id="letter_commit" click="submitMail" text="发送"/>
                <a:gridButton id="letter_approval" click="approvalMail" text="审批"/>
            </a:screenTopToolbar>
            <a:hBox>
                <a:vBox>
                    <a:form title=" ">
                        <a:textField name="business_contact_number" readOnly="true" bindTarget="mailCreateDs"
                                     prompt="业务联络函编号" width="650"/>
                        <a:lov id="mail_to" name="mail_to" bindTarget="mailCreateDs" height="80" prompt="收件人"
                               width="650"/>
                        <a:lov id="mail_cc" name="mail_cc" bindTarget="mailCreateDs" height="40" prompt="抄送"
                               width="650"/>
                        <a:textField id="subject" name="subject" bindTarget="mailCreateDs" height="40" prompt="主题"
                                     width="654"/>
                        <!--<a:textField name="attachment_file" bindTarget="mailCreateDs" prompt="附件" readOnly="true"
                                     width="654"/>-->
                        <a:textArea id="body" name="body" bindTarget="mailCreateDs" height="270" prompt="正文"
                                    width="650"/>
                    </a:form>
                </a:vBox>
            </a:hBox>
            <script type="text/javascript"><![CDATA[
            Leaf.onReady(function () {
                //隐藏审批
                $jq('#letter_approval').hide();


            });
            ]]></script>
        </a:screenBody>
    </a:view>
</a:screen>