const moment = require('moment')
const orm = require('./orm')


function test_month(str) {
    let a = which_month()
    let b = which_month(str)
    if (a == b) {
        return true
    } else {
        return false
    }
}

function which_month(str = null) {
    let today = moment()
    if (str) {
        today = moment(str)
    }
    let day = today.get('date')
    if (day > 6) {
        return today.format('YYYY-MM')
    } else {
        return today.subtract(1, 'month').format('YYYY-MM')
    }
}

async function test_order_id(order_id) {
    try {
        if (!order_id) {
            throw new Error('无效的订单号')
        }
        let ret = true
        let t = order_id.slice(0, 17)
        let append = order_id.slice(17)
        if (/[^0-9a-zA-Z_-]/.test(append) || order_id.length != 32 || /[^\d]/.test(t)) {
            throw new Error('无效的订单号')
        }
        return await orm.check_order_id(order_id)
    } catch (e) {
        throw e
    }
}


function to_base64(str) {
    return new Buffer(str).toString('base64')
}

function from_base64(base64) {
    return new Buffer(base64, 'base64').toString()
}

//  加权随机
function load_balance(items) {
    let list = []
    for (let item of items) {
        for (let i = 0; i < item.weight; i++) {
            list.push(item.app_id)
        }
    }
    let randint = getRandomInt(0, list.length)
    return list[randint]
}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}


module.exports = {
    test_order_id,
    test_month,
    which_month,
    to_base64,
    from_base64,
    load_balance
}