import axios from 'axios'
import Vue from 'vue'
import { delayPerform } from 'js-perform-lock'

const WindowsTranslateApi = 'https://jiasm.zfire.top/translate'
// const WindowsTranslateApi = 'http://127.0.0.1:7001'

// 数据过滤校验
function isNumberRegex(str) {
  const regexPatterns = [
    /^\d+$/, // 纯数字
    /^\d*\.\d+$/, // 浮点数
    /^([01]\d|2[0-3]):([0-5]\d)$/, // 时间 (HH:MM)
    /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/, // 时间 (HH:MM:SS)
    /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/, // 完整时间戳
    /^[A-Za-z]+$/, // 纯字母
    /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]+$/, // 字母和数字
    /^(?=.*[A-Za-z])(?=.*[\p{P}\p{S}])[\p{L}\p{P}\p{S}]+$/u, // 字母和标点符号
    /^(?=.*\d)(?=.*[\p{P}\p{S}])[\d\p{P}\p{S}]+$/u, // 数字和标点符号
    /^[\p{P}\s\dA-Za-z]+$/u // 字母、数字和标点符号
  ]
  return regexPatterns.some(pattern => pattern.test(str)) || !!window.Vue_Translation_Of_Text_Old_Data[str]
}

// 文本转译请求
function pushNewText(data) {
  return new Promise(function (r, j) {
    axios
      .post(WindowsTranslateApi + '/api/v1/common/translationOfText', data)
      .then(response => {
        if (response.data.code === 0) {
          var obj = {}
          var obj2 = {}
          response.data.data.map(val => {
            obj[val[0]] = val[1]
            obj2[val[1]] = true
          })
          window.Vue_Translation_Of_Text_Old_Data = { ...(window.Vue_Translation_Of_Text_Old_Data || {}), ...obj2 }
          window.Vue_Translation_Of_Text_Data = { ...(window.Vue_Translation_Of_Text_Data || {}), ...obj }
          r({ ...obj })
        }
      })
      .catch(j)
  })
}

var deferredReplacement = (function () {
  var allKeywords = []
  var keywords = []
  var zhixingfun = []
  var index = 0
  var index2 = 0

  const dInit = new delayPerform(250).refactor(function () {
    let len = index
    let len2 = index2
    let keywords_ = keywords.splice(0, len)
    let zhixingfun_ = zhixingfun.splice(0, len2)
    index -= len
    index2 -= len2
    if (keywords_.length > 0) {
      pushNewText({
        keywords: keywords_,
        targetLanguage: window?.Vue_Translation_Of_Text_Type
      }).then(data => {
        for (var i = 0; i < len2; i++) {
          zhixingfun_?.[i]?.()
        }
      })
    } else if (zhixingfun_.length > 0) {
      setTimeout(function () {
        for (var i = 0; i < len2; i++) {
          zhixingfun_?.[i]?.()
        }
      }, 250)
    }
  })

  return function (text, cb) {
    dInit()
    if (!allKeywords.includes(text)) {
      index++
      allKeywords.push(text)
      keywords.push(text)
    }
    index2++
    zhixingfun.push(cb)
  }
})()

export const GlobalTextProcessor = {
  install(Vue) {
    Vue.mixin({
      updated() {
        this.$nextTick(() => {
          this.processTextNodes(this.$el)
          this.autoSelect('uni-tabbar-bottom')
        })
      },
      methods: {
        // 通过class修改
        autoSelect(name) {
          document.querySelectorAll(`.${name}`).forEach(element => {
            this.processAbsolutely(element)
          })
        },
        // 通过标签名修改
        autoHtmlSelect(name) {
          document.getElementsByTagName(name).forEach(element => {
            this.processAbsolutely(element)
          })
        },
        processTextNodes(el) {
          // 遍历子节点并处理文本内容
          if (el.nodeType === Node.ELEMENT_NODE) {
            // 跳过 table-body中的td 元素
            if (el.nodeName.toLowerCase() === 'td') {
              return
            }
            Array.from(el.childNodes).forEach(child => {
              if (child.nodeType === Node.TEXT_NODE) {
                let text = child.textContent
                let _child = child
                if (text && !isNumberRegex(text.trim())) {
                  try {
                    if (window?.Vue_Translation_Of_Text_Data?.[text.trim()]) {
                      child.textContent = window?.Vue_Translation_Of_Text_Data?.[text.trim()]
                    } else if (text.trim()) {
                      deferredReplacement(text.trim(), function () {
                        if (window.Vue_Translation_Of_Text_Data[text.trim()]) {
                          _child.textContent = window.Vue_Translation_Of_Text_Data[text.trim()]
                        }
                      })
                    }
                  } catch (error) {}
                }
              } else if (child.nodeName === 'INPUT' || child.nodeName === 'TEXTAREA' || child.nodeName === 'SELECT') {
                // 修改输入框和下拉框的 placeholder 内容
                let placeholder = child.getAttribute('placeholder')
                let _child = child
                if (placeholder && !isNumberRegex(placeholder.trim())) {
                  try {
                    if (window?.Vue_Translation_Of_Text_Data?.[placeholder.trim() + '']) {
                      child.setAttribute('placeholder', window?.Vue_Translation_Of_Text_Data?.[placeholder.trim() + ''])
                    } else if (placeholder.trim() + '') {
                      deferredReplacement(placeholder.trim() + '', function () {
                        if (window?.Vue_Translation_Of_Text_Data?.[placeholder.trim() + '']) {
                          _child.setAttribute(
                            'placeholder',
                            window?.Vue_Translation_Of_Text_Data?.[placeholder.trim() + '']
                          )
                        }
                      })
                    }
                  } catch (error) {}
                }
              } else if (child?.classList?.contains?.('el-select')) {
                // 处理 class 为 el-select 的组件
                this.processSelect(child)
              } else {
                // 递归处理子节点
                this.processTextNodes(child)
              }
            })
          }
        },
        processSelect(el) {
          // 遍历子节点并处理文本内容
          if (el.nodeType === Node.ELEMENT_NODE) {
            Array.from(el.childNodes).forEach(child => {
              if (child.nodeName === 'INPUT') {
                // 修改输入框和下拉框的 placeholder 内容
                let value = child.value
                let _child = child
                if (value && !isNumberRegex(value.trim())) {
                  try {
                    if (window?.Vue_Translation_Of_Text_Data?.[value.trim() + '']) {
                      child.value = window?.Vue_Translation_Of_Text_Data?.[value.trim() + '']
                    } else if (value.trim() + '') {
                      deferredReplacement(value.trim() + '', function () {
                        if (window?.Vue_Translation_Of_Text_Data?.[value.trim() + '']) {
                          _child.value = window?.Vue_Translation_Of_Text_Data?.[value.trim() + '']
                        }
                      })
                    }
                  } catch (error) {}
                }
              } else {
                // 递归处理子节点
                this.processSelect(child)
              }
            })
          }
        },
        processAbsolutely(el) {
          // 遍历子节点并处理文本内容
          if (el.nodeType === Node.ELEMENT_NODE) {
            Array.from(el.childNodes).forEach(child => {
              if (child.nodeType === Node.TEXT_NODE) {
                let text = child.textContent
                let _child = child
                if (text && !isNumberRegex(text.trim())) {
                  try {
                    if (window?.Vue_Translation_Of_Text_Data?.[text.trim()]) {
                      child.textContent = window?.Vue_Translation_Of_Text_Data?.[text.trim()]
                    } else if (text.trim()) {
                      deferredReplacement(text.trim(), function () {
                        if (window.Vue_Translation_Of_Text_Data[text.trim()]) {
                          _child.textContent = window.Vue_Translation_Of_Text_Data[text.trim()]
                        }
                      })
                    }
                  } catch (error) {}
                }
              } else {
                // 递归处理子节点
                this.processAbsolutely(child)
              }
            })
          }
        }
      }
    })
  }
}

export function translaBeforeRegistration(cb) {
  window.Vue_Translation_Of_Text_Type = window.localStorage.getItem('Vue_Translation_Of_Text_Type')
  if (window?.Vue_Translation_Of_Text_Type && ['en', 'ar', 'ru', 'ja'].includes(window?.Vue_Translation_Of_Text_Type)) {
    Vue.use(GlobalTextProcessor) // 注册插件
    axios
      .post(WindowsTranslateApi + '/api/v1/common/readTranslationOfText', {
        targetLanguage: window?.Vue_Translation_Of_Text_Type
      })
      .then(({ data }) => {
        var obj = {}
        var obj2 = {}
        data?.data?.map(item => {
          obj[item.source] = item.target
          obj2[item.target] = true
        })
        window.Vue_Translation_Of_Text_Old_Data = { ...(window.Vue_Translation_Of_Text_Old_Data || {}), ...obj2 }
        window.Vue_Translation_Of_Text_Data = { ...(window.Vue_Translation_Of_Text_Data || {}), ...obj }
        cb?.()
      })
      .catch(error => {
        cb?.()
      })
  } else {
    cb?.()
  }
}
