import { useLocaleStoreWithOut } from '@/store/modules/locale'

/**
 * 对字符串函数的内容进行格式化
 * @param strFun 字符串函数
 */
export const formattingStrFunction = (strFun) => {
  if (import.meta.env.PROD) strFun = strFun.replace(/console\.log/g, '//console.log')
  strFun = strFun.replace(/(?<!['"])(?<!http:|https:)\/\/[^\n"']*(?=\n)\n/g, '\n')
  strFun = strFun.replace(/(?<!['"])(?<!http:|https:)\/\/[^\n"']*(?=\r)\r/g, '\n')
  strFun = strFun.replace(/\/\*{1,2}[\s\S]*?\*\//gis, '')
  strFun = strFun.replace(/(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/g, '')
  return strFun
}
/**
 * 解析字符串函数
 * @param strFun 字符串函数
 */
export const analysisStrFunction: (strFun: string) => ((callData?: object) => object | void) | boolean = (strFun) => {
  strFun = formattingStrFunction(strFun)
  try {
    return eval(`(${strFun})`)
  } catch (error) {
    setTimeout(() => { console.error(error) });
    return false
  }
}

/**
 * 解析字符串对象
 * @param strObj 字符串对象
 * @param errTip 解析错误提示文本
 * @param callData 字符串对象内部可用值/方法
 */
export const handleStrObj: (strObj: string, errTip?: string, callData?: object) => object = (strObj, errTip, callData) => {
  try {
    const fun = analysisStrFunction(`function getData(callData){ 
      ${strObj}
     }`)
    if (typeof fun == 'boolean') {
      console.warn(errTip)
      return {}
    }
    const obj = fun(callData)
    if (obj instanceof Object) return obj
    return {}
  } catch (error) {
    return {}
  }
}

/**
 * 深结构取值
 * @param obj 数据源
 * @param path 路径
 */
export const getDeepValue = (obj, path) => {
  if (!path) return ''
  return path.split('.').reduce((acc, key) => acc && acc[key], obj)
}

/**
 * 格式化语言配置
 * @param langStr 国际化配置
 * @param fieldName 默认语言文本
 */
export const formattingLengStr = (langStr, fieldName?) => {
  const localeStore = useLocaleStoreWithOut()
  const langObj = langStr ? handleStrObj(langStr) : {}
  langObj['zh-CN'] = fieldName
  const textList: string[] = []
  localeStore.localeMap.forEach(item => {
    const { lang, name } = item
    textList.push(`//${name}`)
    textList.push(`'${lang}': '${langObj[lang] || ''}',`)
    delete langObj[lang]
  })
  for (const key in langObj) {
    textList.push(`${key}: '${langObj[key] || ''}',`)
  }
  return `return {
  ${textList.join('\n  ')}
}`
}

/**
 * 组装语言数据
 * @param list 数据源
 * @param i18nKey 国际化配置key
 * @param codeKey 编码key
 * @param defTextKey 默认文本key
 */
export const assembleLengObj = (list, i18nKey, codeKey, defTextKey, childKey?): object => {
  const lengObj = {}
  const setLeng = (data) => {
    const labelI18n = getDeepValue(data, i18nKey)
    const codeVal = data[codeKey]
    const defTextVal = data[defTextKey]
    if (labelI18n) {
      const obj = handleStrObj(labelI18n)
      for (const key in obj) {
        if (!lengObj[key]) lengObj[key] = {}
        lengObj[key][codeVal] = obj[key]
      }
    }
    if (!lengObj['zh-CN']) lengObj['zh-CN'] = {}
    lengObj['zh-CN'][codeVal] = defTextVal

    if (childKey && data[childKey]) {
      data[childKey]?.forEach(child => setLeng(child))
    }
  }
  list.forEach(item => setLeng(item))
  return lengObj
}


//获取字典文本格式化替换字典列表
export const getDicFormatterKeyList = ({ dictTextFormatter, dictCode, dictText }) => {
  const dicKeyList = dictTextFormatter.match(/\{([^}]+)\}/g).map(match => {
    const replaceKey = match.replace(/[{}]/g, '')
    let valueKey = replaceKey
    if (valueKey == 'dicCode') valueKey = dictCode
    else if (valueKey == 'dicText') valueKey = dictText
    return {
      replaceKey,
      valueKey,
    }
  })
  return dicKeyList
}
//替换字典文本
export const dicItemFormatterFun = (item, keyList, { dictTextFormatter, dictText }) => {
  item.originalDicText = item[dictText]
  keyList.forEach(({ replaceKey, valueKey }) => {
    dictTextFormatter = dictTextFormatter.replace(`{${replaceKey}}`, item[valueKey] !== undefined ? item[valueKey] : '')
  })
  item[dictText] = dictTextFormatter
  return item
}