import { Apis } from '@/gen/Apis'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { setTabBar } from '../libraries/setTabBar'
import { getApiLoading } from '../libraries/apiLoading'
// const wxAppId = 'wx31500e871924b903' //小程序id
import config from '@/common/libraries/config'

type DataType = {
  user?: {
    id: number
    phone?: string
    name?: string
  }
  orgs?: { id?: number; name?: string }[]
  selectedOrg?: { id?: number; name?: string; is_show_procedure?: number }
  work_info?: { session_key: string; openid: string }
  selected_house?: { id?: string; full_name?: string; asset_projects_id?: string }
  environment?: string
  house_register?: boolean
  house_occupant?: boolean
  is_house_exist?: number
  address_city?: {
    city?: string
  },
  current_city:{
    city?: string
  },
  config?: {
    companyAction?: {
      name?: string
      icon?: { url?: string }[]
      url?: string
      is_show?: number
    }[]
    companyConfig?: {
      config_value?: {
        color?: string
        pageColor?: string
        logo?: { url?: string }[]
      }
    }
  }
}

export const useWeAppAuthStore = defineStore('we_app_auth', () => {
  const loading = ref<boolean>(false)
  const hasError = ref<boolean>(false)
  const is_house_exist = ref(0)
  const data = ref<DataType>({
    user: { id: 0, name: '' },
    work_info: { session_key: '', openid: '' },
    selected_house: {},
    environment: '',
    house_occupant: false,
    house_register: false,
    is_house_exist: 0,
    config: {},
    address_city: {},
    current_city: {}
  })

  function login(app: any) {
    uni.login({
      provider: 'weixin', //使用微信登录
      success: function (loginRes) {
        console.log(loginRes)
        getWXToken(app, loginRes.code)
      }
    })
  }

  const getWXToken = (app: any, code: string) => {
    Apis.Login.Auth.Login({ code: code, app_id: config?.WxAppId })
      .then(res => {
        console.log('登录', res?.data)
        uni.setStorageSync(import.meta.env.VITE_ACCESS_TOKEN_KEY, res?.data?.token?.token)
        app?.appContext.config.globalProperties.$isResolve()
        setTimeout(() => {
          loading.value = false
          hasError.value = false
        }, 300)
        data.value.selected_house = res.data?.selected_house
        data.value.user = res.data?.user
        data.value.config = res.data?.config
        //设置底部菜单
        setTabBar(res?.data?.config)
        if (data.value.user) {
          getIsHouseExist()
        }
      })
      .catch(() => {
        loading.value = false
        hasError.value = true
      })
  }

  const getIsHouseExist = () => {
    Apis.Archive.HouseOccupants.GetCustomerHouseIsExist().then(res => {
      data.value.house_occupant = res.data?.house_occupant || false
      data.value.house_register = res.data?.house_register || false
      data.value.is_house_exist = is_house_exist.value + 1
    })
  }

  function me(fun?: () => void) {
    getApiLoading(Apis.Login.Auth.Me, {}).then(res => {
      data.value.user = res.data.user
      data.value.config = res.data?.config
      data.value.selected_house = res.data?.selected_house
      console.log('me', res.data)
      if (data.value.user) {
        getIsHouseExist()
      }
      setTimeout(() => {
        loading.value = false
        hasError.value = false
      }, 300)
      //设置底部菜单
      setTabBar(res?.data?.config)
      return fun?.()
    })
  }

  //小程序快捷绑定
  const handleUserLogin = async (from_data: {
    code?: string
    phone?: string
    phone_validate_code?: string
  }) => {
    getApiLoading(Apis.Login.Auth.BindPhoneNumber, {
      app_id: config?.WxAppId,
      ...from_data
    }).then(res => {
      me(() => {
        uni.navigateBack({ delta: 1 })
      })
    })
  }


const SetAddressCity = () =>{

 // 高德配置
const AMAP_KEY = 'be262c006216c542747fce766130cee3'
uni.getLocation({
    type: 'gcj02',
    altitude: true,
    isHighAccuracy: true,
    success(res) {
      console.log(res, '经纬度')
      const url = `https://restapi.amap.com/v3/geocode/regeo?location=${res.longitude},${res.latitude}&key=${AMAP_KEY}`
      uni.request({
        url: url,
        method: 'GET',
        success(res: any) {
          console.log(res, 'address')
          data.value.current_city = res?.data?.regeocode?.addressComponent
        },
      })
    },
    fail(e) {
      uni.showModal({
        title: '提示',
        content: '请先允许定位！',
        success: function (res) {
          if (res.confirm) {
            uni.openSetting()
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      console.log('拒绝定位', e)
    }
  })
}

  return {
    loading,
    hasError,
    data,
    login,
    me,
    handleUserLogin,
    getIsHouseExist,
    SetAddressCity
  }
})
