import { create } from 'zustand'
import { fetchJSON, appendRequestHeader } from '@/utils/request'
import { isEmpty, isNotEmpty } from '@/utils/commons'

const useAuthStore = create((set, get) => ({

  loginUser: {
    userId: -1,
    userIdStr: '-1',
    username: '',
    avatarUrl: '',
    mobile: '',
    email: '',
    openId: '',
    accountList: [],
    permissionList: [],
  },

  loginStatus: 0,

  login: async (authCode) => {

    const { saveUserSession, setLoginStatus } = get()

    setLoginStatus(200)

    const json = await fetchJSON(`https://p9axztuwd7x8a7.mycht.cn/dingtalk/dingtalkwork/WhatsAppAuth`, { authCode })

    if (json.errcode === 0 && isNotEmpty(json.result.opisn)) {
      set(() => ({
        loginUser: {
          userId: json.result.opisn,
          userIdStr: json.result?.accountlist.map(acc => {
            return acc.OPI_SN
          }).join(','),
          accountName: json.result.opicode,
          username: json.result.nick,
          avatarUrl: json.result.avatarUrl,
          mobile: '+' + json.result.stateCode + '-' + json.result.mobile,
          email: json.result.email,
          openId: json.result.openId,
          accountList: json.result.accountlist,
        }
      }))
      saveUserSession()
      setLoginStatus(302)
    } else {
      setLoginStatus(403)
    }
  },

  setLoginStatus: (code) => {
    set(() => ({
      loginStatus: code
    }))
  },

  logout: () => {
    window.sessionStorage.clear()
    set(() => ({
      loginStatus: 0,
      loginUser: {
        userId: -1,
        userIdStr: '-1',
        username: '',
        avatarUrl: '',
        mobile: '',
        email: '',
        openId: '',
        accountList: [],
        permissionList: [],
      }
    }))

  },

  loadUserSession: () => {
    let sessionData = window.sessionStorage.getItem('GLOBAL_SALES_LOGIN_USER')

    if (import.meta.env.DEV && isEmpty(sessionData)) {
      sessionData = window.localStorage.getItem('GLOBAL_SALES_LOGIN_USER')
    }

    if (sessionData !== null) {
      const sesstionObj = JSON.parse(sessionData)
      set(() => ({
        loginUser: sesstionObj
      }))

      appendRequestHeader('X-User-Id', sesstionObj.userId)

      window.__spytitle = sesstionObj.username;
    }
  },

  saveUserSession: () => {
    const { loginUser } = get()
    window.sessionStorage.setItem('GLOBAL_SALES_LOGIN_USER', JSON.stringify(loginUser))
    appendRequestHeader('X-User-Id', loginUser.userId)
  },

  copyUserSession: () => {
    const sessionData = window.sessionStorage.getItem('GLOBAL_SALES_LOGIN_USER')
    if (sessionData !== null) {
      navigator.clipboard.writeText(sessionData)
    }
  }

}))

export default useAuthStore
