export * from './wxLogin'
export * from './initWXConfig'
import * as ww from '@wecom/jssdk'
import { initWxConfig } from './initWXConfig'

const DEFAULT_SHARE_TITLE = '企业文化'
const DEFAULT_SHARE_DESC = '点击查看详情'
const DEFAULT_SHARE_IMAGE =
  'https://res.mail.qq.com/node/ww/wwmng/style/images/index_share_logo$13c64306.png'

const getCurrentShareUrl = () =>
  `https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww42a2d34b42b8d721&redirect_uri=${location.href}&response_type=code&scope=snsapi_base#wechat_redirect`

interface IShareWxOption {
  title: string
  link?: string
  desc?: string
  imgUrl?: string
}

interface IShareWxResult {
  err_msg?: string
  errMsg?: string
}

export async function wxShare(option: IShareWxOption): Promise<IShareWxResult> {
  await initWxConfig()
  return new Promise((resolve, reject) => {
    ww.invoke(
      'shareAppMessage',
      {
        title: option.title || DEFAULT_SHARE_TITLE,
        desc: option.desc || DEFAULT_SHARE_DESC,
        link: option.link || getCurrentShareUrl(),
        imgUrl: option.imgUrl || DEFAULT_SHARE_IMAGE,
      },
      function (res: IShareWxResult) {
        const errMsg = res.err_msg || res.errMsg
        if (errMsg === 'shareAppMessage:ok' || errMsg === 'openExistedChatWithMsg:ok') {
          resolve(res)
        } else {
          reject(res)
        }
      },
    )
  })
}

export function isWxShareCancel(error: unknown) {
  const err = error as { errMsg?: string; err_msg?: string; message?: string }
  return [err.errMsg, err.err_msg, err.message].some((msg) =>
    msg?.includes('shareAppMessage:cancel'),
  )
}

interface ISelectDepOrUser {
  err_msg: string
  result: IResult
}

interface IResult {
  userList: ISelectUser[]
  departmentList: ISelectDept[]
}

export interface ISelectUser {
  id: string
  name: string
  avatar: string
}

export interface ISelectDept {
  id: string
  name: string
}

export async function selectDepOrUser(wxOption = {}): Promise<IResult> {
  await initWxConfig()
  const defaultOption = {
    fromDepartmentId: -1,
    mode: 'single',
    type: ['user', 'department'],
  }
  const option = {
    ...defaultOption,
    ...wxOption,
  }
  return new Promise((resolve, reject) => {
    ww.invoke('selectEnterpriseContact', option, function (res: ISelectDepOrUser) {
      if (res.err_msg == 'selectEnterpriseContact:ok') {
        resolve(res.result)
      } else {
        reject(res)
      }
    })
  })
}
