import { getUserInfo, getProductUserList, getMessageList } from '@/api/user'
import { getStorage } from "@/utils/localStorage";
import { getSession } from "@/utils/sessionStorage";
import { getCookie, removeCookie } from "@/utils/cookie";
const user = {
  state: {
    isLogin: false,
    myFavoriteList: [],
    token: getCookie('userToken'),
    socketToken: getSession('socketToken'),
    userInfo: {},
    isDot: false,
    msgDotNumber: 0
  },
  mutations: {
    SET_LOGIN: (state, sign) => {
      if (!sign) {
        state.isDot = false
        state.msgDotNumber = 0
        state.token = ''
        state.userInfo = {}
        removeCookie('userToken')
      }
      state.isLogin = sign
    },
    setToken: (state, token) => {
      state.token = token
    },
    setMyFavoriteList: (state, list) => {
      state.myFavoriteList = list
    },
    setSocketToken: (state, token) => {
      state.socketToken = token
    },
    setIsDot: (state, obj) => {
      state.isDot = obj.sign
      state.msgDotNumber = obj.number
    },
    SET_USER_INFO: (state, v) => (state.userInfo = v),
  },
  actions: {
    getUserInfo({ commit, dispatch }, sign) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(res => {
          if (sign) {
            dispatch('getMessageList')
          }
          commit('SET_USER_INFO', res)
          resolve(res)
        }).catch(error => {
          if (error.code == 1000) {
            commit('SET_USER_INFO', {
              email: error.email,
              phone: error.phone,
              update_datetime: error.update_datetime,
              status: error.status,
              password_verification: error.password_verification,
            })
          }
          // reject(error)
        })
      })
    },
    getMessageList({ commit, dispatch }) {
      return new Promise((resolve, reject) => {
        getMessageList({
          pageNum: 1,
          pageSize: 1,
          status: 0
        }).then(res => {
          commit('setIsDot',{
            sign: (res.list || []).length > 0,
            number: res.total
          })
          resolve(res)
        }).catch(error => {
        })
      })
    },
    getProductUserList({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.isLogin) {
          getProductUserList().then(res => {
            commit('setMyFavoriteList', res.list || [])
            resolve()
          }).catch(error => {
          })
        } else {
          var list = getStorage('myFavoriteList')
          commit('setMyFavoriteList', list || [])
          resolve()
        }
      })
    },
  }
}

export default user
