import { login, logout, getInfo } from '@/api/login'
import {editUserMsg, listUserMsg} from '@/api/system/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import { isHttp } from '@/utils/validate'
import * as mqtt from "mqtt/dist/mqtt.min"

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      userId: '',
      messagesList:[],
      mqttClient: undefined,
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        const authId = userInfo.authId
        return new Promise((resolve, reject) => {
          login(username, password, code, uuid, authId).then(res => {
            setToken(res.token)
            this.token = res.token
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.user
            const avatar = (user.avatar === "" || user.avatar == null) ? defAva : !isHttp(user.avatar)? import.meta.env.VITE_APP_BASE_API : '' + user.avatar;

            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.name = user.userName
            this.avatar = avatar;
            this.userId = user.userId
            //获取用户的时候 创建 mqtt连接
            this.setMqttClient()
            //获取用户消息
            this.selUserMsg()
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      setMqttClient(){
        //mqtt
        const clientId = "mqtt_yu_client_v3_" + Math.random().toString(16).substring(2, 8);
        const username = import.meta.env.VITE_MQTT_USERNAME;
        const password = import.meta.env.VITE_MQTT_PASSWORD;
        const url = import.meta.env.VITE_MQTT_URI;
        const client = mqtt.connect(url, {
          clientId,
          username,
          password,
        });
        console.log('mqtt链接成功！')
        this.mqttClient = client
      },
      selUserMsg(){
        listUserMsg().then(res =>{
          this.messagesList = res.data
        })
      },
      editUserMsg(noticeId){
        //设置已读
        return new Promise((resolve, reject) =>{
          this.messagesList.map((item)=>{
            if (item.noticeId === noticeId && item.isRead === '0'){
              editUserMsg(noticeId).then(res =>{
                item.isRead = '1'
                resolve(res)
              }).catch(error => {
                reject(error)
              })
            }
          })

        })
      }
    }
  })

export default useUserStore
