import { loginReq, logoutReq, getInfoReq } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  setUserId,
  TokenKey,
} from '@/utils/auth'
import { Query } from '@/api/dataIntegration'
import { login, loginUp } from '@/api/newLogin'
import { ObjTy } from '~/common'
import router, { constantRoutes, asyncRoutes } from '@/router'
import { defineStore } from 'pinia'
import { usePermissionStore } from '@/store/permission'
import { useTagsViewStore } from '@/store/tagsView'
const resetRouter = () => {
  const asyncRouterNameArr: Array<any> = asyncRoutes.map((mItem) => mItem.name)
  asyncRouterNameArr.forEach((name) => {
    if (router.hasRoute(name)) {
      router.removeRoute(name)
    }
  })
}

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      username: '',
      avatar: '',
      roles: [] as Array<any>,
      token: getToken(),
      UserType: sessionStorage.getItem('UserType')
        ? sessionStorage.getItem('UserType')
        : '',
      UserId: sessionStorage.getItem('User_Id')
        ? sessionStorage.getItem('User_Id')
        : '',
      userPoewrList: sessionStorage.getItem('userAuthList')
        ? JSON.parse(<any>sessionStorage.getItem('userAuthList'))
        : [],
    }
  },

  actions: {
    M_username(username: string) {
      this.$patch((state) => {
        state.username = username
      })
    },
    M_AVATAR(avatar: string) {
      this.$patch((state) => {
        state.avatar = avatar
      })
    },
    M_roles(roles: Array<string>) {
      this.$patch((state) => {
        state.roles = roles
      })
    },

    SET_TOKEN(token: string) {
      this.$patch((state) => {
        state.token = token
      })
    },

    SET_UserId(UserId: string) {
      this.$patch((state) => {
        state.UserId = UserId
      })
    },
    SET_UserType(UserType: string) {
      this.$patch((state) => {
        state.UserType = UserType
        sessionStorage.setItem('UserType', UserType)
      })
    },
    SET_UserPoewrList(userPoewrList: any) {
      this.$patch((state) => {
        state.userPoewrList = userPoewrList
      })
    },

    login(data: ObjTy) {
      return new Promise((resolve, reject) => {
        login(data)
          .then((res: ObjTy) => {
            const { date, token, userid } = res.returnData
            this.SET_TOKEN(token)
            this.SET_UserId(userid)
            this.SET_UserType('1')
            setToken('userName', data.username)
            setToken(TokenKey, token)
            setUserId(userid)
            setToken('userid', userid)
            resolve(null)
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    // get user info
    getInfo() {
      return new Promise((resolve, reject) => {
        Query({
          id: DATACONTENT_ID.loginId,
          dataContent: [getToken('userid')],
        })
          .then((res: ObjTy) => {
            if (res.code == 0) {
              const { listValues } = res.returnData
              const datas = listValues
              if (datas && datas.length) {
                const arrs: any = []
                for (const item of datas) {
                  if (item.ident) {
                    arrs.push(item.ident)
                  }
                }
                // arrs.push('transit');
                sessionStorage.setItem('userAuthList', JSON.stringify(arrs))
                setTimeout(() => {
                  const data = {
                    roles: arrs,
                    introduction: '',
                    avatar: '',
                    name: getToken('userName'),
                    token: this.token,
                  }

                  const { name, avatar, roles } = data
                  this.M_username(name)
                  this.M_AVATAR(avatar)
                  this.M_roles(roles ? roles : ['admin'])
                  this.SET_UserPoewrList(roles ? roles : ['admin'])
                  resolve(data)
                }, 100)
              } else {
                const arr: any = []
                sessionStorage.setItem('userAuthList', arr)
                setTimeout(() => {
                  const data = {
                    roles: this.userPoewrList,
                    introduction: '',
                    avatar: '',
                    name: getToken('userName'),
                    token: this.token,
                  }

                  const { name, avatar, roles } = data

                  this.M_username(name)
                  this.M_AVATAR(avatar)
                  this.M_roles(roles ? roles : ['admin'])
                  this.SET_UserPoewrList(roles ? roles : ['admin'])
                  resolve(data)
                }, 100)
              }
            } else {
              reject(res.returnData)
            }
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    getMenuInfo() {
      return new Promise((resolve, reject) => {
        Query({
          id: 100,
          dataContent: [getToken('userid')],
        })
          .then((res: ObjTy) => {
            if (res.code == 0) {
              const { listValues } = res.returnData
              const datas: any = listValues
              resolve(datas)
            } else {
              reject(res.returnData)
            }
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    // user logout
    logout() {
      return new Promise((resolve, reject) => {
        loginUp()
          .then((res) => {
            useUserStore().resetState()
            resolve(res)
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    resetState() {
      sessionStorage.clear()
      removeToken('codeToken')
      removeToken('systemSet')
      removeToken('userid')
      removeToken('userName')
      this.M_username('')
      this.M_roles([])
      removeToken() // must remove  token  first
      resetRouter() // reset the router
      const permissionStore = usePermissionStore()
      permissionStore.M_isGetUserInfo(false)
      const tagsViewStore = useTagsViewStore()
      tagsViewStore.delAllViews()
    },
  },
})
