
import { getAll } from '/@/api/sys/index'

function formatDate(timestamp: any, isday: any) {
    if(timestamp == '' || timestamp == null){
        return  ''
    }
    let date = new Date(timestamp);
    let y = date.getFullYear();
    let m: string | number = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d: string | number = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h: string | number = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let minute: string | number = date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    let second: string | number = date.getSeconds();
    second = second < 10 ? ('0' + second) : second;
    if (isday) {
        return y + '-' + m + '-' + d;
    } else {
        return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
    }

}


function toThousands(num = 0) {
    return num.toString().replace(/\d+/, function (n) {
        return n.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    });
};

async function download(file: any, name: string) {
    // 下载excel
    let download: any = await getAll().download(file);
    let blob = new Blob([download], { type: "application/octet-stream;" });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `${name}.xlsx`;
    document.body.appendChild(link);
    link.click();
};


// 转为万元
function formatNumber(num: string | number) {
    num = Number(num);
    if (num == 0) {
        return num + "";
    } else {
        if ((num / 10000).toFixed(2) == "0") {
            //小于100的保留2位
            return (num / 100).toFixed(4)
        } else {
            // parseFloat() 去掉后面不用的0，如50.00
            //大于100的保留2位
            return parseFloat((num / 10000).toFixed(2))
        }
    }
}

// 转为亿元或者元万元,根据数字长度来
function unitConvert(num: any) {
    var moneyUnits = ["元", "万元", "亿元"]
    var dividend = 10000;
    var curentNum = num;
    //转换数字
    var curentUnit = moneyUnits[0];
    //转换单位
    for (var i = 0; i < moneyUnits.length; i++) {
        curentUnit = moneyUnits[i]
        if (strNumSize(curentNum) < 5) {
            break;
        }
        curentNum = curentNum / dividend
    }
    var m = { num: 0, unit: "" }
    m.num = curentNum.toFixed(2)
    m.unit = curentUnit;
    return m;
}

function strNumSize(tempNum: any) {
    var stringNum = tempNum.toString()
    var index = stringNum.indexOf(".")
    var newNum = stringNum;
    if (index != -1) {
        newNum = stringNum.substring(0, index)
    }
    return newNum.length
}
// 数字转换
function numFormat(num: string | number, type: number) {
    if (type == 0) {
        // 转为亿元
        let nums = unitConvert(num).num;
        let c = (nums.toString().indexOf('.') !== -1) ? nums.toLocaleString() : nums.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
        return c;
    }
    else if (type == 1) {
        // 转为万元
        let nums = formatNumber(num);
        let c = (nums.toString().indexOf('.') !== -1) ? nums.toLocaleString() : nums.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
        return c;
    }
    else {

        if(num == 0 || num == null){
            return '0.00'
        }
        num = num == undefined ? 0 : num
        // 不转加逗号
        let c = (num.toString().indexOf('.') !== -1) ? num.toLocaleString() : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
        return c;
    }
}

// 向上取整或者向下取整
function formatInt(num: number, prec: number = 2, ceil: boolean = true) {
    // num：数值；prec：向上取整多少位，默认为2位；ceil：true-向上，false-向下；
    const len = String(num).length;
    if (len <= prec) { return num }
    const mult = Math.pow(10, prec);
    return ceil ? Math.ceil(num / mult) * mult : Math.floor(num / mult) * mult;
}

// 获取当前日期或者选定日期的前12个月
function getLastYearMonthArray(date: Date, type:any) {//type 是销售分析（获取上一月） 可以不传
    let result = [];
    let d = new Date();
    if (date != undefined) d = date;
    let year = d.getFullYear();
    if (type || type == undefined) {
        d.setMonth(d.getMonth() + 1, 1);
    } else {
        d.setMonth(d.getMonth(), 1);
    }
    for (let i = 0; i < 12; i++) {
        d.setMonth(d.getMonth() - 1);
        let m: any = d.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        result.push(d.getFullYear() + "-" + m);
    }
    return result.reverse(); // 返回反向排列数组
}

function atchFileSuffixType(fileName: string) {
    // 后缀获取
    var suffix = ''
    // 获取类型结果
    var result: any = ''
    try {
        var flieArr = fileName.split('.')
        suffix = flieArr[flieArr.length - 1]
    } catch (err) {
        suffix = ''
    }
    // fileName无后缀返回 false
    if (!suffix) {
        result = false
        return result
    }
    // 图片格式
    var imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp']
    // 进行图片匹配
    result = imglist.some(function (item) {
        return item == suffix
    })
    if (result) {
        result = 'image'
        return result
    }
    // 匹配txt
    var txtlist = ['txt']
    result = txtlist.some(function (item) {
        return item == suffix
    })
    if (result) {
        result = 'txt'
        return result
    }
    // 匹配 excel
    var excelist = ['xls', 'xlsx']
    result = excelist.some(function (item) {
        return item == suffix
    })
    if (result) {
        result = 'excel'
        return result
    }
    // 匹配 word
    var wordlist = ['doc', 'docx']
    result = wordlist.some(function (item) {
        return item == suffix
    })
    if (result) {
        result = 'word'
        return result
    }
    // 匹配 pdf
    var pdflist = ['pdf']
    result = pdflist.some(function (item) {
        return item == suffix
    })
    if (result) {
        result = 'pdf'
        return result
    }
    // 匹配 ppt
    var pptlist = ['ppt']
    result = pptlist.some(function (item) {
        return item == suffix
    })
    if (result) {
        result = 'ppt'
        return result
    }
    // 匹配 视频
    var videolist = ['mp4', 'm2v', 'mkv']
    result = videolist.some(function (item) {
        return item == suffix
    })
    if (result) {
        result = 'video'
        return result
    }
    // 匹配 音频
    var radiolist = ['mp3', 'wav', 'wmv']
    result = radiolist.some(function (item) {
        return item == suffix
    })
    if (result) {
        result = 'radio'
        return result
    }
    // 其他 文件类型
    result = 'other'
    return result
}


export default {
    formatDate,
    download,
    toThousands,
    numFormat,
    formatInt,
    getLastYearMonthArray,
    atchFileSuffixType
}
