import { ref } from 'vue'
import { useI18n } from 'vue-i18n'

export function useDingTalkLogin() {
  const { t } = useI18n({ useScope: 'global' })
  const loggingIn = ref(false)
  const loginError = ref(null)

  const loginByDingTalk = async () => {
    if (loggingIn.value) return
    
    loggingIn.value = true
    loginError.value = null
    
    try {
      // 检查钉钉是否安装
      const providerRes = await checkDingTalkInstalled()
      if (!providerRes.provider.includes('dingtalk')) {
        throw new Error(t('login.dingtalkNotInstalled'))
      }
      
      // 调用钉钉登录
      const loginRes = await uniLogin()
      console.log('钉钉登录成功获取code:', loginRes)
      
      // 获取用户信息
      const userInfo = await fetchUserInfo(loginRes.code)
      console.log('获取用户信息成功:', userInfo)
      
      // 保存用户信息
      saveUserInfo(userInfo)
      
      return userInfo
    } catch (error) {
      console.error('钉钉登录失败:', error)
      loginError.value = error.message || t('login.failed')
      showLoginError()
      return null
    } finally {
      loggingIn.value = false
    }
  }

  const checkDingTalkInstalled = () => {
    return new Promise((resolve, reject) => {
      uni.getProvider({
        service: 'oauth',
        success: resolve,
        fail: reject
      })
    })
  }

  const uniLogin = () => {
    return new Promise((resolve, reject) => {
      uni.login({
        provider: 'dingtalk',
        success: resolve,
        fail: reject
      })
    })
  }

  const fetchUserInfo = (code) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: 'https://your-api.com/api/dingtalk/login',
        method: 'POST',
        data: { code },
        success: (res) => {
          if (res.data.code === 200) {
            resolve(res.data.data)
          } else {
            reject(new Error(res.data.message || '获取用户信息失败'))
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  }

  const saveUserInfo = (userInfo) => {
    uni.setStorageSync('userInfo', userInfo)
    uni.setStorageSync('isLoggedIn', true)
  }

  const showLoginError = () => {
    uni.showToast({
      title: loginError.value,
      icon: 'none',
      duration: 3000
    })
  }

  return {
    loggingIn,
    loginError,
    loginByDingTalk
  }
}    