/**
 * 短信发送记录管理初始化
 */
var MessageRecord = {
    id: "MessageRecordTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
MessageRecord.initColumn = function () {
    return [
        {field: 'selectItem', radio: true},
            {title: '发送对象', field: 'type', visible: true, align: 'center', valign: 'middle',width:80,
                formatter(value,row,index){
                    if(value==1){
                        return "管理员";
                    }
                    if(value==2){
                        return "用户";
                    }
                }
            },
            {title: '用户姓名', field: 'name', visible: true, align: 'center', valign: 'middle',width:100,'class': 'uitd_showTip'},
            {title: '手机号码', field: 'phone', visible: true, align: 'center', valign: 'middle',width:120,'class': 'uitd_showTip'},
            {title: '发送参数', field: 'params', visible: true, align: 'center', valign: 'middle',width:140,'class': 'uitd_showTip'},
            {title: '短信模板', field: 'templateCode', visible: true, align: 'center', valign: 'middle',width:120,'class': 'uitd_showTip'},
            {title: '发送状态', field: 'state', visible: true, align: 'center', valign: 'middle',width:100,
                formatter(value,row,index){
                    if(value==1){
                        return "等待回执";
                    }
                    if(value==2){
                        return "发送失败";
                    }
                    if(value==3){
                        return "发送成功";
                    }
                }
            },
            {title: '发送状态说明', field: 'msg', visible: true, align: 'center', valign: 'middle',width:150,'class': 'uitd_showTip'},
            {title: '发送日期', field: 'sendingDate', visible: true, align: 'center', valign: 'middle',width:120,'class': 'uitd_showTip'},
    ];
};

/**
 * 检查是否选中
 */
MessageRecord.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if(selected.length == 0){
        Feng.info("请先选中表格中的某一记录！");
        return false;
    }else{
        MessageRecord.seItem = selected[0];
        return true;
    }
};

/**
 * 发送自定义短信
 */
MessageRecord.showSendMessageModal = function(){
    layer.open({
        type: 1,
        id: "neewFieldFormModel",
        title: '发送短信',
        area: ['800px', '450px'], //宽高
        fix: false, //不固定
        shade: 0,
        maxmin: true,
        content: MessageRecord.createSendMessageHtml(),
        btn: ['<i class="fa fa-envelope"></i>&nbsp;&nbsp;发送', '<i class="fa fa-eraser"></i>&nbsp;&nbsp;关闭'],
        btnAlign: 'c',
        zIndex: layer.zIndex,
        yes: function (index, layero) {
            var title = $("#title").val();
            var content = $("#content").val();
            var phones = $("#phones").val();
            if(title == null || title == ''){
                Feng.info("请填写短信主题");
                return;
            }
            if(content == null || content == ''){
                Feng.info("请填写短信内容");
                return ;
            }
            if(phones == null || phones == ''){
                Feng.info("填写手机号码");
                return ;
            }
            var operation = function(){
                var ajax = new $ax(Feng.ctxPath + "/admin/message_record/sendMessage", function (data) {
                    if(data.code==200){
                        Feng.success(data.msg);
                        layer.close(index);
                    }else{
                        Feng.error(data.msg);
                    }
                }, function (data) {
                    Feng.error("发送短信失败!" + data.responseJSON.message + "!");
                });
                ajax.setData({"content":content,"params":phones,"title":title});
                ajax.start();
            }
            Feng.confirm("请确认短信内容和发送对象，确定发送吗?", operation);
        }
    });
}

MessageRecord.createSendMessageHtml = function(){
    return  '<form id="firstCheckForm">\n' +
            '    <div class="form-group" style="margin: 10px;">\n' +
            '       <label for="checkState" class="control-label">短信主题</label>\n' +
            '       <input class="form-control" id="title" placeholder="作为短信发送内容的标识,建议不超过8个字符" />\n' +
            '    </div>\n' +
            '    <div class="form-group" style="margin: 10px;">\n' +
            '       <label for="checkState" class="control-label">短信内容</label>\n' +
            '       <textarea class="form-control" id="content" maxlength="1000" placeholder="长度不能超过1000个字符,不能存在敏感字符，否则可能发送不成功" rows="4"></textarea>\n' +
            '    </div>\n' +
            '    <div class="form-group" style="margin: 10px;">\n' +
            '       <label for="" class="control-label">手机号码</label>\n' +
            '       <textarea class="form-control" id="phones"  placeholder="多个手机号以英文逗号隔开，此处输入完成后，点击框下方可现实手机号码个数" rows="4" onchange="MessageRecord.countD(this)"></textarea>\n' +
            '    </div>\n' +
            ' </form>';
}

MessageRecord.countD = function(content){
    var phones =  $(content).val();
    var count = 0;
    var result = phones.match(/,/g)
    var size = (result || []).length;
    if((size+1)>1000){
        Feng.error("已超过1000个手机号码！！")
        $("#phones").val("");
    }
    Feng.info("本次共计"+(size+1)+"个手机号");
}

/**
 * 重新发送短信
 */
MessageRecord.resendMessage = function(){
    if (this.check()) {
        if(MessageRecord.seItem.state!=2){
            Feng.info("当前记录未发送失败，无法重发");
            return ;
        }
        var ajax = new $ax(Feng.ctxPath + "/admin/message_record/resendMessage", function (data) {
            if(data.code==200){
                Feng.success(data.msg);
                MessageRecord.table.refresh();
            }else{
                Feng.error(data.msg);
            }
        }, function (data) {
            Feng.error("发送短信失败!" + data.responseJSON.message + "!");
        });
        ajax.set("messageRecordId",MessageRecord.seItem.id);
        ajax.start();
    }
}

MessageRecord.refreshMessageState = function(){
    var ajax = new $ax(Feng.ctxPath + "/admin/message_record/refreshMessageState", function (data) {
        if(data.code==200){
            Feng.success(data.msg);
            MessageRecord.table.refresh();
        }else{
            Feng.error(data.msg);
        }
    }, function (data) {
        Feng.error("刷新失败!" + data.responseJSON.message + "!");
    });
    ajax.start();
}


MessageRecord.export = function(){
    var queryData = MessageRecord.formParams();
    var url = Feng.ctxPath + "/admin/message_record/export?"+
        "&name=" + queryData.name +
        "&type=" + queryData.type +
        "&phone=" + queryData.phone +
        "&state=" + queryData.state +
        "&startTime=" + queryData.startTime +
        "&endTime=" + queryData.endTime ;
    window.location.href = encodeURI(encodeURI(url));
}

/**
 * 查询表单提交参数对象
 * @returns {{}}
 */
MessageRecord.formParams = function() {
    var queryData = {};
    queryData['name'] = $("#name").val();
    queryData['type'] = $("#type").val();
    queryData['phone'] = $("#phone").val();
    queryData['state'] = $("#state").val();
    queryData['startTime'] = $("#startTime").val();
    queryData['endTime'] = $("#endTime").val()
    return queryData;
}

/**
 * 查询人才认定申报列表
 */
MessageRecord.search = function () {
    MessageRecord.table.refresh({query: MessageRecord.formParams()});
};

/**
 * 重置
 */
MessageRecord.reset = function (){
    $("#name").val("");
    $("#type").val("");
    $("#phone").val("");
    $("#state").val("");
    $("#startTime").val("");
    $("#endTime").val("")
}

$(function () {
    var defaultColunms = MessageRecord.initColumn();
    var table = new BSTable(MessageRecord.id, "/admin/message_record/list", defaultColunms);
    table.setPaginationType("server");
    MessageRecord.table = table.init();
    //批量加载时间控件
    $(".date").each(function(){
        laydate.render({
            elem: this
            ,type: 'datetime'
            ,trigger: 'click'
            ,format:'yyyy-MM-dd HH:mm:ss'
        });
    });
});
