import {Base64} from 'js-base64'
import {ref} from 'vue'
import { showToast } from 'vant'


// 导出静态图片资源
export function getStaticImg(path){
    return new URL(`../assets/imgs/${path}`, import.meta.url).href
}

// 获取个人信息
export function useUserInfo(){
    let userInfo=ref(null)
    userInfo.value=localStorage.getItem('userInfo')?JSON.parse(Base64.decode(localStorage.getItem('userInfo'))):null
    return userInfo
}

// 是否为微信浏览器
export function isWeiXin(){
    const ua = navigator.userAgent.toLowerCase();
    const flag = ua.indexOf('micromessenger') != -1;
    if(flag){
        console.log('在微信浏览器中', flag)
    }
    return flag
}

/**
 * 将远程图片转化为base64
 * url 远程图片地址
 */
export function transfImgTobase64(url) { 
    return new Promise((resolve,reject)=>{
        const image = new Image();
        image.crossOrigin = 'Anonymous';
        image.onload =()=>{
            const canvas = document.createElement('canvas');
            canvas.width = image.width;
            canvas.height = image.height;

            const context = canvas.getContext('2d');
            context.drawImage(image, 0, 0);

            const base64 = canvas.toDataURL('image/png');

            resolve(base64)
        }
        image.onerror = function (e) {
            console.log('图片加载失败',e);
            
            resolve(url);
            throw new Error(JSON.stringify(e))
        };
        image.src = url;
    })
}

/**
 * 设置剪切板
 * @param text 文本
 * @param msg 提示文案
 */
export async function setClipboardData(text,msg){
    if(navigator.clipboard&&window.isSecureContext){
        try{
           await navigator.clipboard.writeText(text)
           showToast({message:msg||'复制链接成功',type:'success'})
       }catch(err){
           console.log(err);
           throw new Error(JSON.stringify(err)) 
           showToast({message:msg||'复制失败',type:'fail'})
       }
   }else{
       const input = document.createElement('input')
       input.setAttribute('readonly','readonly')
       input.value = text
       document.body.appendChild(input)
       input.select();
       document.execCommand('copy');
       document.body.removeChild(input);
       showToast({message:msg||'复制链接成功',type:'success'})
   }
}