import qs from 'query-string'
import appState from '/src/state'
import SettingState from '/src/pages/detail/setting-state'
import instruments from '/src/constant/instruments'
import instrumentsClassfiy from '/src/constant/instrumentsClassfiy'

/**是否是开发环境 */
export const getDevelopment = function () {
  return /(192\.168|localhost)/ig.test(location.host)
}

export const addZero = (num: number) => {
  return num < 10 ? '0' + num : num
}

export const formatTime = (time: number) => {
  const s = time % 60
  const m = time / 60
  return addZero(Math.floor(m)) + ':' + addZero(Math.floor(s))
}

export const browser = () => {
  var u = navigator.userAgent
  //   app = navigator.appVersion;
  return {
    trident: u.indexOf('Trident') > -1, //IE内核
    presto: u.indexOf('Presto') > -1, //opera内核
    webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
    ios: !!u.match(/Mac OS X/), //ios终端
    android: u.indexOf('ORCHESTRAAPPA') > -1 || u.indexOf('Adr') > -1, //android终端
    iPhone: u.indexOf('ORCHESTRAAPPI') > -1, //是否为iPhone或者QQHD浏览器
    isApp:
      u.indexOf('ORCHESTRAAPPI') > -1 ||
      u.indexOf('ORCHESTRAAPPA') > -1,
    isTeacher: u.indexOf('ORCHESTRATEACHER') > -1,
    isStudent: u.indexOf('ORCHESTRASTUDENT') > -1,
    isSchool: u.indexOf('ORCHESTRASCHOOL') > -1,
    iPad: (navigator.userAgent.match(/(iPad)/) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)), //是否iPad
    webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
    weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
    huawei: !!u.match(/huawei/i) || !!u.match(/honor/i),
    xiaomi: !!u.match(/mi\s/i) || !!u.match(/redmi/i) || !!u.match(/mix/i),
  }
}

export const getRequestHostname = () => {
  let search : any = ''
  try {
    search = qs.parse(location.search)
  } catch (error) {}
  if(search?.client){
    return search.client === 'student' ? '/api-student' : search.client === 'teacher' ? '/api-teacher' : '/api-backend'
  }
  const browserInfo = browser();
  if (browserInfo.isStudent){
    return '/api-student'
  }
  if (browserInfo.isTeacher){
    return '/api-teacher'
  }
  return '/api-backend'
}

export const getRandomKey = () => {
  let key = '' + new Date().getTime() + Math.floor(Math.random() * 1000000)
  return key
}

export const findNearestNumber = (arr: number[], target: number) => {
  return arr.reduce((pre, curr) => {
    return Math.abs(pre - target) > Math.abs(curr - target) ? curr : pre
  })
}

export const toNext = (hash: string, query?: any) => {
  const setPrefix = (url: string): string => {
    if (url) {
      return '?' + url
    }
    return ''
  }

  const searchStr = qs.stringify({
    ...qs.parse(location.search),
    _t: new Date().getTime(),
  })
  const hashSearchStr = qs.stringify(query)
  const nextUrl = location.origin + location.pathname + setPrefix(searchStr) + hash + setPrefix(hashSearchStr)
  return nextUrl
  // location.replace(nextUrl)
}

export const noop = (): void => {}

export const getImageUrl = (name: string) => {
  return new URL(`./dir/${name}.png`, location.origin).href
}

export const setTongjiTag = (event: any[]) => {
  if ((window as any)._czc) {
    ;(window as any)._czc.push(event)
  }
}

export type IPlatform = 'ANDROID' | 'IOS' | 'WEB'

export const getPlatform = (): IPlatform => {
  const browserInfo = browser()
  if (browserInfo.ios) {
    return 'IOS'
  }
  if (browserInfo.android) {
    return 'ANDROID'
  }
  return 'WEB'
}

type IJavaScriptAnimate = {
  timing: (timeFraction: number) => number
  draw: (progress: number) => void
  duration: number
}

export function JavaScriptAnimate({ timing, draw, duration }: IJavaScriptAnimate) {
  let start = performance.now()

  requestAnimationFrame(function animate(time) {
    // timeFraction 从 0 增加到 1
    let timeFraction = (time - start) / duration
    if (timeFraction > 1) timeFraction = 1

    // 计算当前动画状态
    let progress = timing(timeFraction)

    draw(progress) // 绘制

    if (timeFraction < 1) {
      requestAnimationFrame(animate)
    }
  })
}

/** 格式化当前曲谱缩放比例 */
export const formatZoom = (num = 1) => {
  const search = qs.parse(location.search);
  const size = {
    small: 0.5,
    middle: 0.7,
    large: 1,
  }
  let customZoom = size[SettingState.sett.scoreSize]
  // 自定义曲谱缩放比例
  if (search?.zoom) {
    let userZoom = Number(search?.zoom)
    userZoom = userZoom < 50 ? 50 : userZoom > 160 ? 160 : userZoom
    customZoom = userZoom / 100
  }
  return num * customZoom
}

/**
 * 设置声部初始化信息
 */
export const setVoiceInit = () => {
  const chinesePartName = { ...instruments }

  const MusicalInstrumentClassification = { ...instrumentsClassfiy }

  appState.chinesePartName = chinesePartName
  appState.MusicalInstrumentClassification = MusicalInstrumentClassification
}

export const getVoiceChinesName = (name: string | undefined) => {
  let viewname = name || ''
  if (name) {
    const cname = appState.chinesePartName[name]
    if (!cname) {
      const names = Object.keys(appState.chinesePartName)
      for (const n of names) {
        if (name.match(n)) {
          // console.table({
          //   输入名称: name,
          //   循环名称: n,
          //   匹配: name.match(n)
          // })
          viewname = name.replace(n, appState.chinesePartName[n])
          break
        }
      }
    } else {
      viewname = cname
    }
  }
  return viewname ? name + (name !== viewname ? ' (' + viewname + ')' : '') : ''
}


// 判断是否被转译
export const isEncoded = (uri: string) => {
  uri = uri || '';
  return uri !== decodeURI(uri);
}

/** 设置全局通信 */
export const setGlobalData = (_key: string, _value: any) => {
  if (!_key || !_value) return;
  const GYM = (window as any).GYM || {};
  GYM[_key] = _value
  ;(window as any).GYM = GYM
}
