import { Apis } from '@/gen/Apis'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getApiLoading } from '../libraries/apiLoading'
const wxworkId = 'ww96c806131a95c739' //企微id
const wxAppId = 'wx04d2d27ca198367b' //小程序id

type DataType = {
  user?: {
    id: number
    name?: string
    phone?: string
  }
  orgs?: { id?: number; name?: string }[]
  selectedOrg?: { id?: number; name?: string; is_show_procedure?: number }
  work_info?: { session_key: string; openid: string }
  environment?: string
}

export const useWeAppAuthStore = defineStore('we_app_auth', () => {
  const loading = ref<boolean>(false)
  const hasError = ref<boolean>(false)
  const data = ref<DataType>({
    user: { id: 0, name: '', phone: '' },
    work_info: { session_key: '', openid: '' },
    environment: ''
  })

  function login(app: any) {
    const res: any = uni.getSystemInfoSync()
    data.value.environment = res?.environment
    console.log(res?.environment, 'res?.environment')
    if (res?.environment === 'wxwork') {
      uni.qy.login({
        success: function (res: any) {
          console.log(res)
          getWorkToken(app, res.code)
        }
      })
    } else {
      uni.login({
        provider: 'weixin', //使用微信登录
        success: function (loginRes) {
          console.log(loginRes)
          getWXToken(app, loginRes.code)
        }
      })
    }
  }
  const getWorkToken = (app: any, code: string) => {
    Apis.Login.Auth.WorkLogin({ code: code, app_id: wxworkId })
      .then(res => {
        console.log('企业微信登录', res?.data)
        data.value.user = res.data?.user
        data.value.work_info = res.data?.work_info
        loading.value = false
        uni.setStorageSync(import.meta.env.VITE_ACCESS_TOKEN_KEY, res?.data?.token?.token)
        app?.appContext.config.globalProperties.$isResolve()
      })
      .catch(() => {
        loading.value = false
        hasError.value = true
      })
  }

  const getWXToken = (app: any, code: string) => {
    Apis.Login.Auth.Login({ code: code, app_id: wxAppId })
      .then(res => {
        console.log('登录', res?.data)
        data.value.user = res.data?.user
        loading.value = false
        uni.setStorageSync(import.meta.env.VITE_ACCESS_TOKEN_KEY, res?.data?.token?.token)
        app?.appContext.config.globalProperties.$isResolve()
      })
      .catch(() => {
        loading.value = false
        hasError.value = true
      })
  }

  function me(fun: () => void) {
    getApiLoading(Apis.Login.Auth.Me, {}).then(res => {
      data.value.user = res.data.user
      console.log('me', res.data)
      loading.value = false
      hasError.value = false
      return fun()
    })
  }
  //企业微绑定
  const handleUserLoginWxwork = async (from_data: { iv?: string; encryptedData?: string }) => {
    getApiLoading(Apis.Login.Auth.BindWork, {
      app_id: wxAppId,
      session_key: data?.value?.work_info?.session_key,
      iv: from_data?.iv,
      encrypted_data: from_data?.encryptedData
    }).then(res => {
      me(() => {
        uni.navigateBack({ delta: 1 })
      })
    })
  }
  //小程序快捷绑定
  const handleUserLogin = async (from_data: {
    code?: string
    phone?: string
    phone_validate_code?: string
  }) => {
    getApiLoading(Apis.Login.Auth.BindPhoneNumber, {
      app_id: wxAppId,
      ...from_data
    }).then(res => {
      me(() => {
        uni.navigateBack({ delta: 1 })
      })
    })
  }

  return {
    loading,
    hasError,
    data,
    login,
    me,
    handleUserLogin,
    handleUserLoginWxwork
  }
})
