import { login, getInfo, logout, getUserInfo, CodeSr, menulist } from '@/api/user'
import {
    getToken,
    setLoginStatus,
    getUserIndex,
    getLoginName,
    setLoginName,
    setUserIndex,
    setToken,
    removeToken,
    setUserInfo,
    appuserinfo,
    setRefreshToken,
    removeRefreshToken,
    removeClear,
    getLoginStatus
} from '@/utils/auth'
import router, { resetRouter } from '@/router/index'
import tagsView from '@/store/modules/tagsView'
import store from '@/store'

const state = {
    token: getToken(),
    name: '',
    loginName: getLoginName(),
    avatar: '',
    userIndex1: getUserIndex(),
    introduction: '',
    roles: [],
    perms: [],
    userInfo: null,
    loginStatus: getLoginStatus(),
    lineID: '',
    menulists: []
}
// const getters= {
//     info(state) {
//       return state.info;
//     },
//   },
const mutations = {
    lineID: (state, id) => {
        state.lineID = id
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
        state.introduction = introduction
    },
    SET_NICKNAME: (state, name) => {
        state.name = name
    },
    SET_USERINDEX: (state, userIndex1) => {
        state.userIndex1 = userIndex1
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_PERMS: (state, perms) => {
        state.perms = perms
    },
    SET_LOGINNAME: (state, loginName) => {
        state.loginName = loginName
    },
    SET_LOGINSTATUS: (state, loginStatus) => {
        state.loginStatus = loginStatus
    },
    RESET_STATE: state => {
        state.userInfo = null
        // localStorage.removeItem('APP_USER_INFO')
    },
    SET_USER_INFO: (state, data) => {
        state.userInfo = data
    },
    SET_MUENU: (state, data) => {
        state.menulists = data
    }
}
var usermessage
const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password, imageCode, verifyCode } = userInfo
        //resetToken({commit})
        var loginName = username
        commit('SET_LOGINNAME', loginName)
        setLoginName(loginName)
        return new Promise((resolve, reject) => {
            //登录认证
            login({
                username: username,
                password: password,
                imageCode: imageCode,
                grant_type: 'captcha',
                verifyCode: verifyCode
                // grant_type: "password",
            })
                .then(response => {
                    if (response.code == 'A0000') {
                        usermessage = response.data
                        const { access_token, refresh_token, token_type, userIndex, userType } = response.data
                        window.userIndex1 = userIndex
                        window.userType = userType
                        window.sessionStorage.setItem('type', userType)
                        const userIndex1 = userIndex
                        window.userIndex1 = userIndex
                        const token = token_type + ' ' + access_token
                        commit('SET_USERINDEX', userIndex1)
                        commit('SET_TOKEN', token)
                        const loginStatus = true
                        commit('SET_LOGINSTATUS', loginStatus)
                        setLoginStatus(loginStatus)
                        setUserIndex(userIndex1)
                        setToken(token)
                        setRefreshToken(refresh_token)

                        //setUserInfo(JSON.stringify(response.data))
                        //commit('SET_USER_INFO', response.data)
                        resolve(response)
                    }
                    if (response.code == 'A0101') {
                        resolve(response)
                    }
                })
                .catch(error => {
                    //debugger
                    reject(error)
                })
        })
    },
    getmenu({ commit }) {
        return new Promise((resolve, reject) => {
            menulist()
                .then(res => {
                    if (res.code == 'A0000') {
                        // this.$store.state.menulists = res.data
                        commit('SET_MUENU', res.data)
                        resolve(res)
                    }
                })
                .catch(error => {
                    reject(error)
                })
        })
    },
    //获取用户信息
    getInfo({ commit }) {
        return new Promise((resolve, reject) => {
            if (process.env.VUE_APP_MODE === 'jbqr') {
                
                let userInfo=window.localStorage.getItem('adminInfo')
                
                setUserInfo(userInfo)
                if (!userInfo) {
                    reject('验证失败请重新登录')
                }

                commit('SET_USER_INFO', userInfo)
                resolve(userInfo)
            } 
            // else if (process.env.VUE_APP_MODE === 'cgyqr') {
            //     let userInfo = {
            //         name: '管理员',
            //         deptId: '5699e5916a18a6381e1ac92da5bd2628',
            //         phone: '',
            //         email: '',
            //         limitIpStart: '0.0.0.0',
            //         limitIpEnd: '255.255.255.255',
            //         limitTime: '0-23',
            //         casualUser: 1,
            //         type: 2,
            //         smsNotice: 0,
            //         emailNotice: 0,
            //         role: ['正式用户'],
            //         devCode: null,
            //         headSculpture: null,
            //         id: '09188831028a42d8b0fea0d443ffbfb1',
            //         loginName: 'cgyqrsy',
            //         state: 1,
            //         registerTime: '2023-03-31T10:47:39',
            //         loginTime: '2023-09-11T11:18:56',
            //         deptName: '全国',
            //         areaId: '0',
            //         areaName: '全国',
            //         deptLevel: 1,
            //         roleList: ['ff63e0fd89f5e990a1cb8b4cb37e0f5f'],
            //         roleCode: ['formal_user']
            //     }
            //     setUserInfo(JSON.stringify(userInfo))
            //     if (!userInfo) {
            //         reject('验证失败请重新登录')
            //     }
            //     commit('SET_USER_INFO', userInfo)
            //     resolve(userInfo)
            // }
             else {
                //获取用户信息接口
                var data = {
                    id: window.sessionStorage.cnid
                }
                getUserInfo(data)
                    .then(response => {
                        setUserInfo(JSON.stringify(response.data))
                        if (!response.data) {
                            reject('验证失败请重新登录')
                        }
                        commit('SET_USER_INFO', response.data)
                        resolve(response.data)
                    })
                    .catch(error => {
                        reject(error)
                    })
            }
        })
    },
    logout({ commit, state, dispatch }) {
        // 重置已访问视图和缓存视图
        window.localStorage.setItem('tag', 'dag')

        return new Promise((resolve, reject) => {
            logout(state.token)
                .then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    removeToken()
                    appuserinfo()
                    removeRefreshToken()
                    resetRouter()
                    commit('RESET_STATE')
                    //if (process.env.VUE_APP_USE_LOGIN === 'true') {
                    router.push(`/login`)

                    // } else {
                    //   const loginPath = ''
                    //   if (!loginPath) {
                    //     console.error('开发者请填写单点登录页面的地址')
                    //   }
                    //  }
                    store.dispatch('tagsView/delAllTags').then(() => {})
                    resolve()
                })
                .catch(error => {
                    reject(error)
                })
        })
    },

    refreshToken({ commit }, refreshToken) {
        //resetToken()
        commit('SET_TOKEN', undefined)
        return new Promise((resolve, reject) => {
            //登录接口
            login({
                grant_type: 'refresh_token',
                refresh_token: refreshToken,
                username: window.sessionStorage.cnloginname
            })
                .then(response => {
                    const { access_token, refresh_token, token_type } = response.data
                    // alert("access_token"+access_token)
                    // //console.log("refresh_token:", refresh_token);
                    //  alert('token_type'+token_type)
                    const token = token_type + ' ' + access_token
                    commit('SET_TOKEN', token)
                    setToken(token)
                    setRefreshToken(refresh_token)
                    resolve(token)
                })
                .catch(error => {
                    reject(error)
                })
        })
    },
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            //commit('SET_ROLES', [])
            //commit('SET_PERMS', [])
            removeToken()
            removeRefreshToken()
            removeClear()
            resolve()
            setTimeout(() => {
                location.reload()
            }, 1000)
            //router.push(`/login?redirect=${router.app.$route.fullPath}`)
            router.push('/login')
        })
    },
    remToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            // commit('SET_ROLES', [])
            //commit('SET_PERMS', [])
            removeToken()
            removeRefreshToken()
            removeClear()
            resolve()
        })
    },

    // 动态修改权限
    async changeRoles({ commit, dispatch }, role) {
        const token = role + '-token'

        commit('SET_TOKEN', token)
        setToken(token)

        const { roles } = await dispatch('getUserInfo')

        resetRouter()

        // 基于角色生成可访问的路线图
        const accessRoutes = await dispatch('permission/generateRoutes', roles, {
            root: false
        })
        //动态添加可访问的路由
        router.addRoutes(accessRoutes)

        // 重置已访问视图和缓存视图
        dispatch('tagsView/delAllViews', null, { admin: true })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
