import {useEffect, useState} from "react";
import {createContainer} from "unstated-next";
import Taro from "@tarojs/taro";

// import {whiteList} from "@/config";


function DataKey(data: any) {
  return !Array.isArray(data)
    && typeof data === 'object'
    && 'data' in data
    && 'user' in data.data
    && 'token' in data.data
    && 'company' in data.data
}

function useProfile() {
  let data

  if (process.env.TARO_ENV === 'h5') {
    try {
      const profileCopy = JSON.parse(localStorage.getItem("profileCopy") || '{}')
      if (DataKey(profileCopy)) {
        data = profileCopy.data || null
        localStorage.removeItem("profileCopy")
        Taro.reLaunch({url: '/pages/index/index'})
      }
    } catch (e) {
      console.error(e)
    }
  }

  if (data == null) {
    try {
      const cacheData = {data: JSON.parse(Taro.getStorageSync('profile') || '{}')}
      if (DataKey(cacheData)) {
        data = cacheData.data
      }
    } catch (e) {
      console.error(e)
    }
  }

  // if (data?.token == null) {
  //   if (!whiteList.includes(Taro.getCurrentInstance().router?.path?.split('?')?.[0] || '')) {
  //     Taro.reLaunch({url: '/pages/login/login'})
  //   }
  // }

  const [role, setRole] = useState<UserRole | null>(data?.role || null)
  const [user, setUser] = useState<User | null>(data?.user || null)
  const [token, setToken] = useState<string | null>(data?.token || null)
  const [company, setCompany] = useState<Company | null>(data?.company || null)


  function empty(jump = true, relaunch=false) {
    setUser(null)
    setUser(null)
    setToken(null)
    Taro.removeStorageSync('profile')
    Taro.clearStorage()
    if(relaunch){
      jump && Taro.reLaunch({url: '/pages/my/my'})
    }else{
      jump && Taro.navigateTo({url: '/pages/login/login'})
    }
  }

  useEffect(() => {
    Taro.setStorage({
      key: 'profile',
      data: JSON.stringify({role, user, token, company})
    })
  }, [role, user, token, company])

  return {
    role, setRole,
    user, setUser,
    token, setToken,
    company, setCompany,
    empty
  }
}

export const Profile = createContainer(useProfile);
