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

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

//取数组中的值
export const getRowsValue = (arr, key, key2, value) => {
    if (value) {
        const index = arrIndex(arr, key, value)
        return arr[index][key2]
    } else {
        return ''
    }
}

//日期格式化
export const dateFormat = (date, format) => {
    format = format || 'yyyy-MM-dd hh:mm:ss'
    if (date !== 'Invalid Date') {
        let o = {
            'M+': date.getMonth() + 1, //month
            'd+': date.getDate(), //day
            'h+': date.getHours(), //hour
            'm+': date.getMinutes(), //minute
            's+': date.getSeconds(), //second
            'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
            'S': date.getMilliseconds(), //millisecond
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
        }
        for (let 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
    }
    return ''
}

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

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

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

//判断起止时间是否为1个月
export const isExactlyOneMonthApart = (dateStr1, dateStr2)=> {
    // 将日期字符串转换为 Date 对象
    const date1 = new Date(dateStr1)
    const date2 = new Date(dateStr2)

    // 获取两个日期的年、月、日
    const year1 = date1.getFullYear()
    const month1 = date1.getMonth()
    const day1 = date1.getDate()

    const year2 = date2.getFullYear()
    const month2 = date2.getMonth()
    const day2 = date2.getDate()

    // 计算日期差值（以毫秒为单位）
    const diff = Math.abs(date2 - date1)

    // 计算日期相差的天数
    const daysDiff = Math.ceil(diff / (1000 * 60 * 60 * 24))

    // 判断日期相差的天数是否等于一个月的天数
    const daysInMonth1 = new Date(year1, month1 + 1, 0).getDate() // 当月的天数
    const daysInMonth2 = new Date(year2, month2 + 1, 0).getDate() // 下个月的天数

    return daysDiff === daysInMonth1 || daysDiff === daysInMonth2
}


