/**
 * 计算字符串的哈希值
 * @returns {number}
 */
String.prototype.hashCode = function () {
    let hash = 0, i, chr;
    if (this.length === 0) return hash;
    for (i = 0; i < this.length; i++) {
        chr = this.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0;
    }
    return hash;
};
/**
 * 日期格式化
 * @param format
 * @returns {*}
 */
Date.prototype.format = function (format) {
    let date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}

/**
 * 打开一个最大化的弹窗
 * @param url 页面url
 * @param options
 */
function openMaxLayer(url, options) {
    let _options = Object.assign({
        title: false,
        type: 2,
        area: [window.innerWidth - 30 + 'px', window.innerHeight - 26 + 'px'],
        content: url,
        success: function (layero, index) {
            this.childElem = layer.getChildFrame('body', index);
            this.childWindow = window[layero.find('iframe')[0]['name']];
        }
    }, options);
    layer.open(_options);
}

function showOkMsg(msg = 'OK提示', options) {
    layer.msg(msg, Object.assign({icon: 1, time: 1000}, options))
}

function showErrorMsg(msg = '系统异常', options) {
    layer.msg(msg, Object.assign({icon: 2, time: 2000}, options))
}

function postRequest(url, data) {
    return sendRequest(url, data, {type: 'post'});
}

function sendRequest(url, params, options = {}) {
    let loadIndex = layer.load();
    return new Promise(function (resolve, reject) {
        $.ajax(Object.assign({
            url,
            type: 'get',
            data: params,
            dataType: 'json',
            success: (res) => {
                layer.close(loadIndex);
                resolve && resolve(res);
            },
            error: (err) => {
                layer.close(loadIndex);
                reject && reject(err);
            }
        }, options))
    });
}

/**
 * 生成layui table组件的options
 * @param options
 * @returns {any}
 */
function generateTableOptions(options) {
    return Object.assign({
        page: true,
        autoSort: false,
        limit: 30,
        limits: [20, 30, 50, 100],
        height: 'full-20',
        defaultToolbar: [],
        text: {none: '没有查询到数据'},
        request: {
            pageName: 'current' //页码的参数名称，默认：page
            , limitName: 'size' //每页数据量的参数名，默认：limit
        },
        response: {
            statusName: 'flag' //规定数据状态的字段名称，默认：code
            , statusCode: true //规定成功的状态码，默认：0
        },
        parseData: function (res) { //res 即为原始返回的数据
            let data = res.data || {records: [], total: 0};
            return {
                "flag": res.flag, //解析接口状态
                "msg": res.msg, //解析提示文本
                "data": data.records,
                "count": data.total
            };
        }
    }, options);
}

/**
 * 获取查询参数模型
 * @returns {{column: string, logic: string, value: string}}
 */
function getQueryParamModel() {
    return {
        column: '',
        logic: '',
        value: ''
    }
}

/**
 * 查询参数中的判断逻辑符号的常量
 * @type {{ne: string, lt: string, le: string, eq: string, gt: string, ge: string}}
 */
const Logic = {
    lt: 'lt',  // 小于
    gt: 'gt', // 大于
    le: 'le', // 小于等于
    ge: 'ge', // 大于等于
    eq: 'eq', // 等于
    ne: 'ne', // 不等于
    like: 'like', // like全匹配
    likeLeft: 'likeLeft', // like左匹配
    likeRight: 'likeRight', // like右匹配
    in: 'in', // 包含在列表中
    notIn: 'notIn' // 不包含在列表中
}

/**
 * 解析数据
 * @param row 数据行
 * @param field 字段配置
 */
function parseValue(row, field) {
    let {tag, fieldId, options} = field;
    let value = row[fieldId];
    if (!value || value === 'null' || value === '') {
        return ''
    }
    switch (tag) {
        case 'radio':
        case 'select':
            return matchValue(value)
        case 'switch':
            return value == 1 ? '是' : '否';
        case 'checkbox':
            let values = [];
            for (let val of value.split(',')) {
                values.push(matchValue(val));
            }
            return values.join(',');
        case 'date':
            return new Date(value).format(field.dateFormat);
        case 'password':
            return '******';
        default:
            return value;
    }

    function matchValue(value) {
        for (let ops of options) {
            if (ops.value === value) {
                return ops.text;
            }
        }
        return value;
    }
}

/**
 *
 * 合并字段配置以及查询列表的字段配置
 * @param formInfo
 * @returns {any}
 */
function getTableHeaders(formInfo) {
    let fieldConfig = JSON.parse(formInfo.fieldConfig);
    if (formInfo.queryConfig) {
        let queryConfig = JSON.parse(formInfo.queryConfig);
        // 先进行排序并过滤不需要显示的字段
        queryConfig = queryConfig.filter(conf => conf.display);
        return fieldSort(queryConfig).map(conf => {
            for (let cc of fieldConfig) {
                if (cc.fieldId === conf.fieldId) {
                    Object.assign(conf, cc);
                    break;
                }
            }
            return conf;
        });
    }
    return fieldSort(fieldConfig);
}

/**
 * 字段排序
 * @param fieldList
 */
function fieldSort(fieldList = []) {

    return fieldList.sort((a, b) => a.fieldId > b.fieldId)
        .sort((a, b) => {
            if (a.headerOrder !== undefined && b.headerOrder !== undefined) {
                return a.headerOrder * 1 - b.headerOrder * 1
            }
            return 0 - 1;
        });
}
