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
  permissions?: {
    id: number
    name: string
    name_en: string
    type: number
    children?: {
      id: number
      name: string
      name_en: string
      type: number
    }[]
  }[]
}




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: '' },
    permissions: [],
    environment: ''
  })



  const trackTimer = ref<number | null>(null)
  // 启动每5分钟调用一次setTrack的定时器
  const startTrackTimer = () => {
    // 清理之前的定时器（如果存在）
    if (trackTimer.value) {
      clearInterval(trackTimer.value)
      trackTimer.value = null
    }
    // 设置新的定时器，每5分钟（300000毫秒）调用一次setTrack
    trackTimer.value = setInterval(() => {
      setTrack()
    }, 5 * 60 * 1000) as unknown as number
  }

  const setTrack = () => {
    uni.getLocation({
        type: 'wgs84',
        altitude: true,
        isHighAccuracy: true,
        success(res) {
          Apis.Attendance.AttendanceEmployeeTracks.Track( { latitude: res.latitude, longitude: res.longitude })
          console.log(res, '经纬度')
        },
        fail(res) {
          uni.hideLoading()
          uni.showModal({
            title: '提示',
            content: '定位失败，员工轨迹失效！请打开定位！',
            success: function (res) {
              if (res.confirm) {
                uni.openSetting()
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          console.log(res, '获取经纬度失败')
        }
      })
  }


  function login(app: any) {
    const res: any = uni.getSystemInfoSync()
    data.value.environment = res?.environment
    console.log(res?.environment, 'res?.environment')
    if (res?.environment === 'wxwork') {
      wx.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
        data.value.permissions = res.data?.permissions[0]?.children
        loading.value = false
        uni.setStorageSync(import.meta.env.VITE_ACCESS_TOKEN_KEY, res?.data?.token?.token)
        if(res?.data?.user?.phone){
          setTrack()
          // 启动每5分钟调用一次setTrack的定时器
          startTrackTimer()
        }
        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
        data.value.permissions = res.data?.permissions[0]?.children
        loading.value = false
        uni.setStorageSync(import.meta.env.VITE_ACCESS_TOKEN_KEY, res?.data?.token?.token)
        if(res?.data?.user?.phone){
          setTrack()
          // 启动每5分钟调用一次setTrack的定时器
          startTrackTimer()
        }
        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
      data.value.permissions = res.data?.permissions[0]?.children
      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
  }
})
