import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router';
import type { App, Plugin } from 'vue';
import { useUserStore } from '@/stores/user'
import { useI18n } from 'vue-i18n'

import { unref } from 'vue';
import { isObject } from '@/utils/is';
import type { Component } from 'vue';

export const noop = () => { };
declare type TargetContext = '_self' | '_blank';
declare type Recordable<T = any> = Record<string, T>;
/**
 * @description:  Set ui mount node
 */
export function getPopupContainer(node?: HTMLElement): HTMLElement {
  return (node?.parentNode as HTMLElement) ?? document.body;
}

/**
 * Add the object as a parameter to the URL
 * @param baseUrl url
 * @param obj
 * @returns {string}
 * eg:
 *  let obj = {a: '3', b: '4'}
 *  setObjToUrlParams('www.baidu.com', obj)
 *  ==>www.baidu.com?a=3&b=4
 */
export function setObjToUrlParams(baseUrl: string, obj: any): string {
  let parameters = '';
  for (const key in obj) {
    parameters += key + '=' + encodeURIComponent(obj[key]) + '&';
  }
  parameters = parameters.replace(/&$/, '');
  return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters;
}

export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
  let key: string;
  for (key in target) {
    src[key] = isObject(src[key]) ? deepMerge(src[key], target[key]) : (src[key] = target[key]);
  }
  return src;
}

export function openWindow(
  url: string,
  opt?: { target?: TargetContext | string; noopener?: boolean; noreferrer?: boolean },
) {
  const { target = '__blank', noopener = true, noreferrer = true } = opt || {};
  const feature: string[] = [];

  noopener && feature.push('noopener=yes');
  noreferrer && feature.push('noreferrer=yes');

  window.open(url, target, feature.join(','));
}

// dynamic use hook props
export function getDynamicProps<T, U>(props: T): Partial<U> {
  const ret: Recordable = {};

  Object.keys(props).map((key) => {
    ret[key] = unref((props as Recordable)[key]);
  });

  return ret as Partial<U>;
}

export function getRawRoute(route: RouteLocationNormalized): RouteLocationNormalized {
  if (!route) return route;
  const { matched, ...opt } = route;
  return {
    ...opt,
    matched: (matched
      ? matched.map((item) => ({
        meta: item.meta,
        name: item.name,
        path: item.path,
      }))
      : undefined) as RouteRecordNormalized[],
  };
}

export const withInstall = <T>(component: T, alias?: string) => {
  const comp = component as any;
  comp.install = (app: App) => {
    app.component(comp.name || comp.displayName, component);
    if (alias) {
      app.config.globalProperties[alias] = component;
    }
  };
  return component as T & Plugin;
};
//请求微信接口，用来获取code
export async function getWeChatCode(appid:string) {
  const local = encodeURIComponent(window.location.href) //一定要用encodeURIComponent方法获取当前页面地址作为回调地址
  //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
  window.location.href =
    'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
    appid +
    '&redirect_uri=' +
    local +
    '&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect&connect_redirect=1'
}

export function GetRequest(value: string) {
  var url = decodeURI(window.location.search); //?id="123456"&name="www";
  var object = {};
  if (url.indexOf("?") != -1)//url中存在问号，也就说有参数。  
  {
    var str = url.substr(1);  //得到?后面的字符串
    var strs = str.split("&");  //将得到的参数分隔成数组[id="123456",name="www"];
    for (var i = 0; i < strs.length; i++) {
      object[strs[i].split("=")[0]] = strs[i].split("=")[1];//得到{id:'123456',name:'www'}
    }
  }
  console.log('GetRequest', object)
  return object[value];
}

//支付备注
export const getRemark = (list, orderType, t) => {
  
// const { locale, t } = useI18n()
const { isEur } = useUserStore()
  let str = []
  list.map(item => {
    let newStr = ''
    if (orderType == 'cooperationOrder') {
      newStr = t('mall.cooperationOrderName',{count: item.count })
    } else if (orderType == 'downOrder') {
      newStr = `${item.name} (${item.sceneNum})`
    } else if (orderType != 'incrementOrder') {
      newStr = `${locale.value == 'zh' ? item.name : item.nameEn}`
    } else {
      newStr = `${item.type == 1 ? t('payInfo.gjhy') : isEur ? t('payInfo.zyhys') : t('payInfo.zyhy')}`
    }
    if(orderType != 'cooperationOrder' && orderType != 'downOrder'){
      newStr += `x ${item.count}` 
    }
    
    if(orderType == 'incrementOrder'){
      newStr += `，${item.type?t(`payInfo.expirationmon`, { num: item.monthQy || 1 }):t(`payInfo.expiration`, { num: 1 })}` 
    }
    str.push(newStr)
  })
  return str.join('、')
}