import { defineStore } from 'pinia'
import { login, getUserInfo } from '@/service/modules/common'
import {
  loginBySms,
  getUserInfoByCode,
  changeEnt,
  loginByPassword,
  logoutApi
} from '@/service/modules/login'

import { getOpenId } from '@/service/modules/newsDetail'
import type { sendParams } from '@/types/login'

export const useLoginStore = defineStore('login', {
  state() {
    return {
      accessToken: '',
      userInfo: [],
      currentUserId: ''
    }
  },
  getters: {
    isLogin: (state) => !!state.accessToken,
    currentUserInfo(state): any {
      if (!state.userInfo.length) return
      if (state.currentUserId) {
        return state.userInfo.find((item: any) => {
          return item.userId == state.currentUserId
        })
      }
      return state.userInfo[0]
    }
  },
  actions: {
    // 根据验证码登录
    async loginBySms(data: any) {
      const { phone, code } = data
      const res = await loginBySms(phone, code)
      this.accessToken = res.access_token
      return await this.getUserInfoByCode()
    },
    // 根据账号密码登录
    async loginByPassword(data: any) {
      const { phone, password } = data
      const res = await loginByPassword(phone + '@mp', password)
      return res
      // this.accessToken = res.access_token
      // return await this.getUserInfoByCode()
    },
    // 获取用户信息
    async getUserInfoByCode() {
      const wxLoginRes: any = await login()
      const wxUserInfo: any = await getUserInfo()
      const wxCode = wxLoginRes.code // 随机码
      const res = await getOpenId(wxCode)

      const userInfoData = await getUserInfoByCode(
        res.openid,
        encodeURIComponent(wxUserInfo.userInfo.avatarUrl)
      )
      this.userInfo = userInfoData.data.userInfo
      return userInfoData.data
    },
    // 更换当前的企业
    setCurrentUserId(id: string) {
      this.currentUserId = id
    },
    async changeWeiXinLogin(sendParams: sendParams) {
      const res = await changeEnt(sendParams)
      this.accessToken = res.access_token
      return await this.getUserInfoByCode()
    },
    // 退出登录
    logoutFn() {
      logoutApi()
    }
  },
  persist: {
    storage: {
      getItem(key: string): string | null {
        return uni.getStorageSync(key)
      },
      setItem(key: string, value: string) {
        return uni.setStorageSync(key, value)
      }
    }
  }
})
