'use strict';

/**
 * 辅助方法扩展
 *
 * @author CaiAoLin
 * @date 2017/9/28
 * @version
 */
module.exports = {
    /**
     * 内置验证器转换为前端jquery验证器
     *
     * @param {Object} rule - 后端service中的rule
     * @return {Object} - 返回转换后的数据
     */
    validateConvert(rule) {
        const result = {};
        if (Object.keys(rule).length <= 0) {
            return rule;
        }

        for (const index in rule) {
            result[index] = {};
            const type = rule[index].type !== undefined && rule[index].type !== '' ? rule[index].type : '';
            const stringType = ['string', 'password'];
            // 是否必填
            if (rule[index].required !== undefined) {
                result[index].required = rule[index].required;
            }

            // 最小长度
            if (stringType.indexOf(type) >= 0 && rule[index].min !== undefined) {
                result[index].minlength = rule[index].min;
            }

            // 最大长度
            if (stringType.indexOf(type) >= 0 && rule[index].max !== undefined) {
                result[index].maxlength = rule[index].max;
            }

            // 密码相关
            if (type === 'password' && rule[index].compare !== undefined) {
                result[index].equalTo = '#' + rule[index].compare;
            }

            // 最小值
            const integerType = ['integer', 'int', 'Number'];
            if (integerType.indexOf(type) >= 0 && rule[index].min !== undefined) {
                result[index].min = rule[index].min;
            }

            // 最大值
            if (integerType.indexOf(type) >= 0 && rule[index].max !== undefined) {
                result[index].max = rule[index].max;
            }

            // 自定义判断
            if (rule[index] === 'isMobile' || rule[index] === 'isIP') {
                result[index] = rule[index];
            }

        }

        return result;
    },

    /**
     * 生成随机字符串
     *
     * @param {Number} length - 需要生成字符串的长度
     * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
     * @return {String} - 返回生成结果
     */
    generateRandomString(length, type = 1) {
        length = parseInt(length);
        length = isNaN(length) ? 1 : length;
        let randSeed = [];
        let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
            'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

        switch (type) {
            case 1:
                randSeed = stringSeed.concat(numberSeed);
                stringSeed = numberSeed = null;
                break;
            case 2:
                randSeed = numberSeed;
                break;
            case 3:
                randSeed = stringSeed;
                break;
            default:
                break;
        }

        const seedLength = randSeed.length - 1;
        let result = '';
        for (let i = 0; i < length; i++) {
            const index = Math.ceil(Math.random() * seedLength);
            result += randSeed[index];
        }

        return result;
    },

    /**
     * 显示排序符号
     *
     * @param {String} field - 字段名称
     * @return {String} - 返回字段排序的符号
     */
    showSortFlag(field) {
        const sort = this.ctx.sort;
        if (!(sort instanceof Array) || sort.length !== 2) {
            return '';
        }
        sort[1] = sort[1].toUpperCase();
        return (sort[0] === field && sort[1] === 'DESC') ? '' : '-';
    },

    /**
     * 判断是否为ajax请求
     *
     * @param {Object} request - 请求数据
     * @return {boolean} 判断结果
     */
    isAjax(request) {
        let headerInfo = request.headers['x-requested-with'] === undefined ? '' : request.headers['x-requested-with'];
        headerInfo = headerInfo.toLowerCase();
        return headerInfo === 'xmlhttprequest';
    },

    /**
     * 模拟发送请求
     *
     * @param {String} url - 请求地址
     * @param {Object} data - 请求数据
     * @param {String} type - 请求类型(POST) POST | GET
     * @return {Object} - 请求结果
     */
    async sendRequest(url, data, type = 'POST') {
        // 发起请求
        const response = await this.ctx.curl(url, {
            method: type,
            data,
            dataType: 'json',
        });
        if (response.status !== 200) {
            throw '请求失败';
        }

        return response.data;
    },

};
