// nuxt 3 - plugins/my-plugin.ts import { useRoute } from 'vue-router' import { useStore } from '~/stores/index' import dayjs from 'dayjs' import weekday from 'dayjs/plugin/weekday' import weekOfYear from 'dayjs/plugin/weekOfYear' import relativeTime from 'dayjs/plugin/relativeTime' dayjs.extend(weekday) dayjs.extend(weekOfYear) dayjs.extend(relativeTime) export default defineNuxtPlugin(() => { const route = useRoute() const {$id, $empty} = useNuxtApp() const store = useStore() const dialog = function(content, title, type, duration, width, height, vbind) { content = typeof content === 'string'? content : JSON.stringify(content) let vtitle = type==='Success'? `${title}` : title if(type==='Error') vtitle = `${title}` let data = {id: $id() , component: `dialog/${type || 'Info'}`, vbind: {content: content, duration: duration, vbind: vbind}, title: vtitle, width: width || '600px', height: height || '100px'} store.commit('showmodal', data) } const snackbar = function(content, title, type, width, height) { content = typeof content == 'string'? content : JSON.stringify(content) let vtitle = type==='Success'? `${title}` : title if(type==='Error') vtitle = `${title}` let data = {id: $id() , component: `snackbar/${type || 'Info'}`, vbind: {content: content}, title: vtitle, width: width || '600px', height: height || '100px'} store.commit('snackbar', data) } const getLink = function(val) { if(val === undefined || val === null || val === '' || val==="") return '' let json = val.indexOf('{')>=0? JSON.parse(val) : {path: val} return json } const errPhone = function(phone) { var text = undefined if ($empty(phone)) { text = 'Số điện thoại di động không được bỏ trống.' } else if (isNaN(phone)) { text = 'Số điện thoại di động không hợp lệ.' } else if(phone.length<9 || phone.length>11) { text = 'Số điện thoại di động phải từ 9-11 số.' } return text } const errEmail = function(email) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ var text = undefined if ($empty(email)) { text = 'Email không được bỏ trống.' } else if (!(re.test(String(email).toLowerCase()))) { text = 'Email không hợp lệ.' } return text } const errPhoneEmail = function(contact) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ var text = undefined if ($empty(contact)) { text = 'Số điện thoại di động hoặc Email không được bỏ trống.' } else if (!(re.test(String(contact).toLowerCase()) || !isNaN(contact))) { text = 'Số điện thoại di động hoặc Email không hợp lệ.' } else if(!isNaN(contact) && (contact.length<9 || contact.length>11)) { text = 'Số điện thoại di động không hợp lệ.' } return text } const upload = function(file, type, user, convert) { var fileFormat = [{type: 'image', format: ['.png', '.jpg', 'jpeg', '.bmp', '.gif', '.svg', '.webp']}, {type: 'video', format: ['.wmv', '.avi', '.mp4', '.flv', '.mov', '.mpg', '.amv', '.rm']} ] var valid = undefined if(type==='image' || type==='video') { valid = false let found = fileFormat.find(v=>v.type===type) found.format.map(x=>{ if(file.name.toLowerCase().indexOf(x)>=0) valid = true }) } if(valid===false) return {name: file.name, error: true, text: 'Định dạng file không hợp lệ'} if((type==='image' || type==='file') && file.size > 500*1024*1024) { return {name: file.name, error: true, text: 'Kích thước ' + (type==='image'? 'hình ảnh' : 'tài liệu') + ' phải dưới 500MB'} } else if(type==='video' && file.size > 1073741274) { return {name: file.name, error: true, text: 'Kích thước video phải dưới 1GB'} } let data = new FormData() let fileName = dayjs(new Date()).format("YYYYMMDDhhmmss") + '-' + nonAccent(file.name) data.append('name', file.name) data.append('filename', fileName) data.append('file', file) data.append('type', type) data.append('size', file.size) data.append('user', user) data.append('convert', convert) return {form: data, type: type, size: file.size, file: file, name: file.name, filename: fileName} } const checkChange = function(obj1, obj2, list) { var change = false if(list) { list.map(v=>{if(obj1[v]!==obj2[v]) change = true}) } else { for (var k in obj1 ) { if(obj1[k]!==obj2[k]) change = true } } return change } const resetNull = function(obj) { for (const [key, value] of Object.entries(obj)) { if(typeof value==='string') { let val = value.trim() if(val==='' || val==="") val = null obj[key] = val } } return obj } const copyToClipboard = function(text) { snackbar('Copied to clipboard') if (window.clipboardData && window.clipboardData.setData) { // IE specific code path to prevent textarea being shown while dialog is visible. return clipboardData.setData("Text", text); } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) { var textarea = document.createElement("textarea"); textarea.textContent = text; textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge. document.body.appendChild(textarea); textarea.select(); try { return document.execCommand("copy"); // Security exception may be thrown by some browsers. } catch (ex) { console.warn("Copy to clipboard failed.", ex); return false; } finally { document.body.removeChild(textarea); } } } const nonAccent = function(str) { if($empty(str)) return null str = str.replaceAll('/', '-').replaceAll('%', '-').replaceAll('?', '-') str = str.toLowerCase(); str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a"); str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e"); str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i"); str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o"); str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u"); str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y"); str = str.replace(/đ/g, "d"); // Some system encode vietnamese combining accent as individual utf-8 characters str = str.replace(/\u0300|\u0301|\u0303|\u0309|\u0323/g, ""); // Huyền sắc hỏi ngã nặng str = str.replace(/\u02C6|\u0306|\u031B/g, ""); // Â, Ê, Ă, Ơ, Ư str = str.split(' ').filter(s => s).join('-') return str } const linkID = function(link) { link = link? link : route.params.slug if($empty(link)) return let idx = link.lastIndexOf('-') let id = (idx>-1 && idx { for(var i = 0; i < elms.length; i++) { elms[i].style.display='block'; } }, 1000) return opt.filename } const exportImage = function(docid, name) { var element = document.getElementById(docid) let elms = element.querySelectorAll("[id='ignore']") for(var i = 0; i < elms.length; i++) { elms[i].style.display='none'; } let filename = `${name}-${dayjs().format('YYYYMMDDHHmmss')}.png` html2canvas(element).then(canvas => { const link = document.createElement("a"); link.href = canvas.toDataURL("image/png"); link.download = filename; link.click(); link.remove() }) setTimeout(()=> { for(var i = 0; i < elms.length; i++) { elms[i].style.display='block'; } }, 1000) return filename } const download = async function(url, fileName) { let name = dayjs(new Date()).format("YYYYMMDDhhmmss") + '-' + fileName const response = await fetch(url, { method: "GET" }); const blob = await response.blob(); const urlDownload = window.URL.createObjectURL(blob); const link = document.createElement("a"); link.href = urlDownload; link.setAttribute("download", name); link.click(); link.remove(); } const vnmoney = function(amount) { var readGroup = function (group) { let readDigit = [" Không", " Một", " Hai", " Ba", " Bốn", " Năm", " Sáu", " Bảy", " Tám", " Chín"]; var temp = ""; if (group == "000") return ""; temp = readDigit[parseInt(group.substring(0, 1))] + " Trăm"; if (group.substring(1, 2) == "0") if (group.substring(2, 3) == "0") return temp; else { temp += " Lẻ" + readDigit[parseInt(group.substring(2, 3))]; return temp; } else temp += readDigit[parseInt(group.substring(1, 2))] + " Mươi"; if (group.substring(2, 3) == "5") temp += " Lăm"; else if (group.substring(2, 3) != "0") temp += readDigit[parseInt(group.substring(2, 3))]; return temp; } var readMoney = function(num) { if ((num == null) || (num == "")) return ""; let temp = ""; while (num.length < 18) { num = "0" + num; } let g1 = num.substring(0, 3); let g2 = num.substring(3, 6); let g3 = num.substring(6, 9); let g4 = num.substring(9, 12); let g5 = num.substring(12, 15); let g6 = num.substring(15, 18); if (g1 != "000") { temp = readGroup(g1); temp += " Triệu"; } if (g2 != "000") { temp += readGroup(g2); temp += " Nghìn"; } if (g3 != "000") { temp += readGroup(g3); temp += " Tỷ"; } else if ("" != temp) { temp += " Tỷ"; } if (g4 != "000") { temp += readGroup(g4); temp += " Triệu"; } if (g5 != "000") { temp += readGroup(g5); temp += " Nghìn"; } temp = temp + readGroup(g6); temp = temp.replaceAll("Một Mươi", "Mười"); temp = temp.trim(); temp = temp.replaceAll("Không Trăm", ""); temp = temp.trim(); temp = temp.replaceAll("Mười Không", "Mười"); temp = temp.trim(); temp = temp.replaceAll("Mươi Không", "Mươi"); temp = temp.trim(); if (temp.indexOf("Lẻ") == 0) temp = temp.substring(2); temp = temp.trim(); temp = temp.replaceAll("Mươi Một", "Mươi Mốt"); temp = temp.trim(); let result = temp.substring(0, 1).toUpperCase() + temp.substring(1).toLowerCase(); return (result == "" ? "Không" : result) + " đồng chẵn" } return readMoney(amount.toString()) } const lang = function(code) { let field = store.common.find((v) => v.code===code) return field? field[store.lang] : '' } const createMeta = function(metainfo) { return { title: metainfo.title, link: [ { hid: 'canonical', rel: 'canonical', href: `https://y99.vn${route.path}` } ], meta: [ { hid: 'description', name: 'description', content: metainfo.description || '' }, { hid: 'og:title', property: 'og:title', content: metainfo.title }, { hid: 'og:description', property: 'og:description', content: metainfo.description || '' }, { hid: 'og:type', property: 'og:type', content: metainfo.type || '' }, { hid: 'og:image', property: 'og:image', content: metainfo.image || '' }, { hid: 'og:url', property: 'og:url', content: `https://y99.vn${route.path}` }, { property: 'og:locale', content: 'vi_VN' }, { hid: 'fb:app_id', property: 'fb:app_id', content: metainfo.app_id || '549555567061256' }, { hid: 'keywords', name: 'keywords', content: metainfo.keywords || '' } ] } } return { provide: { dialog, snackbar, getLink, errPhone, errEmail, errPhoneEmail, upload, checkChange, resetNull, copyToClipboard, nonAccent, linkID, exportpdf, exportImage, vnmoney, createMeta, download, dayjs, lang } } })