<!--公共方法-->
<script>
    /**
     * 获取鼠标选择的多行数据
     */
    function getTableSelects() {
        let select_row=$("#table").bootstrapTable('getSelections');
        if(select_row.length<1){
            document.getElementById("js_load").style.display = "none";
            lightyear.notify("您还没有选择要更改的数据！", 'danger');
            throw "您还没有选择要更改的数据";
        }
        return select_row;
    }
    /*/!**
     * 获取鼠标选择的多行数据
     *!/
    function getLoginUser() {
        var user;
        runAjax("${ctx}/login/get/user","get",function (res) {
            console.log("###########",res.body)
            user = res.body;
        })
        return user;
    }*/

    /**
     * 获取数据表选择的一行数据
     *
     */
    function getTableSelectOne() {
        let select_row=getTableSelects();
        if(select_row.length>1){
            document.getElementById("js_load").style.display = "none";
            lightyear.notify("您只能选择一条数据哦！", 'danger');
            throw "您只能选择一条数据哦";
        }
        return select_row[0];
    }

    /**
     * 获取当前表格选中行的id
     * */
    function getCheckIds() {
        let ids=[];
        let select_row=getTableSelects();
        select_row.forEach(function (item,index) {
            ids.push(item.id);
        })
        return ids;
    }
    /**
     * 使用id获取一行
     **/
    function getRowById(id) {
        return $("#table").bootstrapTable('getRowByUniqueId',id);
    }
    /**
     * 判断是否为json字符串
     **/
    function isJsonString(str) {
        if(typeof str == "object"){
            return true;
        }
        try {
            if (typeof JSON.parse(str) == "object") {
                return true;
            }
        } catch(e) {
        }
        return false;
    }

    /**
     * 执行AJAX
     * @param url
     * @param Method
     * @param data
     */
    function sendAjax(url,Method,data) {
        $.ajax({
            data:data,
            type: Method,
            url: url,
            success : function (res) {
                if (res.status===200){
                    lightyear.notify('操作成功!', 'success');
                    search();
                    return res;
                }
                if(res.status===300){
                    $.confirm({
                        title: '操作确认',
                        content: res.message,
                        type: 'blue',
                        typeAnimated: true,
                        buttons: {
                            tryAgain: {
                                text: '继续',
                                btnClass: 'btn-blue',
                                action: function(){
                                    data.sign=res.sign;
                                    sendAjax(url,Method,data);
                                }
                            },
                            close: {
                                text: '放弃'
                            }
                        }
                    });
                    return;
                }
                lightyear.notify(res.message, 'danger');
            },
            error : function (XMLHttpRequest, textStatus, errorThrown){
                document.getElementById("js_load").style.display = "none";
               if (textStatus===412){
                   lightyear.notify("会话超时，请重新登陆或刷新页面。", 'danger');
                   return;
               }
                lightyear.notify("系统繁忙，请尝试重新登陆。", 'danger');
            }
        });
    };
    /**
     * 执行AJAX
     * @param url
     * @param Method
     * @param data
     */
    function runAjax(url,Method,data,callback) {
        $.ajax({
            data:data,
            type: Method,
            url: url,
            success : function (res) {
                if(!isJsonString(res)){
                    callback(res);
                    return;
                }
                if (res.status===200){
                    callback(res);
                    return;
                }
                if(res.status===300){
                    $.confirm({
                        title: '操作确认',
                        content: res.message,
                        type: 'blue',
                        typeAnimated: true,
                        buttons: {
                            tryAgain: {
                                text: '继续',
                                btnClass: 'btn-blue',
                                action: function(){
                                    data.sign=res.sign;
                                    runAjax(url,Method,data,callback);
                                }
                            },
                            close: {
                                text: '放弃'
                            }
                        }
                    });
                    return;
                }
                document.getElementById("js_load").style.display = "none";
                lightyear.notify(res.message, 'danger');
            },
            error : function (XMLHttpRequest, textStatus, errorThrown){
                document.getElementById("js_load").style.display = "none";
                if (textStatus==412){
                    lightyear.notify("会话超时，请重新登陆或刷新页面。", 'danger');
                    return;
                }
                lightyear.notify("系统繁忙，请尝试重新登陆。", 'danger');
            }
        });
    };
    /**
     * 获取cookie
     * @param name 指定要获取的cookie的名称
     * @returns {string|null}
     */
    function getCookie(name) {
        let start = document.cookie.indexOf(name + "="); //得到cookie字符串中的名称
        let len = start + name.length + 1; //得到从起始位置到结束cookie位置的长度
        //如果起始没有值且name不存在于cookie字符串中，则返回null
        if ((!start) && (name !== document.cookie.substring(0, name.length))) {
            return null;
        }
        if (start === -1) return null; //如果起始位置为-1也为null
        let end = document.cookie.indexOf(';', len); //获取cookie尾部位置
        if (end === -1) end = document.cookie.length; //计算cookie尾部长度
        return unescape(document.cookie.substring(len, end)); //获取cookie值
    }


    /**
     * 设置cookie
     * @param name 名称
     * @param value 值
     * @param expires 过期日
     * @param path 路径
     * @param domain 域名
     * @param secure 加密
     */
    function setCookie(name, value, expires, path, domain, secure) {
        let today = new Date();
        today.setTime(today.getTime());
        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24; //计算cookie的过期毫秒数
        }
        //计算cookie的过期日期
        let expires_date = new Date(today.getTime() + (expires));
        //构造并保存cookie字符串
        document.cookie = name + '=' + escape(value) +
            ((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
            ((path) ? ';path=' + path : '') +
            ((domain) ? ';domain=' + domain : '') +
            ((secure) ? ';secure' : '');
    }

    /**
     * 删除cookie，必须先获取指定名称的cookie，然后让cookie过期
     * @param name
     * @param path
     * @param domain
     * @constructor
     */
    //删除cookie，必须先获取指定名称的cookie，然后让cookie过期
    function Cookie(name, path, domain) {
        if (getCookie(name)) document.cookie = name + '=' +
            ((path) ? ';path=' + path : '') +
            ((domain) ? ';domain=' + domain : '') +
            ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
    }

    /**
     * 时间格式字符串转为友好显示
     * @param dateStr yyyy-MM-dd HH:mm:ss
     * @returns {string}
     */
        function toDateFriendly(dateStr) {
        //af-测试可用
        let dateTimeStamp = Date.parse(dateStr.replace(/-/gi, "/"));
        let minute = 1000 * 60;
        let hour = minute * 60;
        let day = hour * 24;
        let halfamonth = day * 15;
        let month = day * 30;
        let now = new Date().getTime();
        let diffValue = now - dateTimeStamp;
        if (diffValue < 0) {
            return '';
        }
        let monthC = diffValue / month;
        let weekC = diffValue / (7 * day);
        let dayC = diffValue / day;
        let hourC = diffValue / hour;
        let minC = diffValue / minute;
        let result = '';
        if (monthC >= 1) {
            result = "" + parseInt(monthC) + "月前";
        } else if (weekC >= 1) {
            result = "" + parseInt(weekC) + "周前";
        } else if (dayC >= 1) {
            result = "" + parseInt(dayC) + "天前";
        } else if (hourC >= 1) {
            result = "" + parseInt(hourC) + "小时前";
        } else if (minC >= 1) {
            result = "" + parseInt(minC) + "分钟前";
        } else
            result = "刚刚";
        return result;
    }

    /**
     * 初始化并创建一个BootstrapTable对象
     {
	"id": "id_table", //绑定的<table>标签id
	"url": "${ctx}/config/xxxx", //获取数据接口
	"query": { //请求携带的查询参数
		"name": "张三"
	},
	"columns": [{//需要展示的列
		"field": "configName",//字段名称需要和后台返回的对应
		"title": "配置项名称",
	}],
	"operate": [{//对每一列添加的操作按钮
		"name": "查看",//按钮名称
		"method": "function (row){}"//按钮点击后执行的方法，参数有row=当前选中的行
	}, ]
	}
     * @param conf
     */
    function createTable(conf){
        //遍历展示列
        conf.columns.map((item,index)=>{
            item.align="center";
        });
        if (conf.operate.length>0){
            //遍历操作
            conf.columns.push(
                {
                    title:"操作",
                    align:"center",
                    formatter:function (value, row, index){
                        let str="";
                        conf.operate.map((item,index)=>{
                            let node='<a style="color: #52d3c7" href="#" onclick="agentMethod(\''+conf.id+'\',\''+row.id+'\',\''+item.method+'\')">'+item.name+'</a>';
                            str+=node;
                        });
                        return str
                    }
                }
            );
        }
        $("#"+conf.id).bootstrapTable('destroy');
        $("#" + conf.id).bootstrapTable(
            Object.assign(
                {
                    url: conf.url,
                    pagination: true,
                    uniqueId: 'id',
                    sidePagination: "server",
                    showRefresh: true
                },
                conf.attribute,
                {
                    queryParams: function (params) {
                        return {
                            pageSize: params.limit, // 每页要显示的数据条数
                            offset: params.offset, // 每页显示数据的开始行号
                            sort: params.sort, // 要排序的字段
                            sortOrder: params.order, // 排序规则,
                            showRefresh: true,
                            query:conf.query
                        }
                    },
                    onLoadSuccess: function (data) {},
                    columns: conf.columns
                }
            )
        );
    }

    /**
     * 代理访问方法
     **/
    function agentMethod(table,id,method){
        let row=$("#" + table).bootstrapTable("getRowByUniqueId",id);
        window[method](row);
    }

    /**
     * 获取数据库中指定表的指定一条数据实体
     * @param table 数据库表名称
     * @param id 数据id
     */
    function getEntity(table,id){
        let data;
        $.ajax({
            data:{keyTableName:table,id:id},
            type: 'post',
            url: "${ctx}/block/select/search/back/id",
            async: false,
            success: function (res) {
                if (res.status===200){
                    data= res.body;
                }
            }
        });
        return data;
    }

    /**
     * 打开模态框
     * @param id 模态
     * @param onOpen
     * @param onClose
     */
    function openModel(id,onOpen,onClose){
        if (onOpen){
            onOpen();
        }
        $("#"+id).modal('show');
        $('#'+id).on('hide.bs.modal',function (){
            if(onClose){
                onClose();
            }
        });
    }



</script>
<!--bootstrap-table中的的Column默认调用方法-->
<script>
    function formatter_operate(value, row, index) {
        return '<a href="javascript:tableDetail('+row.id+');"> 查看</a>';
    }
    /**
     * 格式化数组外键
     **/
    function formatter_array_key(value, row, index){
        console.log(this);
        return "<a href='javascript:arrayKeyDetail(\""+row.id+"\",\""+this.field+"\");'>详情</a>"
    }
    /**
     * 处理数组外键
     */
    function arrayKeyDetail(id,field){
        runAjax("${ctx}/table/key/model/conf","GET",{fieldName:field},function (res){
            createTable({
                id:"id_model_table_ranch_key_show",
                url:"${ctx}/table/key/query/model/array",
                /*attribute:{
                    toolbar: "#but_test"
                },*/
                query:{
                    id:id,
                    field:field
                },
                columns:res.body,
                operate:[]
            });
        });
        $("#id_model_ranch_key_show").modal('show');
    }

    /**
     * 外键处理
     * @param value
     * @param row
     * @param index
     * @returns {string}
     */
    function formatter_key(value, row, index){
        let result="加载中";
        $.ajax({
            data:{fieldName:this.field,id:value,key:this.key},
            type: 'get',
            url: "${ctx}/block/select/search/show/id",
            dataType: 'JSON',
            async: false,
            success: function (data) {
                if (data.status!==200){
                    lightyear.notify("系统繁忙，请尝试重新登陆。", 'danger');
                    return;
                }
                result= data.body;
            }
        });
        return "<a href='javascript:arrayKeyDetail(\""+row.id+"\",\""+this.field+"\");'>"+result+"</a>"
    }

    /**
     * 地址处理
     * @param value
     * @param row
     * @param index
     * @returns {string}
     */
    function formatter_address(value, row, index) {
        let params="&lat="+value.lat;
        params+="&lng="+value.lng;
        params+="&address="+value.address+value.detail;
        return "<a target='_blank' title='"+value.address+value.detail+"' href='${ctx}/views/page/map/gaode_marker?"+params+"' style='overflow: hidden;text-overflow: ellipsis;white-space: nowrap;'>"+value.city+value.area+"</a>";
    }

    /**
     * 图片处理
     * @param value
     * @param row
     * @param index
     * @returns {string}
     */
    function formatter_image(value, row, index) {
        //console.log(value)
        if (!value){
            return "-";
        }
        let urls=value.split(";");
        let htmlStr="";
        for (let i=0;i<urls.length;i++){
            if(urls[i]===""){
                continue;
            }
            htmlStr=htmlStr+("<a target='_blank' href='"+urls[i]+"'> 点击查看</a></br>");
        }
        return htmlStr;
    }
    function formatter_link(value, row, index) {
        if (!value){
            return "-";
        }
        return "<a target='_blank' href="+value+"> 点击访问</a>";
    }
    function formatter_file(value, row, index) {
        if (!value){
            return "-";
        }
        let urls=value.split(";");
        let htmlStr="";
        for (let i=0;i<urls.length;i++){
            if(urls[i]===""){
                continue;
            }
            htmlStr=htmlStr+("<a target='_blank' href='"+urls[i]+"'> 点击下载</a></br>");
        }
        return htmlStr;
    }
    function formatter_edit(value, row, index) {
        if (value===undefined){
            value="点击编辑备注";
        }
        return '<a href="#" name="UserName" class="table-edit" data-type="text" data-pk='+row.id+' data-title="备注">' + value + '</a>';
    }
    function formatter_boolean(value, row, index) {
        if (value===undefined){
            return "-";
        }
        if(value===true)return "是";
        if(value===false)return  "否";
        else return "-";
    }
</script>
<!--bootatrap-table触发事件-->
<script>
    $('#table').on('load-success.bs.table', function () {
        //$('#table').bootstrapTable('refresh',{silent: false});
        console.log("成功");
        document.getElementById("js_load").style.display = "none";
    });
    $('#table').on('refresh.bs.table', function () {
        document.getElementById("js_load").style.display = "inline";
    });
    $('#table').on('search.bs.table', function () {
        document.getElementById("js_load").style.display = "inline";
    });
    $('#table').on('load-error.bs.table', function (jqXHR,status) {
        document.getElementById("js_load").style.display = "none";
        if (status===412){
            lightyear.notify("会话超时，请重新登陆或刷新页面。", 'danger');
            return;
        }
        lightyear.notify("数据加载失败，请检查网络连接，或者重新登陆！", 'danger');
    });
    $('#table').on('sort.bs.table', function () {
        document.getElementById("js_load").style.display = "inline";
    });
    function search() {
        $('#table').bootstrapTable('refresh',{url: "${ctx!}/table/query"});
    };

    /**
     * 表单重置并刷新数据表区域
     */
    function tableReset(form_id) {
        $("#"+form_id)[0].reset();
        $('#'+form_id+' .selectpicker').selectpicker('refresh');
        search();
    };
    function queryParams(params) {
        let queryParams = {
            pageSize: params.limit, // 每页要显示的数据条数
            offset: params.offset, // 每页显示数据的开始行号
            sort: params.sort, // 要排序的字段
            sortOrder: params.order, // 排序规则
            search:{
                name:params.search,
                key:$("#search-field").val()
            },
            query:{
                <#list pageTemplate.tableQuery as block>
                    ${block.columnName}:$("#${block.id}").val(),
                </#list>
            }
        }
        return queryParams;
    }
</script>
<!--时间选择控件初始化列表-->
<#list pageTemplate.tableQuery as block>
<#if block.blockType =="DateBlock">
<script type="text/javascript">
    $(function () {
        $('#${block.id!}').daterangepicker(
            {
                //timePicker: true, //显示时间
                //timePicker24Hour: true, //时间制
                //showDropdowns: true,//年月下拉
                //timePickerSeconds: true, //时间显示到秒
                /*startDate: moment().hours(0).minutes(0).seconds(0), //设置开始日期
                endDate: moment(new Date()), //设置结束器日期
                maxDate: moment(new Date()), //设置最大日期*/
                //"opens": "center",
                autoUpdateInput: false,
                opens: 'right', // 日期选择框的弹出位置
                ranges: {
                    '今天': [moment(), moment()],
                    '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    '近7天': [moment().subtract(6, 'days'), moment()],
                    '近30天': [moment().subtract(29, 'days'), moment()],
                    '本周': [moment().startOf('week'), moment().endOf('week')],
                    '上周': [moment().week(moment().week() - 1).startOf('week'), moment().week(moment().week() - 1).endOf('week')],
                    '本月': [moment().startOf('month'), moment().endOf('month')],
                    '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                    '本季度': [moment().startOf('quarter'), moment().endOf('quarter')],
                    '上季度':[moment().quarter(moment().quarter() - 1).startOf('quarter'),moment().quarter(moment().quarter() - 1).endOf('quarter')],
                    '本年': [moment().startOf('year'), moment().endOf('year')],
                    '去年': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
                },
                showWeekNumbers: true,
                separator: ' to ',
                locale: {
                    format: "YYYY-MM-DD", //设置显示格式
                    applyLabel: '确定', //确定按钮文本
                    cancelLabel: '取消', //取消按钮文本
                    customRangeLabel: '自定义',
                    daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                        '七月', '八月', '九月', '十月', '十一月', '十二月'
                    ],
                    firstDay: 1
                },
            }/*, function(start, end, label) {
                timeRangeChange = [start.format('YYYY-MM-DD')]+'至'+[end.format('YYYY-MM-DD')];
                $("#query_date").val(timeRangeChange);
                console.log(timeRangeChange);
            }*/
        );
    });
    $('#${block.id!}').on('apply.daterangepicker', function (ev, picker) {
        timeRangeChange = [picker.startDate.format('YYYY-MM-DD')] + '至' + [picker.endDate.format('YYYY-MM-DD')];
       /* $("#query_date").val(timeRangeChange);*/
        $('#${block.id!}').val(timeRangeChange);
    });
</script>
</#if>
</#list>

<!--批量操作按钮方法-->
<script>
    //详情模态框中Ajax数量
    var modelAjaxCount=0;
    /**
     *加载动画检查
     */
    function checkLoading() {
        modelAjaxCount--;
        if(modelAjaxCount<1){
            document.getElementById("js_load").style.display = "none";
        }
    }

    /**
     * 修改数据模态框
     **/
    function tableEdit(select_row) {
        document.getElementById("js_load").style.display = "inline";
        modelAjaxCount=0;
        runAjax("${ctx}/table/model/get/template","GET","",function (data) {
            //console.log(data);
            data.body.inputBlocks.forEach(function (item,index) {
                let str=select_row[item.name];
                if ("undefined"===select_row[item.name]){
                }
                if("SelectBlock"===item.blockType){
                    if ("searchSelect"===item.selectType){
                        modelAjaxCount++;
                    }
                }
                if ('AddressBlock' === item.blockType){
                    if("undefined"===select_row[item.name].detail){
                        str=select_row[item.name].address
                    }
                    else{
                        str=select_row[item.name].address+select_row[item.name].detail;
                    }
                    let poi={};
                    poi.location={};
                    poi.address=str;
                    poi.location.lng=select_row[item.name].lng;
                    poi.location.lat=select_row[item.name].lat;
                    $('#'+item.id+'_show').val(str);
                    $('#'+item.id).val(JSON.stringify(poi));
                    return;
                }
                $('#'+item.id).val(str);
                $('#'+item.id).trigger('input',str);
            });
            if(modelAjaxCount===0){
                document.getElementById("js_load").style.display = "none";
            }
        });
        $('#id_table_model').modal("show");
    }
    /**
     * 删除数据
     **/
    function tableDelete(ids) {
        $.confirm({
            title: '删除确认',
            content: '您将要删除该条数据，是否继续？',
            type: 'red',
            typeAnimated: true,
            buttons: {
                tryAgain: {
                    text: '删除',
                    btnClass: 'btn-red',
                    action: function(){
                        sendAjax("${ctx!}/table/button/delete/","POST",{idsp:ids});
                    }
                },
                close: {
                    text: '取消'
                }
            }
        });
    }
    /**
     *打开详情页
     **/
    function tableDetail(id) {
        tableEdit(getRowById(id));
    }


    /**
     * 批量操作按钮默认调用方式
     */
    function buttonClick(type) {
        switch (type) {
            //新增按钮操作
            case "ADD":
                //$("#id_table_model_form")[0].reset();
                $('#id_table_model_new').modal("show");
                break;
            //编辑按钮操作
            case "EDIT":
                tableEdit(getTableSelectOne());break;
            //删除按钮操作
            case "DELETE":
                tableDelete(getCheckIds());break;
        }
    };

    /**
     * 导出数据
     * @param flag
     **/
    function exportExcel(flag) {
       let ids = null;
        switch (flag) {
            case "check":
                ids = getCheckIds('table').join(',');
                break;
            case "page":
                $("#table").bootstrapTable('checkAll');
                ids = getCheckIds('table').join(',');
                break;
            case "all":
                ids = "";
                window.location.href = "${ctx}/table/export/excel?ids=" + ids;
                return;
            default:
                break;
        }
        if (ids.length < 1) {
            lightyear.notify("暂时没有可导出的数据~~。", 'danger');
            return;
        }
        window.location.href = "${ctx}/table/export/excel?ids=" + ids;
    }

    /**
     * 修改一列
     * 默认
     * @param column 列名称
     * @param value 值
     */
    function setColumn(column,value){
        setColumn2(getTableSelectOne().id,column,value);
    }

    /**
     *  修改一列数据
     * @param id id
     * @param column 列名
     * @param value 值
     */
    function setColumn2(id,column,value) {
        let data={
            id: id,
            column:column,
            value:value
        };
        $.confirm({
            title: '更改数据',
            content: '您将要执行更改操作，是否继续？',
            type: 'blue',
            typeAnimated: true,
            buttons: {
                tryAgain: {
                    text: '继续',
                    btnClass: 'btn-blue',
                    action: function(){
                        sendAjax("${ctx}/table/model/set/column","post",data);
                    }
                },
                close: {
                    text: '放弃'
                }
            }
        });
    }

</script>
<!--其他事件-->
<script>
    $(".table-edit").editable({
            url: function (params) {
                $.ajax({
                    type: 'POST',
                    url: "${ctx}/partner/update/rmk",
                    data: {
                        partnerId:params.pk,
                        rmk:params.value
                    },
                    dataType: 'JSON',
                    success: function (data, textStatus, jqXHR) {
                        if (data.status===200){
                            lightyear.notify('修改成功!', 'success');
                        }
                        else{
                            lightyear.notify(data.message, 'danger');
                        }
                    },
                    error: function () {
                        lightyear.notify("糟糕~~服务器失去响应，请尝试重新登陆。", 'danger');
                    }
                });
            },
            type: 'text'
        }
    );
    $(function(){
        $('#id_search_column .dropdown-menu a').click(function() {
            let field = $(this).data('field') || '';
            $('#search-field').val(field);
            $('#search-btn').html($(this).text() + ' <span class="caret"></span>');
        });
    });
    /**
     * 新增修改弹出层表单提交
     */
    function okSend(flag) {
        $.confirm({
            title: '修改确认',
            content: '您将要执行更改操作，是否继续？',
            type: 'blue',
            typeAnimated: true,
            buttons: {
                tryAgain: {
                    text: '继续',
                    btnClass: 'btn-blue',
                    action: function(){
                        editSubmit(flag);
                    }
                },
                close: {
                    text: '放弃'
                }
            }
        });
    };

    /**
     * 更改表单提交
     */
    function editSubmit(flag) {
        let data={}
        if('new'===flag){
            $('#table_model_new_submit_id').button('loading');
            data={${pageTemplate.tableModel.newJs!}}
        }
        else{
            $('#table_model_edit_submit_id').button('loading');
            data={${pageTemplate.tableModel.js!}}
        }
        $.ajax({
            data:data,
            type: "POST",
            url: "${ctx}${pageTemplate.tableModel.url}",
            success : function (data) {
                $('#table_model_edit_submit_id').button('reset');
                if (data.status===200){
                    if("new"===flag){
                        tableReset('id_table_model_form_new');
                        $('#table_model_new_submit_id').button('reset');
                        $('#id_table_model_new').modal("hide");
                        return;
                    }
                    else{
                        $('#id_table_model').modal("hide");
                        $('#table_model_edit_submit_id').button('reset');
                    }
                    search();
                    lightyear.notify('操作成功!', 'success');
                    return;
                }
                $('#table_model_new_submit_id').button('reset');
                $('#table_model_edit_submit_id').button('reset');
                lightyear.notify(data.message, 'danger');
            },
            error : function (XMLHttpRequest, textStatus, errorThrown){
                $('#table_model_edit_submit_id').button('reset');
                console.log("开始：");
                console.log(XMLHttpRequest);
                console.log(textStatus);
                console.log(errorThrown);
                console.log("结束：")
                if (XMLHttpRequest.status===412){
                    lightyear.notify("会话超时，请重新登陆或刷新页面。", 'danger');
                    return;
                }
                lightyear.notify("系统繁忙，请尝试重新登陆。", 'danger');
            }
        });
    }

    /**
     * 设置语音通知
     * @param node
     */
    function setVolume(node){
        let open=!JSON.parse(getCookie('volume_open'));
        setCookie("volume_open",open,15);
        node.setAttribute('class',open?'mdi mdi-volume-high mdi-24px':'mdi mdi-volume-off mdi-24px');
    }
    $(function(){
        let open=getCookie('volume_open');
        if(open==null){
            setCookie("volume_open",true,15);
        }
        document.getElementById("id_notice_volume").setAttribute('class',JSON.parse(open)?'mdi mdi-volume-high mdi-24px':'mdi mdi-volume-off mdi-24px');
    });
    /**
     * JQuery扩展，表单遍历赋值
     * @param jsonValue json值对象
     */
    $.fn.setForm = function(jsonValue) {
        var obj = this;
        $.each(jsonValue, function(name, ival) {
            var $oinput = obj.find("input[name=" + name + "]");
            var $oselect = obj.find("select[name=" + name + "]")
            if ($oinput.attr("type") === "radio" || $oinput.attr("type") === "checkbox") {
                $oinput.each(function() {
                    //console.log(Object.prototype.toString.apply(ival),'++++++++++++++++')
                    if (Object.prototype.toString.apply(ival) === '[object Array]') { //是复选框，并且是数组

                        for (var i = 0; i < ival.length; i++) {
                            if ($(this).val() === ival[i]){ //或者文本相等


                                $(this).prop("checked", true);
                            }
                        }
                    }else {

                        if ($(this).val() === ival){

                            $(this).prop("checked", true);
                        }
                    }
                });
            }else if($oselect.attr("name") !== undefined){
                $oselect.each(function(i) {

                    for (j = 0; j < $oselect[i].options.length; j++) {
                        if ($oselect[i].options[j].text === ival) {    // 选项值与变量相同

                            $oselect[i].options[j].selected =true;

                        }
                    }

                })

            }else if ($oinput.attr("type") === "textarea") {
                obj.find("[name=" + name + "]").html(ival);
            } else {
                obj.find("[name=" + name + "]").val(ival);
            }
        })
    };

    /**
     * form表单转json
     * @returns {{}}
     */
    $.fn.serializeFormToJson = function(){
        var arr = $(this).serializeArray();//form表单数据 name：value
        var param = {};
        $.each(arr,function(i,obj){ //将form表单数据封装成json对象
            param[obj.name] = obj.value;
        })
        return param;
    }
</script>