import {getStore, setStore} from '@/util/store'
import {isURL, validatenull} from '@/util/validate'
import {getUserInfo, loginByUsername, logout, refreshToken} from '@/api/admin/login'
import {deepClone, encryption} from '@/util/util'
import webiste from '@/const/website'
import {getMenu} from '@/api/admin/menu'
import {applyId} from "@/util/self";
import {fetchSelectList} from "@/api/admin/dataAuth";
import route from "@/router/views/index"
import {Message} from "element-ui";

function addPath(ele, first) {
  const menu = webiste.menu
  const propsConfig = menu.props
  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: {},
    permissions: {},
    roles: [],
    menu: getStore({
      name: 'menu'
    }) || [],
    menuAll: [],
    dataAuths: getStore({
      name: 'dataAuths'
    }) || [],
    expires_in: getStore({
      name: 'expires_in'
    }) || '',
    access_token: getStore({
      name: 'access_token'
    }) || '',
    refresh_token: getStore({
      name: 'refresh_token'
    }) || ''
  },

  actions: {
    // 根据用户名登录
    LoginByUsername({commit}, userInfo) {
      localStorage.setItem('username',userInfo.username)
      // const user = encryption({
      //   data: userInfo,
      //   key: 'thanks,jiayuecsc',
      //   param: ['password']
      // })
      const param = new URLSearchParams()
      param.append('username', userInfo.username)
      param.append('password', userInfo.password)
      return new Promise((resolve, reject) => {

        loginByUsername(param).then(response => {
         if(response !== undefined){
           const data = response.data
           commit('SET_ACCESS_TOKEN', data.data)
           commit('SET_REFRESH_TOKEN', data.data)
           // commit('SET_EXPIRES_IN', data.expires_in)
           commit('CLEAR_LOCK')
           resolve()
         }else{
           Message({
             type:'error',
             message:'用户名或者密码错误,请重新输入'
           })
         }

        })
      })
    },
    // 获取数据权限
    GetDataAuth({commit}) {
      return new Promise((resolve, reject) => {
        fetchSelectList().then(response => {
          const data = response.data.data
          commit('SET_DATA_AUTHS', data || [])
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    GetUserInfo({commit}) {
      return new Promise((resolve, reject) => {
        // getUserInfo().then((res) => {
        //   const data = res.data.data || {}
          commit('SET_USER_INFO', "admin")
          commit('SET_ROLES', "admin" || [])
          commit('SET_PERMISSIONS', "admin" || [])

          resolve(data)
        }).catch((err) => {
          reject()
        })
      // })
    },
    // 刷新token
    RefreshToken({commit, state}) {
      return new Promise((resolve, reject) => {
        refreshToken(state.refresh_token).then(response => {
          const data = response.data
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          commit('CLEAR_LOCK')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({commit}) {
      return new Promise((resolve, reject) => {
        // logout().then(() => {
          commit('SET_MENU', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_USER_INFO', {})
          commit('SET_ACCESS_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '')
          commit('SET_EXPIRES_IN', '')
          commit('SET_ROLES', [])
          commit('DEL_ALL_TAG')
          commit('CLEAR_LOCK')
          commit('SET_DATA_AUTHS', [])
          resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },
    // 注销session
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_MENU', [])
        commit('SET_PERMISSIONS', [])
        commit('SET_USER_INFO', {})
        commit('SET_ACCESS_TOKEN', '')
        commit('SET_REFRESH_TOKEN', '')
        commit('SET_ROLES', [])
        commit('DEL_ALL_TAG')
        commit('CLEAR_LOCK')
        commit('SET_DATA_AUTHS', [])
        resolve()
      })
    },
    // 获取系统菜单
    GetMenu({commit,state}, obj) {

      let routes = []
      route.forEach(r => {
        r.id != undefined ? routes.push(r) : routes
      })
      return new Promise(resolve => {
        let username =localStorage.getItem('username')
        let params = {'username':username}
        getMenu(params).then((res) => {
        let menu = deepClone(res.data.data)
          menu = Array.from(menu)
          menu.forEach(ele => {
            addPath(ele)
          })
          let type = true
          commit('SET_MENU', {type, menu})
          resolve(menu)
        })
      })
    }

  },
  mutations: {
    SET_ACCESS_TOKEN: (state, access_token) => {
      state.access_token = access_token
      setStore({
        name: 'access_token',
        content: state.access_token,
        type: 'session'
      })
    },
    SET_EXPIRES_IN: (state, expires_in) => {
      state.expires_in = expires_in
      setStore({
        name: 'expires_in',
        content: state.expires_in,
        type: 'session'
      })
    },
    SET_REFRESH_TOKEN: (state, rfToken) => {
      state.refresh_token = rfToken
      setStore({
        name: 'refresh_token',
        content: state.refresh_token,
        type: 'session'
      })
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_MENU: (state, params = {}) => {
      let {menu, type} = params;
      if (type !== false) state.menu = menu
      setStore({
        name: 'menu',
        content: menu,
        type: 'session'
      })
    },
    SET_MENU_ALL: (state, menuAll) => {
      state.menuAll = menuAll
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      const list = {}
      for (let i = 0; i < permissions.length; i++) {
        list[permissions[i]] = true
      }
      state.permissions = list
    },
    SET_DATA_AUTHS: (state, dataAuths) => {
      state.dataAuths = dataAuths
      setStore({
        name: 'dataAuths',
        content: dataAuths,
        type: 'session'
      })
    }
  }

}
export default user
