import { defineStore } from 'pinia'
import { login, logout, getInfo } from '@/apis/longin'
import { getToken, setToken, removeToken } from '@/utils/auth'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import defAvar from '@/static/avatar-zfsiZCFH.gif'

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    refresh_token: storage.get(constant.refresh_token),
    username: storage.get(constant.username),
    password: storage.get(constant.password),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
    dept: storage.get(constant.dept),
    deptInfo: Object,
    webstatesocket: JSON.parse(localStorage.getItem('webstatesocket') as any) as any
  }),
  actions: {
    //设置cookie
    setCookie(c_name: any, c_pwd: any, exdays: any) {
      var exdate = new Date() //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) //保存的天数
      //字符串拼接cookie
      window.document.cookie = 'userName' + 'ym=' + c_name + ';path=/;expires=' + exdate.toGMTString()
      window.document.cookie = 'password' + 'ym=' + c_pwd + ';path=/;expires=' + exdate.toGMTString()
    },
    //清除cookie
    clearCookie() {
      this.setCookie('', '', -1) //修改2值都为空，天数为负1天就好了
    },
    setsocket(socketval: any) {
      //设置 socket
      //	debugger
      this.webstatesocket = socketval
      localStorage.setItem('webstatesocket', JSON.stringify(socketval))
    },
    // 登录
    userLogin(userInfo: { username: string; password: string; code: string; uuid: string; mianlogin: boolean }) {
      return new Promise<void>((resolve, reject) => {
        // //判断复选框是否被勾选 勾选则调用配置cookie方法
        // if (userInfo.mianlogin == true) {
        //   //传入账号名，密码，和保存天数3个参数
        //   this.setCookie(userInfo.username, userInfo.password, 15)
        // } else {
        //   //console.log("清空Cookie");
        //   //清空Cookie
        //   this.clearCookie()
        // }

        login(userInfo)
          .then((res: any) => {
            if (res.code === 200) {
              // const data = res.data;
              setToken(res.data.access_token)
              this.token = res.data.access_token
              this.refresh_token = res.data.refresh_token
              storage.set(constant.refresh_token, res.data.refresh_token)
              storage.set(constant.username, userInfo.username)
              storage.set(constant.password, userInfo.password)

              resolve()
            }
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    /**
     * 获取用户信息
     *
     * @returns
     */
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res: any) => {
            // debugger
            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是否是一个非空数组
                this.roles = user.roles
                this.permissions = user.permissions
              } else {
                this.roles = ['ROLE_DEFAULT']
              }
              // this.deptInfo = {
              //   deptId: user.dept.deptId,
              //   deptName: user.dept.deptName,
              //   deptType: user.dept.deptType
              // }
              this.name = user.nickName
              this.avatar = avatar

              storage.set(constant.name, this.name)
              storage.set(constant.avatar, this.avatar)
              storage.set(constant.roles, this.roles)
              storage.set(constant.permissions, this.permissions)
            }
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 退出系统
    logOut() {
      return new Promise<void>((resolve, reject) => {
        logout()
          .then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            storage.clean()
            removeToken()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
  }
})
export default useUserStore
