import DGTMessage from '@/utils/message'
import { signUp } from '@/api/apply.js'
import { ElMessageBox,ElLoading } from 'element-plus'
import { createOrder } from '@/api/order.js'
export function downloadFile({url, fileName='download',t}) {
  if (!url) {
    DGTMessage.error(t('common.fileAddressNotExist'));
    return;
  }
  const link = document.createElement('a');
  link.href = url;
  link.download = fileName || '';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

export async function submitSignUp(formData,t,callback) {
  try {
    const response = await signUp(formData);
    if (response.code === 200) {
      DGTMessage.success(t('workflowTrade.signUpSuccess'));
      if(callback && typeof callback === 'function'){
        callback();
      }
      return response.data;
    } else {
      // DGTMessage.error(response.msg || t('workflowTrade.signUpFailed'));
      return null;
    }
  } catch (error) {
    return null;
  }   
}
//截止日期转化为天数和小时
export function formatDeadline(deadline) {
  if (!deadline || isNaN(Date.parse(deadline))) {
    return {diffDays:0,diffHours:0};
  }
  const now = new Date();
  const deadlineDate = new Date(deadline);
  const diffTime = deadlineDate - now;
  //负数直接返回0
  if(diffTime <=0){
    return {diffDays:0,diffHours:0};
  }
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  const diffHours = Math.ceil(diffTime / (1000 * 60 * 60)) % 24;
  return {diffDays,diffHours};
}
//type: pointsBalance  pointsBalance
export function confirmBuy({
  type='baoMiBalance',
  price=0,
  callback,
  callbackParams=null,
  appStore,
  router,
  t,
  payMethod,
  orderType,
  productId,
  paySuccessMsg=t('common.paySuccess')
}){
  const balance = appStore.userInfo?.[type] || 0;
  if(balance < price ){
    ElMessageBox.confirm(t('common.balanceNotEnoughRecharge'), t('common.tip'), {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    }).then(() => {
      // 确认购买
      router.push({
        path: `/order-confirm`,
      })
    }).catch(() => {
      // 取消购买
    });
  }else{
    const unit = type === 'baoMiBalance' ? t('common.baomibi') : t('common.mibi');
    const ms = `${t('common.payNow')} ${price} ${unit}？`
    ElMessageBox.confirm(ms, t('common.tip'), {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    }).then(async () => {
      const res = await createOrder({
        payMethod,
        orderType,
        orderAmt:price,
        productId,
        orderNum:1
      })
      if(res.code === 200){
        // DGTMessage.success(t('common.buy')+t('common.success'));
        paySuccess({t,msg:paySuccessMsg});
        //刷新用户信息,主要是更新余额
        appStore.USERINFO();
        if(callback && typeof callback === 'function'){
          callback(callbackParams);
        }
      }else{
        // DGTMessage.error(res.msg || t('common.buy')+t('common.fail'));
      }
      
    }).catch(() => {
      // 取消购买
    });
  }
}
//判断是否登录
export function isLogin({callback,t}){
  let token = localStorage.getItem('token');
  if(!token){
    //确认弹框
    ElMessageBox.confirm(t('common.notLoginTip'), t('common.tip'), {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    }).then(() => {
      // 确认购买
      if(callback && typeof callback === 'function'){
        callback();
      }
    }).catch(() => {
      // 取消购买
    });
    return false;
  }
  return true;
}
//复制功能
export function copyText(text, t, msg=t('common.copySuccess')) {
  if (!text) {
    DGTMessage.error(t('common.copyError'));
    return;
  }
  const input = document.createElement('input');
  input.value = text;
  document.body.appendChild(input);
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
  DGTMessage.success(msg);
}

// 支付成功确认弹框
export function paySuccess({t,callback,msg=t('common.paySuccess')}){
  ElMessageBox.alert(msg, t('common.tip'), {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: t('common.confirm'),
    callback: (action) => {
       if(callback && typeof callback === 'function'){
        callback();
      }
    },
  })
};
//全局loading封装
export function openFullScreenLoading() {
  const loading = ElLoading.service({
    target: '.container',
    lock: true,
    // text: 'Loading',
    // background: 'rgba(0, 0, 0, 0.7)',
  })
  return loading;
}
//打开新标签跳转地址
export function openNewTab(url) {
  if (!url) {
    return;
  }
  window.open(url, '_blank');
}
