import { extend } from 'umi-request'
import { Toast } from 'vant'
import cleanDeep from 'clean-deep'
import { getRequestHostname, browser } from '/src/helpers/utils'
// import ApiRouter from '/src/api-router'
import { postMessage } from './native-message'

export interface SearchInitParams {
  rows?: string | number
  page?: string | number
}

export interface InitSearchRespones {
  data: {
    rows: any[]
    [key: string]: any
  }
  [key: string]: any
}

let isOpenLogin = false

const request = extend({
  requestType: 'json',
  timeout: 10000,
  prefix: getRequestHostname(),
})

request.use(async (ctx, next) => {
  const { url, options } = ctx.req
  await next()
})

request.interceptors.request.use(
  (url, options: any) => {
    const Authorization = sessionStorage.getItem('Authorization') || ''
    return {
      url,
      options: {
        ...options,
        params: cleanDeep(options.params),
        headers: {
          ...options.headers,
          Authorization,
        },
      },
    }
  },
  { global: false }
)

request.interceptors.response.use(
  async (res, options) => {
    const url = new URL(res.url)
    if (res.status > 299 || res.status < 200) {
      const msg = '服务器错误，状态码' + res.status
      Toast(msg)
      throw new Error(msg)
    }
    const data = await res.clone().json()
    if (data.code !== 200 && data.errCode !== 0) {
      const msg = data.msg || data.message || '处理失败，请重试'
      if (!(data.code === 403 || data.code === 401)) {
        Toast(msg)
      }
      const browserInfo = browser()
      if (data.code === 403 && browserInfo.isApp && !isOpenLogin) {
        if (browserInfo.android) {
          postMessage({
            api: 'login',
          })
          ;(window as any).DAYA.postMessage(JSON.stringify({ api: 'login' }))
        } else if (browserInfo.iPhone) {
          ;(window as any).webkit.messageHandlers.DAYA.postMessage(JSON.stringify({ api: 'login' }))
        }
      }
      throw new Error(msg)
    }
    return res
  },
  { global: false }
)

export default request
