import dict from './dict'

export interface DialogOptions {
  title?: string
  buttons?: {
    text: string
    color: string
  }[]
  click?: any
  close?: any
  content: string
  okText?: string
  okColor?: string
  ok?: any
  cancelText?: string
  cancelColor?: string
  cancel?: any
  hideCancel?: boolean
  maskClosable?: boolean
}

export const toast_bg_colors = {
  info: 'rgba(0, 0, 0, 0.7)',
  success: '#19be6b',
  warn: '#ff7900',
  error: '#EB0909',
  primary: '#5677fc',
} as any
const default_duration = 1500
export const toast_dict_key = 'mj-toast'
export const loading_dict_key = 'mj-loading'
export const dialog_dict_key = 'mj-dialog'
export const hide_dict_key = 'mj-hide'

function _toast(type: string, msg: string, duration = default_duration) {
  dict.callFn(toast_dict_key, type, msg, duration)
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(true)
    }, duration)
  })
}

export async function info(text: string, duration?: number) {
  return _toast('info', text, duration)
}

export async function error(text: string, duration?: number) {
  return _toast('error', text, duration)
}

export async function warn(text: string, duration?: number) {
  return _toast('warn', text, duration)
}

export async function success(text: string, duration?: number) {
  return _toast('success', text, duration)
}

export async function primary(text: string, duration?: number) {
  return _toast('primary', text, duration)
}

export function loading(text = '正在加载中...') {
  dict.callFn(loading_dict_key, text)
}

export function dialog(options: DialogOptions) {
  dict.callFn(dialog_dict_key, options)
}

export function hide() {
  dict.callFn(hide_dict_key)
}

interface LoadOptions {
  loading?: string
  task: () => Promise<any>
  option?: string
  hideSuccess?: boolean
  hideError?: boolean
}

async function load(options: LoadOptions) {
  let loadingContent = '加载中...'
  let successContent = '操作成功！'
  let errorContent = '操作失败！'
  if (options.option) {
    loadingContent = `${options.option}中...`
    successContent = `${options.option}成功！`
    errorContent = `${options.option}失败！`
  }
  let showOptions = options.loading
  if (!showOptions) {
    showOptions = loadingContent
  }
  loading(showOptions)

  if (options.hideSuccess === undefined) {
    options.hideSuccess = true
  }

  if (options.hideError === undefined) {
    options.hideError = true
  }

  try {
    const res = await options.task()
    !options.hideSuccess && success(successContent)
    // 返回出去
    return res
  } catch (err: any) {
    if (err) {
      if (typeof err === 'string') {
        errorContent += `${err}`
      } else if (err.message) {
        errorContent += `${err.message}`
      }
    }
    !options.hideError && error(errorContent)
    throw err
  } finally {
    hide()
  }
}

export default {
  info,
  success,
  error,
  load,
  loading,
  warn,
  primary,
  hide,
  dialog,
}
