/**
 * EMA 公共工具模块
 */
var Common = {
    /**
     * 获取请求头（包含token）
     */
    getHeaders: function() {
        var token = localStorage.getItem('token');
        var headers = {};
        if (token) {
            // 添加Bearer Token认证
            headers['token'] = token;
        }
        return headers;
    },

    /**
     * Ajax请求封装
     * @param {Object} options 请求配置
     */
    ajax: function(options) {
        var layer = layui.layer;
        var token = localStorage.getItem('token');
        
        // 获取请求类型
        var requestType = (options.type || 'GET').toUpperCase();
        
        // 构建请求配置
        var ajaxOptions = {
            url: Config.getApiUrl(options.url || ''),
            type: requestType,
            dataType: 'json',
            headers: this.getHeaders(),
            beforeSend: function(xhr) {
                // 确保token在请求头中
                if (token) {
                    xhr.setRequestHeader('token', token);
                }
                if (options.loading !== false) {
                    layer.load(2, { shade: [0.3, '#000'] });
                }
            },
            complete: function() {
                if (options.loading !== false) {
                    layer.closeAll('loading');
                }
            },
            success: function(res) {
                if (res.code === 401 || res.code === 403 || (res.msg && res.msg.indexOf('登录') !== -1)) {
                    layer.msg('登录已过期，请重新登录', { icon: 2 }, function() {
                        localStorage.clear();
                        parent.location.href = '../index.html';
                    });
                    return;
                }
                options.success && options.success(res);
            },
            error: function(xhr) {
                var msg = '请求失败';
                if (xhr.status === 401) {
                    layer.msg('登录已过期，请重新登录', { icon: 2 }, function() {
                        localStorage.clear();
                        parent.location.href = '../index.html';
                    });
                    return;
                } else if (xhr.status === 404) {
                    msg = '接口不存在';
                } else if (xhr.status === 500) {
                    msg = '服务器错误';
                } else if (xhr.status === 0) {
                    msg = '网络连接失败，请检查网络';
                }
                options.error && options.error(xhr) || layer.msg(msg, { icon: 2 });
            }
        };

        // POST/PUT 请求使用 JSON 格式放入请求体
        if (requestType === 'POST' || requestType === 'PUT') {
            ajaxOptions.contentType = 'application/json;charset=UTF-8';
            if (options.data) {
                ajaxOptions.data = JSON.stringify(options.data);
            } else {
                ajaxOptions.data = '{}';
            }
        } else {
            // GET/DELETE 请求数据作为查询参数
            ajaxOptions.data = options.data;
        }

        $.ajax(ajaxOptions);
    },
    
    /**
     * GET请求
     */
    get: function(url, data, success, error) {
        var options = { url: url, type: 'GET' };
        if (typeof data === 'function') {
            options.success = data;
        } else {
            options.data = data;
            options.success = success;
        }
        options.error = error;
        this.ajax(options);
    },
    
    /**
     * POST请求
     */
    post: function(url, data, success, error) {
        this.ajax({
            url: url,
            type: 'POST',
            data: data,
            success: success,
            error: error
        });
    },
    
    /**
     * PUT请求
     */
    put: function(url, data, success, error) {
        this.ajax({
            url: url,
            type: 'PUT',
            data: data,
            success: success,
            error: error
        });
    },
    
    /**
     * DELETE请求
     */
    del: function(url, success, error) {
        this.ajax({
            url: url,
            type: 'DELETE',
            success: success,
            error: error
        });
    },
    
    /**
     * 打开弹窗
     * @param {Object} options 配置
     */
    open: function(options) {
        var layer = layui.layer;
        var defaults = {
            type: 2,
            shade: 0.3,
            anim: -1,
            maxmin: true,
            moveOut: true
        };
        return layer.open($.extend(defaults, options));
    },
    
    /**
     * 确认对话框
     */
    confirm: function(content, callback) {
        var layer = layui.layer;
        layer.confirm(content, { icon: 3, title: '提示' }, function(index) {
            callback && callback();
            layer.close(index);
        });
    },
    
    /**
     * 成功提示
     */
    success: function(msg, callback) {
        var layer = layui.layer;
        layer.msg(msg, { icon: 1 }, callback);
    },
    
    /**
     * 失败提示
     */
    error: function(msg, callback) {
        var layer = layui.layer;
        layer.msg(msg, { icon: 2 }, callback);
    },
    
    /**
     * 获取URL参数
     */
    getQueryString: function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        return r != null ? decodeURIComponent(r[2]) : null;
    },
    
    /**
     * 格式化日期
     */
    formatDate: function(date, format) {
        if (!date) return '';
        date = typeof date === 'string' ? new Date(date.replace(/-/g, '/')) : date;
        format = format || 'yyyy-MM-dd HH:mm:ss';
        
        var o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'H+': date.getHours(),
            'h+': date.getHours() % 12 || 12,
            'm+': date.getMinutes(),
            's+': date.getSeconds(),
            'q+': Math.floor((date.getMonth() + 3) / 3),
            'S': date.getMilliseconds()
        };
        
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        
        for (var k in o) {
            if (new RegExp('(' + k + ')').test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
            }
        }
        return format;
    },
    
    /**
     * 获取状态标签
     */
    getStatusBadge: function(status, map) {
        map = map || { '1': '正常', '0': '停用' };
        var config = {
            '1': { class: 'layui-btn-xs', color: 'green' },
            '0': { class: 'layui-btn-xs layui-btn-primary', color: 'gray' }
        };
        var text = map[status] || status;
        var c = config[status] || config['0'];
        return '<span class="layui-badge-' + c.color + ' ' + c.class + '">' + text + '</span>';
    },
    
    /**
     * 获取用户信息
     */
    getUserInfo: function() {
        var userInfo = localStorage.getItem('userInfo');
        return userInfo ? JSON.parse(userInfo) : null;
    },
    
    /**
     * 检查登录状态
     */
    checkLogin: function() {
        var token = localStorage.getItem('token');
        if (!token) {
            parent.location.href = '../index.html';
            return false;
        }
        return true;
    }
};

/**
 * 表格渲染封装
 */
var TableRender = {
    /**
     * 获取表格请求头
     */
    getTableHeaders: function() {
        var token = localStorage.getItem('token');
        var headers = {};
        if (token) {
            headers['token'] = token;
        }
        return headers;
    },

    /**
     * 初始化表格
     */
    init: function(options) {
        var table = layui.table;
        var defaults = {
            method: 'POST',
            contentType: 'application/json',
            headers: this.getTableHeaders(),
            request: {
                pageName: 'pageNumber',
                limitName: 'pageSize'
            },
            response: {
                statusName: 'code',
                statusCode: 200,
                msgName: 'msg',
                dataName: 'data',
                countName: 'count'
            },
            parseData: function(res) {
                // 兼容多种分页返回格式：total/totalRow/totalRow/size
                return {
                    code: res.code,
                    msg: res.message,
                    count: res.data.totalRow || res.data.total || res.data.size || res.data.count || 0,
                    data: res.data ? (res.data.records || res.data.list || []) : []
                };
            },
            before: function(req) {
                // layui table 会在请求前调用此方法
                var token = localStorage.getItem('token');
                if (token) {
                    req.headers = req.headers || {};
                    req.headers['token'] = token;
                }
            }
        };
        return table.render($.extend(defaults, options));
    },
    
    /**
     * 重新加载表格
     */
    reload: function(tableId, options) {
        var table = layui.table;
        var defaultOptions = {
            where: {},
            page: { curr: 1 }
        };
        table.reload(tableId, $.extend(defaultOptions, options));
    }
};
