// 定义组合式API仓库
import { defineStore } from 'pinia'
import { computed } from 'vue'
import { getPrefixName } from '@/config'
import { goToPage } from '@/utils/util'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, logout, getInfo, getrefreshtoken } from '@/apis/longin'
// import { getUserProfile } from '@/apis/systemuser'
import defAvar from '@/static/avatar-zfsiZCFH.gif'
interface userInfoStoreInt {
  token: string
  refreshtoken: string
  avatar: string
  username: string
  password: string
  name: string
  roles: any
  permissions: any
  dept: any
  deptInfo: any
  parentmenutitle: string
  childrenmenutitle: string
  urlip: string
  urlpro: string
  allurl: string
}

// 创建小仓库
export default defineStore(
  getPrefixName('user'),
  () => {
    const userInfo = ref<userInfoStoreInt>({
      token: '',
      refreshtoken: '',
      avatar: '',
      username: '',
      password: '',
      name: '',
      roles: [],
      permissions: [],
      dept: null,
      deptInfo: null,
      parentmenutitle: '',
      childrenmenutitle: '',
      urlip: '',
      urlpro: '',
      allurl: ''
    })
    //debugger
    userInfo.value.token = getToken()
    userInfo.value.refreshtoken = storage.get(constant.refresh_token)
    userInfo.value.username = storage.get(constant.username)
    userInfo.value.password = storage.get(constant.password)
    userInfo.value.name = storage.get(constant.name)
    userInfo.value.avatar = storage.get(constant.avatar)
    userInfo.value.roles = storage.get(constant.roles)
    userInfo.value.permissions = storage.get(constant.permissions)
    userInfo.value.dept = storage.get(constant.dept)
    userInfo.value.parentmenutitle = storage.get(constant.parentmenutitle)
    userInfo.value.childrenmenutitle = storage.get(constant.childrenmenutitle)
    userInfo.value.urlip = storage.get(constant.urlip)
    userInfo.value.urlpro = storage.get(constant.urlpro)
    userInfo.value.allurl = storage.get(constant.allurl)

    const token = computed(() => {
      // debugger
      return userInfo.value.token || ''
    })
    const refreshtoken = computed(() => {
      // debugger
      return userInfo.value.refreshtoken || ''
    })
    const name = computed(() => {
      return userInfo.value.name
    })
    const avatar = computed(() => {
      return userInfo.value.avatar
    })
    const username = computed(() => {
      return userInfo.value.username
    })
    const password = computed(() => {
      return userInfo.value.password
    })
    const roles = computed(() => {
      return userInfo.value.roles
    })
    const permissions = computed(() => {
      return userInfo.value.permissions
    })
    const dept = computed(() => {
      return userInfo.value.permissions
    })

    const deptInfo = computed(() => {
      return userInfo.value.deptInfo
    })
    const urlip = computed(() => {
      return userInfo.value.urlip
    })
    const urlpro = computed(() => {
      return userInfo.value.urlpro
    })
    const allurl = computed(() => {
      return userInfo.value.allurl
    })

    const parentmenutitle = computed(() => {
      return userInfo.value.parentmenutitle
    })
    const childrenmenutitle = computed(() => {
      return userInfo.value.childrenmenutitle
    })

    function setallurl(allurl: any) {
      userInfo.value.allurl = allurl
      storage.set(constant.allurl, allurl)
    }
    function seturlip(urlip: any) {
      userInfo.value.urlip = urlip
      storage.set(constant.urlip, urlip)
    }
    function seturlpro(urlpro: any) {
      userInfo.value.urlpro = urlpro
      storage.set(constant.urlpro, urlpro)
    }

    function setavatar(avatar: any) {
      userInfo.value.avatar = avatar
      storage.set(constant.avatar, avatar)
    }

    function setparentmenutitle(parentmenutitle: any) {
      userInfo.value.parentmenutitle = parentmenutitle
      storage.set(constant.parentmenutitle, parentmenutitle)
    }
    function setchildrenmenutitle(childrenmenutitle: any) {
      userInfo.value.childrenmenutitle = childrenmenutitle
      storage.set(constant.childrenmenutitle, childrenmenutitle)
    }
    // 登录
    function userLogin(dataInfo: { username: string; password: string; code: string; uuid: string; mianlogin: boolean }) {
      return new Promise((resolve, reject) => {
        login(dataInfo)
          .then((res: any) => {
            //  debugger
            // userInfo.value = res.data
            // userInfo.value.userpassword = params.password ? params.password : ''
            // // getUserProfile({}).then((res1: any) => {
            // //   debugger
            // // })

            setToken(res.data.access_token)
            userInfo.value.token = res.data.access_token
            userInfo.value.refreshtoken = res.data.refresh_token
            userInfo.value.username = dataInfo.username
            userInfo.value.password = dataInfo.password
            storage.set(constant.refresh_token, res.data.refresh_token)
            storage.set(constant.username, dataInfo.username)
            storage.set(constant.password, dataInfo.password)

            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    }

    // 刷新token
    function setrefreshtoken() {
      return new Promise((resolve, reject) => {
        getrefreshtoken(userInfo.value.refreshtoken)
          .then((res: any) => {
            //debugger
            if (res.code === 200) {
              setToken(res.data)
              userInfo.value.token = res.data
            }

            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    }

    // 个人信息
    function userinfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res: any) => {
            if (res.code === 200) {
              // const data = res.data;
              const user = res.data
              // prettier-ignore
              // const avatar = user.avatar == "" || user.avatar == null ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
              const avatar = (user == null || user.avatar == "" || user.avatar == null) ? defAvar :  import.meta.env.VITE_APP_BASE_PRE + user.avatar

              if (user.roles && user.roles.length > 0) {
                // 验证返回的roles是否是一个非空数组
                userInfo.value.roles = user.roles
                userInfo.value.permissions = user.permissions
              } else {
                userInfo.value.roles = ['ROLE_DEFAULT']
              }
              // this.deptInfo = {
              //   deptId: user.dept.deptId,
              //   deptName: user.dept.deptName,
              //   deptType: user.dept.deptType
              // }
              userInfo.value.name = user.nickName
              userInfo.value.avatar = avatar

              storage.set(constant.name, user.nickName)
              storage.set(constant.avatar, userInfo.value.avatar)
              storage.set(constant.roles, userInfo.value.roles)
              storage.set(constant.permissions, userInfo.value.permissions)
            }

            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    }

    // 退出登录
    function userlogOut() {
      return new Promise<void>((resolve, reject) => {
        logout()
          .then(() => {
            uni.showToast({
              icon: 'none',
              title: '退出成功',
              mask: true,
              success() {
                setTimeout(() => {
                  userInfo.value = {
                    token: '',
                    refreshtoken: '',
                    avatar: '',
                    username: '',
                    password: '',
                    name: '',
                    roles: [],
                    permissions: [],
                    dept: null,
                    deptInfo: null,
                    parentmenutitle: '',
                    childrenmenutitle: '',
                    urlip: '',
                    urlpro: '',
                    allurl: ''
                  }
                  uni.clearStorageSync()
                  goToPage({
                    url: 'pages/login/login',
                    mode: 'reLaunch'
                  })
                }, 1000)
              }
            })
            storage.clean()
            removeToken()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
    return {
      token,
      refreshtoken,
      avatar,
      username,
      password,
      name,
      roles,
      permissions,
      dept,
      deptInfo,
      userLogin,
      userinfo,
      userlogOut,
      setavatar,
      setparentmenutitle,
      setchildrenmenutitle,
      parentmenutitle,
      childrenmenutitle,
      setrefreshtoken,
      urlip,
      urlpro,
      seturlip,
      seturlpro,
      setallurl,
      allurl
    }
  },
  {
    // unistorage: {
    //   serializer: {
    //     // 序列化，默认为 JSON.stringify
    //     serialize(v) {
    //       return JSON.stringify(v)
    //     },
    //     // 反序列化，默认为 JSON.parse
    //     deserialize(v) {
    //       return JSON.parse(v)
    //     }
    //   }
    // }
    // 开启后对 state 的数据读写都将持久化
    // unistorage: {
    //   key: 'userInfo', // 缓存的键，默认为该 store 的 id，这里是 main,
    //   paths: ['userInfo.token'], // 需要缓存的路径，这里设置 foo 和 nested 下的 data 会被缓存
    //   // 初始化恢复前触发
    //   beforeRestore(ctx: any) {
    //     console.log(ctx)
    //   },
    //   // 初始化恢复后触发
    //   afterRestore(ctx: any) {
    //     console.log('ctx', ctx)
    //   }
    // }
  }
)
