var messageUrl ="${(messageUrl)!}";
var lay_index;
var layedit;

var el = {
    form : '#form',
    id : '#id',
    dataPanel : '#dataPanel',
    attachments : '#attachments',
    messageType : '#messageType',
    tbReceiver : '#tb_receiver',
    editIndex: undefined,
    originalRows: [],
    editSupplierIndex: undefined,
    bodyHeight: document.documentElement.clientHeight
};

$(function () {
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.tbReceiver).datagrid('resize', {height: el.bodyHeight - 80});
        },
        onExpand: function () {
            $(el.tbReceiver).datagrid('resize', {height: 260});
        }
    });
    $(el.messageType).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=message_type',
        panelHeight: 'auto',
        limitToList: 'true',
        prompt: '-- 请选择 --',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
    });
    loadReceiverGrid();
});
layui.use(['layedit','form','layer'], function(){
    layedit = layui.layedit;
    var form = layui.form;
    var layer = layui.layer;
    layedit.set({
        height: 150,
        uploadImage: {
            url: '/pc/sys/file/rest/layui/upload/image', //接口url
            type: 'post' //默认post
        }
    });

    lay_index = layedit.build('messageContent');

    window.saveMsg =function(callback){
        layedit.sync(lay_index);
        var title = $("#title").val();
        var sendType = $("#sendType").val();
        var contentModel = $("#contentModel").val();
        var noAnalysis = $("#noAnalysis").val();

        if(title==''){
            layer.alert("标题不能为空", {icon: 2});
            return;
        }
        if(sendType==''){
            layer.alert("类型不能为空", {icon: 2});
            return;
        }
        if(contentModel=='' && noAnalysis==''){
            layer.alert("请选择内容模板或者自定义内容", {icon: 2});
            return;
        }

        $.post(g.ctx + 'send/addOrUpdateAjax', {"parems":JSON.stringify($("#form").serializeJson())}, function (data) {
            layer.alert("操作成功!", {icon: 1},function () {
                callback();
            });
        });
    }


});


/**
 * 加载收信人数据
 */
function loadReceiverGrid() {
    var url = g.ctx + 'pc/message/addressee/rest/list?messageCenterId='+$(el.id).val();
    $(el.tbReceiver).datagrid({
        iconCls: 'icon-list',
        loadMsg: '数据加载中......',
        url: url,
        height: 260,
        pageSize: 2000,
        pageList: [2000, 3000],
        singleSelect: false,
        pagination: true,
        rownumbers: true,
        queryParams: {inquiryId:$(el.id).val()},
        loadFilter: pagerFilter,
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'addresseeName',
                    title: '收件人',
                    width: '33%',
                    align: 'left'
                },
                {
                    field: 'addresseeCode',
                    title: '账号',
                    width: '32%',
                    align: 'center'
               },
                {
                    field: 'addresseeType',
                    title: '用户类型',
                    width: '33%',
                    align: 'center',
                    formatter: function (value) {
                        switch (value) {
                            case 1:
                                return '内部用户';
                            case 2:
                                return '供应商';
                            default:
                                return '';
                        }
                    }
                }
            ]
        ],
        toolbar: [
            {
                text: '选择供应商',
                iconCls: 'icon-add',
                handler: function () {
                    selectUser(2);
                }
            },'-',
            {
                text: '选择内部用户',
                iconCls: 'icon-add',
                handler: function () {
                    selectUser(1);
                }
            },'-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteUser();
                }
            }
        ],
    });
}

/**
 * 选择用户
 * @param type 类型:1-内部；2-供应商
 */
function selectUser(type) {
    var userDialogElement = openDialog("userDialog", g.ctx + "pc/message/launch/userSelect?type="+type, {
        title: type===2?'供应商':'内部用户',
        width: '60%',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userDialogElement.dialog('destroy');
        },
        buttons: [{
            text: '选择',
            iconCls: 'icon-save',
            handler: function () {
                topWin.frames['userDialog'].chooseRow(function (data) {
                    let old_user = $(el.tbReceiver).datagrid('getRows');
                    for (let i = 0; i < data.length; i++) {
                        let user = data[i];
                        if (!user.accountName)
                            continue;

                        let sameFlag = false;
                        for (let j = 0; j < old_user.length; j++) {
                            if (user.accountName === old_user[j].addresseeCode) {
                                sameFlag = true;
                                break;
                            }
                        }
                        if (sameFlag) {
                            continue;
                        }

                        el.originalRows.push({
                            addresseeName: user.username,
                            addresseeCode: user.accountName,
                            addresseeId: user.id,
                            addresseeType: type,
                        })
                        $(el.tbReceiver).datagrid('appendRow', {
                            addresseeName: user.username,
                            addresseeCode: user.accountName,
                            addresseeId: user.id,
                            addresseeType: type,
                        });
                    }
                    userDialogElement.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                userDialogElement.dialog('close');
            }
        }]
    });
}

function deleteUser() {
    let rows = $(el.tbReceiver).datagrid('getSelections');
    if (rows.length === 0) {
        layer.msg('请选中需要删除的数据', {icon: 0});
        return false;
    }
    $.each(rows, function (index, item) {
        el.originalRows = el.originalRows.filter(obj => obj.addresseeCode !== item.addresseeCode);
        let rowIndex = $(el.tbReceiver).datagrid('getRowIndex', item);
        $(el.tbReceiver).datagrid('deleteRow', rowIndex);
    });
}

function pagerFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function')     {   // is array
        data = {
            total: data.length,
            rows: data
        }
    }
    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalRows) {
        data.originalRows = (data.rows);
        el.originalRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalRows.slice(start, end));
    return data;
}


function saveOrUpdate(call){
    if($(el.form).form('validate')){
        layedit.sync(lay_index);
        var formData = $(el.form).serializeJson();
        if (!formData.messageContent){
            layer.msg("请输入公告内容");
            return;
        }
        formData.attachments = $(el.attachments).attr('data-fileIds');

        let receiver = $(el.tbReceiver).datagrid('getRows');
        if (receiver.length <= 0) {
            layer.msg('请选择收信人', {time: 2000});
            return false;
        }
        formData.messageAddressee = receiver;
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/message/launch/rest/saveOrUpdate',
            method: 'post',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function (data) {
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    }
}