<template>
    <section class="content">
        <div class="box box-primary">
            <div class="box-body">
                <!-- Content Header (Page header) -->
                <section class="content-header">
                    <h1 id="itemTitle"></h1>
                </section>
                <!-- .content -->
                <div id="toolbar">
                    <div class="col-sm-12">
                        <label for="erbanNo" class="col-sm-1 control-label">平台号:</label>
                        <div class="col-sm-2"><input type="text" class="form-control" name="erbanNo" id="erbanNo" /></div>

                        <label for="templateId" class="col-sm-1 control-label">模板ID:</label>
                        <div class="col-sm-2">
                            <select name="templateId" id="templateId" data-btn-class="btn-warning" class="form-control">
                            </select>
                        </div>

                        <label for="sendStatus" class="col-sm-1 control-label">短信发送状态:</label>
                        <div class="col-sm-2">
                            <select name="sendStatus" id="sendStatus" data-btn-class="btn-warning" class="form-control">
                                <option value="0">全部</option>
                                <option value="1">未发送</option>
                                <option value="2">发送成功</option>
                                <option value="3">发送失败</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-12">
                        <label for="createTime" class="col-sm-1 control-label">创建时间:</label>
                        <div class="col-sm-2"><input type="text" class="form-control" name="createTime" id="createTime" />
                        </div>

                        <label for="sendTime" class="col-sm-1 control-label">短信发送时间:</label>
                        <div class="col-sm-2"><input type="text" class="form-control" name="sendTime" id="sendTime" /></div>
                    </div>

                    <div class="col-sm-12">
                        <button id="btnSearch" class="btn btn-default">
                            <i class="glyphicon glyphicon-search"></i>查询
                        </button>
                        <button id="btnSend" class="btn btn-default opt-apply">
                            <i class="glyphicon glyphicon-adjust"></i>批量发送(单页)
                        </button>
                        <button id="btnBatchSend" class="btn btn-default opt-apply">
                            <i class="glyphicon glyphicon-adjust"></i>批量发送(按查询条件)
                        </button>
                        <button id="btnImport" class="btn btn-default">
                            <i class="glyphicon glyphicon-search"></i>导入
                        </button>
                    </div>
                </div>
            </div>
            <div id="table"></div>
        </div>
    </section>

    <div class=" modal fade" id="fileUpload" tabindex="-1" role="dialog" aria-labelledby="modalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title" id="modalLabel1">上传文件</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" id="uploadForm">
                        <div class="form-group">
                            <label for="sendTemplateId" class="col-sm-3 control-label">模板ID:</label>
                            <div class="col-sm-9">
                                <select name="templateId" id="sendTemplateId" class="form-control">
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="uploadFile" class="col-sm-3 control-label">上传文件:</label>
                            <div class="col-sm-9">
                                <input type="file" class="form-control validate[required]" name="uploadFile"
                                    id="uploadFile" />
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">注意:</label>
                            <div class="col-sm-9">
                                <span>
                                    <font color="#dd4b39">1.上传文件仅支持.xlsx格式的文件<br>
                                        2.文件内容第一行为标题(例:平台号,手机号)<br>
                                        3.第一列为用户平台号,第二列为用户绑定的手机号码(手机号码为非必填项)
                                        填写了手机号码时,以填写的手机号码为准</font>
                                </span>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer" style="height: 20%">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="upload">确定</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import TableHelper from '@/utils/bootstrap-table-helper';
import { showLoading, hideLoading }from '@/utils/maintainer.js';

export default {
    name: "OperationSmsAdminView",
    created() {
        this.$nextTick(function () {
            this.initData();
        });
    },
    methods: {
        initData() {
            $(function () {
                //获取模板列表
                getTemplateList();
                //初始化表格
                $('#table').bootstrapTable('destroy');
                $('#table').bootstrapTable({
                    columns: [
                        { field: 'temp', title: 'id', align: 'center', checkbox: true, width: '5%' },
                        { field: 'erbanNo', title: '平台号', align: 'center', width: '5%' },
                        { field: 'phone', title: '手机号码', align: 'center', width: '5%' },
                        { field: 'templateName', title: '短信模板', align: 'center', width: '5%' },
                        {
                            field: 'createTime',
                            title: '创建时间',
                            align: 'center',
                            width: '5%',
                            valign: 'middle',
                            formatter: function (val, row, index) {
                                if (val) {
                                    var date = new Date(val);
                                    return date.format("yyyy-MM-dd hh:mm:00");
                                } else {
                                    return '-';
                                }
                            }
                        },
                        {
                            field: 'sendTime',
                            title: '发送时间',
                            align: 'center',
                            width: '5%',
                            valign: 'middle',
                            formatter: function (val, row, index) {
                                if (val) {
                                    var date = new Date(val);
                                    return date.format("yyyy-MM-dd hh:mm:00");
                                } else {
                                    return '-';
                                }
                            }
                        },
                        { field: 'operatorName', title: '操作者', align: 'center', width: '5%' },
                        {
                            field: 'sendStatus',
                            title: '发送状态',
                            align: 'center',
                            width: '5%',
                            formatter: function (val, row, index) {
                                if (val == 1) {
                                    return "未发送";
                                } else if (val == 2) {
                                    return "发送成功";
                                } else if (val == 3) {
                                    return "发送失败";
                                } else {
                                    return "未知状态";
                                }
                            }
                        },
                        {
                            field: 'recordId',
                            title: '操作',
                            align: 'center',
                            width: '15%',
                            formatter: function (val, row, index) {
                                return '<button id="send" name="send" class="btn btn-sm btn-success opt-send" data-id=' + val + '>' +
                                    '<i class="glyphicon glyphicon-edit"></i> 发送</button>&nbsp;&nbsp;' +
                                    '<button id="del" name="del" class="btn btn-sm btn-success opt-del" data-id=' + val + '>' +
                                    '<i class="glyphicon glyphicon-warning-sign"></i> 删除</button>&nbsp;&nbsp;';
                            }
                        }
                    ],
                    cache: false,
                    striped: true,
                    showRefresh: false,
                    pageSize: 20,
                    pagination: true,
                    pageList: [20, 50, 100, 200, 300, 500],
                    search: false,
                    sidePagination: "server", //表示服务端请求
                    //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
                    //设置为limit可以获取limit, offset, search, sort, order
                    queryParamsType: "undefined",
                    queryParams: function queryParams(params) {   //设置查询参数
                        var param = {
                            page: params.pageNumber,
                            pageSize: params.pageSize,
                            erbanNo: $('#erbanNo').val(),
                            templateId: $('#templateId').val(),
                            sendStatus: $('#sendStatus').val(),
                            createTime: $('#createTime').val(),
                            sendTime: $('#sendTime').val()
                        };
                        return param;
                    },
                    toolbar: '#toolbar',
                    url: '/admin/sms/list.action',
                    onLoadSuccess: function () {  //加载成功时执行
                        console.log("load success");
                    },
                    onLoadError: function () {  //加载失败时执行
                        console.log("load fail");
                    }
                });

                var picker1 = $("#createTime").datetimepicker({
                    format: 'yyyy-mm-dd',
                    autoclose: true,
                });
                var picker2 = $("#sendTime").datetimepicker({
                    format: 'yyyy-mm-dd',
                    autoclose: true
                });

                $("#btnSearch").click(function () {
                    TableHelper.doRefresh('#table');
                })

                $("#btnImport").click(function () {
                    $("#uploadFile").val("");
                    $("#fileUpload").modal('show');
                });

                $("#upload").click(function () {
                    var templateId = $("#sendTemplateId").val();
                    if (templateId == null) {
                        $("#tipMsg").text("短信模板ID不能为空.");
                        $("#tipModal").modal('show');
                    }
                    var file = $("#uploadFile").val();
                    if (file == null || file == undefined || file == '') {
                        $("#tipMsg").text("上传文件不能为空.");
                        $("#tipModal").modal('show');
                    }
                    debugger;
                    $("#fileUpload").modal('hide');
                    showLoading();
                    var option = ({
                        type: "POST",
                        url: "/admin/sms/uploadExcel.action",
                        cache: false,
                        contentType: false,    //不可缺
                        processData: false,    //不可缺
                        dataType: "json",
                        success: function (json) {
                            hideLoading();
                            console.log(json)
                            if (json.code == 200) {
                                $("#tipMsg").text("上传成功");
                                $("#tipModal").modal('show');
                                TableHelper.doRefresh('#table');
                            } else {
                                $("#tipMsg").text("上传失败.");
                                $("#tipModal").modal('show');
                            }
                        },
                        error: function () {
                            hideLoading();
                            $("#tipMsg").text("上传失败.");
                            $("#tipModal").modal('show');
                        }
                    });
                    $("#uploadForm").ajaxSubmit(option);
                });

                function getTemplateList() {
                    $.get('/admin/sms/getSmsTemp', function (res) {
                        if (res.code == 200) {
                            console.log(res.data);
                            var $first = $('<option value="0">全部</option>');
                            $('#templateId').append($first);
                            for (var i = 0; i < res.data.length; i++) {
                                var str = "<option value='" + res.data[i].templateId + "'>" + res.data[i].templateName + "</option>";
                                $('#templateId').append(str);
                                $('#sendTemplateId').append(str);
                            }
                        }
                    })
                }

                $("#btnBatchSend").click(function () {
                    var erbanNo = $('#erbanNo').val();
                    var templateId = $('#templateId').val();
                    var sendStatus = $('#sendStatus').val();
                    var createTime = $('#createTime').val();
                    var sendTime = $('#sendTime').val();
                    var data = {
                        erbanNo: erbanNo,
                        templateId: templateId,
                        sendStatus: sendStatus,
                        createTime: createTime,
                        sendTime: sendTime
                    };
                    var url = "/admin/sms/query/send.action";
                    if (confirm("按查询条件发送最多一次可发送一万条短信!已发送过的用户不会重复发送,你确认批量发送吗?")) {
                        sendSmsByData(data, url);
                    }
                })

                $("#btnSend").click(function () {
                    var rows = $("#table").bootstrapTable("getSelections");
                    if (rows.length == 0) {
                        alert("请先选择要发送的记录");
                        return;
                    }
                    var idArr = [];
                    for (var i = 0; i < rows.length; i++) {
                        idArr.push(rows[i]['recordId']);
                    }
                    var data = {
                        ids: JSON.stringify(idArr)
                    }
                    var url = "/admin/sms/page/send.action";
                    if (confirm("你确认批量发送吗?")) {
                        sendSmsByData(data, url);
                    }
                })

                $("#table").on('click', '.opt-send', function () {
                    var id = $(this).attr("data-id");
                    var data = { recordId: id };
                    var url = "/admin/sms/send.action";
                    if (confirm("已经发送过的短信将会重复发送,确定重复发送短信吗？")) {
                        sendSmsByData(data, url);
                    }
                })

                $("#table").on('click', '.opt-del', function () {
                    var id = $(this).attr("data-id");
                    if (confirm("删除的数据将不能找回，确定删除吗？")) {
                        $.ajax({
                            type: "post",
                            url: "/admin/sms/del.action",
                            data: { recordId: id },
                            dataType: "json",
                            success: function (json) {
                                if (json.code == '200') {
                                    $("#withdrawModal").modal('hide');
                                    $("#tipMsg").text("删除成功");
                                    $("#tipModal").modal('show');
                                    TableHelper.doRefresh("#table");
                                } else {
                                    $("#tipMsg").text("删除失败" + json.msg);
                                    $("#tipModal").modal('show');
                                }
                            }
                        });
                    }
                })

                function sendSmsByData(data, url) {
                    $.ajax({
                        type: "post",
                        url: url,
                        data: data,
                        dataType: "json",
                        success: function (json) {
                            if (json.code == '200') {
                                $("#withdrawModal").modal('hide');
                                $("#tipMsg").text("已发送,发送结果请查看发送状态");
                                $("#tipModal").modal('show');
                                TableHelper.doRefresh("#table");
                            } else {
                                $("#tipMsg").text("发送失败" + json.msg);
                                $("#tipModal").modal('show');
                            }
                        }
                    });
                }
            });
        }
    },

};
</script>

<style scoped></style>