import { setToken, removeToken } from '@/util/auth'
import { setStore, getStore, clearStore } from '@/util/store'
import { encryption, deepClone } from '@/util/util'
import { isURL, validatenull } from '@/util/validate'
import website from '@/const/website.js'
import { loginByUsername, getUserInfo, getMenu, getTopMenu, logout, refeshToken } from '@/api/user'
import { formatPath } from '@/router/avue-router'

function addPath(ele, first) {
  const menu = website.menu
  const propsConfig = menu
  const propsDefault = {
    label: propsConfig.label || 'name',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children'
  }
  const icon = ele[propsDefault.icon]
  ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon
  const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0
  if (!isChild) ele[propsDefault.children] = []
  if (!isChild && first && !isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path] + '/index'
  } else {
    ele[propsDefault.children].forEach((child) => {
      addPath(child)
    })
  }
}

const user = {
  state: {
    userInfo: getStore({ name: 'userInfo' }) || {},
    permission: getStore({ name: 'permission' }) || {},
    roles: [],
    menuId: {},
    menu: getStore({ name: 'menu' }) || [],
    menuAll: getStore({ name: 'menuAll' }) || [],
    token: getStore({ name: 'token' }) || ''
  },
  actions: {
    // 根据用户名登录
    LoginByUsername({ commit }, userInfo = {}) {
      const user = encryption({
        key: website.encryptKey,
        data: userInfo,
        param: ['password']
      })
      return new Promise((resolve) => {
        loginByUsername(user.username, user.password, userInfo.code, userInfo.redomStr).then((res) => {
          const data = res.data
          // console.log(data)
          commit('SET_USERIFNO', data.user_info)
          commit('SET_TOKEN', data.access_token)
          commit('SET_PERMISSION', data.user_info.authorities)
          commit('DEL_ALL_TAG')
          commit('CLEAR_LOCK')
          resolve()
        })
      })
    },
    // 根据手机号登录
    LoginByPhone({ commit }, userInfo) {
      return new Promise((resolve) => {
        loginByUsername(userInfo.phone, userInfo.code).then((res) => {
          const data = res.data.data
          commit('SET_TOKEN', data)
          commit('DEL_ALL_TAG')
          commit('CLEAR_LOCK')
          resolve()
        })
      })
    },
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res) => {
            const data = res.data.data
            commit('SET_USERIFNO', data.userInfo)
            commit('SET_ROLES', data.roles)
            //
            resolve(data)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    // 刷新token
    RefeshToken({ state, commit }) {
      return new Promise((resolve, reject) => {
        refeshToken(state.refeshToken)
          .then((res) => {
            const data = res.data.data
            commit('SET_TOKEN', data)
            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then((res) => {
            commit('SET_MENU', [])
            commit('SET_PERMISSIONS', [])
            commit('SET_USER_INFO', {})
            commit('SET_TOKEN', '')
            // commit('SET_EXPIRES_IN', '')

            commit('SET_MENUALL_NULL', [])

            commit('SET_ROLES', [])
            commit('DEL_ALL_TAG', [])
            commit('CLEAR_LOCK')
            // removeToken()
            resolve()
            // clearStore()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 注销session
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_MENUALL_NULL', [])
        commit('SET_MENU', [])
        commit('SET_ROLES', [])
        commit('DEL_ALL_TAG', [])
        commit('CLEAR_LOCK')
        removeToken()
        resolve()
      })
    },
    GetTopMenu() {
      return new Promise((resolve) => {
        getTopMenu().then((res) => {
          const data = res.data.data || []
          resolve(data)
        })
      })
    },
    // 获取系统菜单
    GetMenu({ commit }, parentId) {
      return new Promise((resolve) => {
        // 动态路由
        getMenu(parentId).then((res) => {
          const data = res.data.data
          let menu = deepClone(data)
          menu.forEach((ele, index) => {
            addPath(ele)
          })
          let type = true
          // console.log('全部菜单', menu)
          menu = [
            {
              id: '1572831092584710146',
              parentId: '-1',
              weight: 1,
              name: '公共组件',
              path: '/communal',
              keepAlive: '0',
              sortOrder: 1,
              icon: 'icon-biaodanbiaoqian',
              menuType: '0',
              permission: null,
              label: '公共组件',
              children: [
                {
                  id: '1575010946960777217',
                  parentId: '1572831092584710146',
                  weight: 1,
                  name: '上传资源',
                  path: '/upload/index',
                  keepAlive: '0',
                  sortOrder: 1,
                  menuType: '0',
                  permission: null,
                  label: '上传资源',
                  children: []
                },
                {
                  id: '1575010946960777219',
                  parentId: '1572831092584710146',
                  weight: 2,
                  name: '预览资源',
                  path: '/upload/browse',
                  keepAlive: '0',
                  sortOrder: 2,
                  menuType: '0',
                  permission: null,
                  label: '预览资源',
                  children: []
                }
              ],
              meta: {}
            }
          ]
          commit('SET_MENU', { type, menu })
          resolve(menu)
        })
      })
    }
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      setToken(token)
      state.token = token
      setStore({ name: 'token', content: state.token })
    },
    SET_MENUID(state, menuId) {
      state.menuId = menuId
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo
      setStore({ name: 'userInfo', content: state.userInfo })
    },
    SET_MENUALL: (state, menuAll) => {
      let menu = state.menuAll
      menuAll.forEach((ele) => {
        let index = menu.findIndex((item) => item.path == ele.path)
        if (index == -1) {
          menu.push(ele)
        } else {
          menu[index] = ele
        }
      })
      state.menuAll = menu
      setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_MENUALL_NULL: (state) => {
      state.menuAll = []
      setStore({ name: 'menuAll', content: state.menuAll })
    },
    // SET_MENU: (state, menu) => {
    //   state.menu = menu
    //   setStore({ name: 'menu', content: state.menu })
    // },

    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
      setStore({
        name: 'userInfo',
        content: userInfo,
        type: 'session'
      })
    },

    SET_MENU: (state, params = {}) => {
      let { menu, type } = params
      if (type !== false) state.menu = menu
      setStore({
        name: 'menu',
        content: menu,
        type: 'session'
      })
    },
    SET_PERMISSIONS: (state, permissions) => {
      const list = {}
      for (let i = 0; i < permissions.length; i++) {
        list[permissions[i].authority] = true
      }

      state.permissions = list
      setStore({
        name: 'permissions',
        content: list,
        type: 'session'
      })
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSION: (state, permission) => {
      state.permission = {}
      permission.forEach((ele) => {
        state.permission[ele.authority] = true
      })
      setStore({
        name: 'permission',
        content: state.permission,
        type: 'session'
      })
    }
  }
}
export default user
