import { ElMessage } from 'element-plus';
export function formatter(num) {
  if (isNaN(num) || !num) return 0;
  let n = num.toString().split('.');
  let number = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  if (n[1]) number = number + '.' + n[1];
  return number;
}

export function copyurl(text) {
  if (!('clipboard' in navigator)) return;
  auth()
    .then(res => {
      if (!res) {
        // 未授权
        ElMessage({
          type: 'error',
          message: '授权未通过',
        });
        return;
      }
      navigator.clipboard.writeText(text).then(
        () => {
          ElMessage({
            type: 'success',
            message: '地址复制成功',
          });
        },
        () => {
          ElMessage({
            type: 'error',
            message: '复制失败',
          });
        }
      );
    })
    .catch(() => {
      ElMessage({
        type: 'error',
        message: '授权未通过',
      });
    });
}

const auth = () => {
  return new Promise((resolve, reject) => {
    navigator.permissions.query({ name: 'clipboard-read' }).then(
      result => {
        if (result.state == 'granted' || result.state == 'prompt') {
          resolve(true);
        } else {
          resolve(false);
        }
      },
      error => {
        reject(error);
      }
    );
  });
};
