import { getArrValue } from 'js-fast-way'
import { getDictionary } from '~api/other'

/**
 * 效验是否为数字或小数的数字
 * @param text  字符串内容
 * @param lose  是否允许负数，默认允许
 * @returns {boolean}
 */
export const isNumberReg = (text, lose = true) => {
    let pattern = lose ? /^-?\d+(.\d{1,2})?$/ : /^[0-9]+([.]{1}[0-9]+){0,1}$/
    return pattern.test(text)
}

//获取字典数据
export const getDictionaryData = async (code) => {
    const { data } = await getDictionary({ code: code })
    //处理数据
    let newArr = []
    const newData = getArrValue(data)
    for (let i = 0; i < newData.length; i++) {
        newArr.push({
            label: newData[i]['dictValue'],
            value: Number(newData[i]['dictKey']),
        })
    }
    return newArr
}

//操作确认
export const actionConfirm = (cbk) => {
    window?.$messageBox?.alert('请确认要执行此操作吗？', '操作确认', {
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        callback: (action) => {
            if (action === 'confirm') {
                cbk()
            }
        },
    })
}

//删除提醒
export const delMessage = (cbk) => {
    window?.$messageBox?.alert('请谨慎考虑后，确认是否需要删除？', '删除提醒', {
        showCancelButton: true,
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        callback: (action) => {
            if (action === 'confirm') {
                cbk()
            }
        },
    })
}

//动态加载线上js文件
export const addDocumentsJs = () => {
    return new Promise((resolve) => {
        const script = document.createElement('script')
        script.src = 'http://47.110.251.215:6831/web-apps/apps/api/documents/api.js'
        script.type = 'text/javascript'
        document.head.appendChild(script)
        script.onload = () => {
            resolve()
        }
    })
}

//判断是否为网址
export const isPathUrl = (path) => {
    return /^(https?:|mailto:|tel:)/.test(path)
}


//获取当前域名
export const getTopUrl = () => {
    return window.location.href.split('/#/')[0]
}

//设置系统名称
export const setAppName = (name) => {
    const title = window.document.title
    window.document.title = `${title}${name ? ' - ' + name : ''}`
}
