import { PinYin } from './constant'

export function convertToPinyin(sourceStr) {
  // 目标数据
  let targetStr = ''
  // 匹配中文
  const cnReg = /[\u4e00-\u9fa5]/
  // 匹配数字和英文
  const enReg = /[a-zA-Z0-9]/
  // 保留英文和数字
  const keep = true

  const searchPinYin = (str, data) => {
    for (const key in data) {
      if (data.hasOwnProperty(key) && data[key].indexOf(str) !== -1) {
        return key
      }
    }
    return ''
  }
  
  const firstCapital = str => {
    if (str) {
      const [first] = str
      const other = str.replace(/^\S/, '')
      return `${first.toUpperCase()}${other}`
    }
    return str
  }
  // 遍历源数据
  for (let i = 0, len = sourceStr.length; i < len; i++) {
    const str = sourceStr.substr(i, 1)
    if (keep && enReg.test(str)) {
      targetStr += str
    } else if (cnReg.test(str)) {
      const searchResult = searchPinYin(str, PinYin)
      if (searchResult) {
        // targetStr += searchResult
        targetStr += firstCapital(searchResult) // 首字母大写
      }
    }
  }

  return targetStr
}

