import { login, singleLogin, logout, getInfo, smsLogin, getConfig, systemConfig, chungengUserLogin } from '@/api/login'

import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    deptId: '',
    deptLength: 0,
    year: '',
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    userRoles: [],
    permissions: [],
    bookName: '',
    setUpModuleId: '',
    //获取登录页相关标题
    systemConfigList: [],
    //系统名称
    loginSystemName: '',
    //浏览器页签名称
    browserName: '',
    //技术支持
    technicalSupport: '',
    //是否阅读须知
    noticeThree: '',
    //界面logo
    globalLogo: '',
    //系统大屏logo
    screenLogo: ''
  },

  mutations: {
    SET_YEAR: (state, payload) => {
      state.year = payload
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_SETUPMODULE: (state, setUpModuleId) => {
      state.setUpModuleId = setUpModuleId
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_NICKNAME: (state, nickName) => {
      state.nickName = nickName
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USERROLES: (state, roles) => {
      state.userRoles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_LOGINDEPTID: (state, loginDeptId) => {
      state.loginDeptId = loginDeptId
    },
    SET_LOGINBOOKID: (state, loginBookId) => {
      state.loginBookId = loginBookId
    },
    SET_DEPTNAME: (state, deptName) => {
      state.deptName = deptName
    },
    SET_DEPT_NAME: (state, deptname) => {
      state.deptname = deptname
    },
    SET_LEADER: (state, leader) => {
      state.leader = leader
    },
    SET_DEPTID: (state, deptId) => {
      state.deptId = deptId
    },
    SET_DEPTIDLENGTH: (state, deptLength) => {
      state.deptLength = deptLength
    },
    SET_BOOKNAME: (state, bookName) => {
      state.bookName = bookName
    },
    SET_BUSINESSOWNERSHIP: (state, businessOwnership) => {
      state.businessOwnership = businessOwnership
    },
    SET_OFFICIALSEAL: (state, officialSeal) => {
      state.officialSeal = officialSeal
    },
    SET_DEPTLEVEL: (state, deptLevel) => {
      state.deptLevel = deptLevel
    },
    SET_BASEROUTINGURL: (state, baseRoutingUrl) => {
      state.baseRoutingUrl = baseRoutingUrl
    },
    SET_BUSINESSLEVEL: (state, businessLevel) => {
      state.businessLevel = businessLevel
    },
    SET_BOOKTYPE: (state, bookType) => {
      state.bookType = bookType
    },
    SET_PARENTDEPTNAME: (state, parentDeptName) => {
      state.parentDeptName = parentDeptName
    },
    SET_USERTYPE: (state, userType) => {
      state.userType = userType
    },
    SET_ALLDEPTNAME: (state, allDeptName) => {
      state.allDeptName = allDeptName
    },
    SET_STSTEMCONFIGlIST: (state, systemConfigList) => {
      state.systemConfigList = systemConfigList
    },
    SET_LOGINSYSTEMNAME: (state, loginSystemName) => {
      state.loginSystemName = loginSystemName
    },
    SET_BORWSERNAME: (state, browserName) => {
      state.browserName = browserName
    },
    SET_TECHNICALSUPPORT: (state, technicalSupport) => {
      state.technicalSupport = technicalSupport
    },
    SET_BIGSCREENURL: (state, bigscreenUrl) => {
      state.bigscreenUrl = bigscreenUrl
    },
    SET_NOTICETHREE: (state, noticeThree) => {
      state.noticeThree = noticeThree
    },
    SET_GLOBALLOGO: (state, globalLogo) => {
      state.globalLogo = globalLogo
    },
    SET_SCREENLOGO: (state, screenLogo) => {
      state.screenLogo = screenLogo
    },
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    SingleLogin ({ commit }, userInfo) {
      const code = userInfo.code
      return new Promise((resolve, reject) => {
        singleLogin(code).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })

    },



    //设置用户当前模块系统
    setUpModule ({ commit }, setUpModuleId) {
      commit('SET_SETUPMODULE', setUpModuleId)
    },

    //短信验证码登录
    SmsLogin ({ commit }, userInfo) {
      const mobile = userInfo.mobile.trim()
      const smsCode = userInfo.smsCode
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        smsLogin(mobile, smsCode, uuid).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })

    },

    // 获取用户信息
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(res => {
          if (res && res.code && res.code == 200) {
            const user = res.user
            // const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
            const avatar = user.avatar == "" ? "" : process.env.VUE_APP_BASE_API + user.avatar;
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', res.roles)
              commit('SET_PERMISSIONS', res.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_USERROLES', user.roles)
            commit('SET_BOOKNAME', user.bookName)
            commit('SET_NAME', user.userName)
            commit('SET_USERID', user.userId)
            commit('SET_NICKNAME', user.nickName)
            commit('SET_LOGINDEPTID', user.loginDeptId)
            commit('SET_LOGINBOOKID', user.loginBookId)
            commit('SET_DEPTNAME', user.deptName)
            commit('SET_DEPT_NAME', user.dept.deptName)
            commit('SET_LEADER', user.dept.leader)
            commit('SET_DEPTID', user.deptId)
            commit('SET_DEPTIDLENGTH', user.deptLength)
            commit('SET_AVATAR', avatar)
            commit('SET_BUSINESSOWNERSHIP', user.businessOwnership)
            commit('SET_BUSINESSLEVEL', user.businessLevel)
            commit('SET_BOOKTYPE', user.bookType)
            commit('SET_PARENTDEPTNAME', user.parentDeptName)
            commit('SET_USERTYPE', user.userType)
            commit('SET_ALLDEPTNAME', user.allDeptName)
            commit('SET_NOTICETHREE', user.noticeThree)
            commit('SET_OFFICIALSEAL', user.officialSeal)
          }

          getConfig().then((num) => {
            // //console.log(res)
            if (num && num.code == 200) {
              let content = num.data;
              commit('SET_DEPTLEVEL', content.deptLevel)
            }
          })
          systemConfig({ configKey: 'system.attachment' }).then((data) => {
            if (data.code == 200) {
              let content = data.rows;
              if (content.length != 0) {
                let baseRoutingUrl = content[0].configValue;
                commit('SET_BASEROUTINGURL', baseRoutingUrl)

              }
            }
          })
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    //获取登录页相关标题
    systemTitle ({ commit, state }) {
      return new Promise((resolve, reject) => {
        systemConfig({ configKey: 'system' }).then((data) => {
          let content = data.rows;
          commit('SET_STSTEMCONFIGlIST', content)
          //系统名称
          let loginSystemName = '';
          //浏览器页签名称
          let browserName = '';
          //技术支持
          let technicalSupport = '';
          //大数据指挥舱
          let bigscreenUrl = '';
          //界面logo
          let globalLogo = '';
          //系统大屏logo
          let screenLogo = '';

          content.forEach((v, i) => {
            if (v.configKey == 'system.login.name') {
              loginSystemName = v.configValue
            } else if (v.configKey == 'system.browser.name') {
              browserName = v.configValue
            } else if (v.configKey == 'system.company.name') {
              technicalSupport = v.configValue
            } else if (v.configKey == 'system.bigscreen.url') {
              bigscreenUrl = v.configValue
            } else if (v.configKey == 'system.logo.pic') {
              globalLogo = v.configValue
            } else if (v.configKey == 'system.logo5.pic') {
              screenLogo = v.configValue
            }
          })

          commit('SET_LOGINSYSTEMNAME', loginSystemName)
          commit('SET_BORWSERNAME', browserName)
          commit('SET_TECHNICALSUPPORT', technicalSupport)
          commit('SET_BIGSCREENURL', bigscreenUrl)
          commit('SET_GLOBALLOGO', globalLogo)
          commit('SET_SCREENLOGO', screenLogo)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 退出系统
    LogOut ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resolve()
      })
    },

    // 更新用户信息


    // 春耕App用户登录
    ChungengLogin ({ commit }, userInfo) {
      const code = userInfo.code;
      return new Promise((resolve, reject) => {
        chungengUserLogin(code).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
}

export default user
