const useXState = (initState: any) => {
const [state, setState] = useState(initState)
let isUpdate = useRef<any>()
const setXState = (state: any, cb: any) => {
setState((prev: any) => {
isUpdate.current = cb
return typeof state === 'function' ? state(prev) : state
})
}
useEffect(() => {
if (isUpdate.current) {
isUpdate.current()
}
},[state])
return [state, setXState]
}
const [val, setVal] = useXState({})
setVal((oldVal)=>{return newVal},()=>{})
const downLoadFn = (url: string, fileName: string) => {
let newUrl = url
if (!url.includes('https')) {
newUrl = url.replace('http', 'https')
}
if (isImage(fileName)) {
window.location.href = newUrl
} else {
getBlob(newUrl).then(blob => {
saveAs(blob, fileName);
}).finally(() => {
});
}
}
function isImage(str: string) {
var reg = /\.(png|jpg|gif|jpeg|webp)$/
return reg.test(str)
}
const getBlob = (url: any) => {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
}
const saveAs = (blob: any, filename: any) => {
if (window.navigator?.msSaveOrOpenBlob) {
window.navigator?.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
const body = document.querySelector('body');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.style.display = 'none';
body?.appendChild(link);
link.click();
body?.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
}
const numberToChinese = (n: number) => {
var fraction = ['角', '分'];
var digit = [
'零', '壹', '贰', '叁', '肆',
'伍', '陆', '柒', '捌', '玖'
];
var unit = [
['元', '万', '亿'],
['', '拾', '佰', '仟']
];
var head = n < 0 ? '欠' : '';
n = Math.abs(n);
var s = '';
for (var i = 0; i < fraction.length; i++) {
s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
}
s = s || '整';
n = Math.floor(n);
for (var i = 0; i < unit[0].length && n > 0; i++) {
var p = '';
for (var j = 0; j < unit[1].length && n > 0; j++) {
p = digit[n % 10] + unit[1][j] + p;
n = Math.floor(n / 10);
}
s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
}
return head + s.replace(/(零.)*零元/, '元')
.replace(/(零.)+/g, '零')
.replace(/^整$/, '零元整');
}
function isCardId(s: string) {
return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|Xx)$)/.test(s)
}
const download = (res, type, filename) => {
const blob = new Blob([res], {
type: type
})
const a = document.createElement('a')
const URL = window.URL || window.webkitURL
const herf = URL.createObjectURL(blob)
a.href = herf
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(herf)
}
const arrOk = (start:Number, end:Number) => {
return [...Array(end - start+1)].map((item, index) => index + start)
}