import { getToken, setToken, removeToken, setRefreshToken, getRefreshToken, removeRefreshToken } from "@/utils/auth"
import { login } from "@/api/login"
import CryptoJS from "crypto-js"
const { VITE_BX_CLIENT_ID, VITE_EDGE_CLIENT_ID } = import.meta.env
export const useUserStore = defineStore(
    "user",
    {
        state: () => ({
            token: getToken(),
            refreshToken: getRefreshToken(),
            userInfo: {},
            menuList: [],
            roles: [],
            permissions: []
        }),
        actions: {
            //登录
            login(userInfo) {
                let data = {
                    username: userInfo.username,
                    password: CryptoJS.MD5(userInfo.password).toString(),
                    grant_type: "password",
                    scope: "all"
                }
                return new Promise((resolve, reject) => {
                    login(data).then(res => {
                        if (res.error_code == "400") {
                            ElMessage({
                                message: res.error_description,
                                type: "warning"
                            })
                            reject("err")
                        } else if (res.error_code == "204") {
                            ElMessage({
                                message: "由于您长时间未登录，请修改密码后登录！",
                                type: "warning"
                            })
                            reject(204)
                        } else if (res.error_code == "203") {
                            ElMessage({
                                message: "由于您长时间未登录，请校验手机号！",
                                type: "warning"
                            })
                            reject(203)
                        } else if (res.error_code == "500") {
                            ElMessage({
                                message: res.error_description,
                                type: "warning"
                            })
                            reject("err")
                        } else {
                            setToken(res.access_token)
                            setRefreshToken(res.refresh_token)
                            this.userInfo = res.user
                            this.token = res.access_token
                            this.refreshToken = res.refresh_token
                            this.menuList = res.menus
                            this.permissions = getButtonPermiss([], res.menus)
                            resolve()
                        }
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            //tips:获取信息（不需要实现持久化 刷新浏览器 重新调用接口获取最新的信息才是正确的处理方式）
            RefreshInfo() {
                return new Promise((resolve, reject) => {
                    let data = {
                        refresh_token: getRefreshToken(),
                        grant_type: "refresh_token",
                        scope: "all"
                    }
                    login(data).then(res => {
                        setToken(res.access_token)
                        setRefreshToken(res.refresh_token)
                        this.token = res.access_token
                        this.userInfo = res.user
                        this.refreshToken = res.refresh_token
                        this.roles = res.roles
                        this.menuList = res.menus
                        this.permissions = getButtonPermiss([], res.menus)
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            //宝信登录
            bxLogin(code) {
                console.log("传递过code", code)
                return new Promise((resolve, reject) => {
                    login({
                        code,
                        source: VITE_BX_CLIENT_ID,
                        grant_type: "social",
                        scope: "all",
                    }).then(res => {
                        if (res.error_code == "400") {
                            ElMessage({
                                message: res.error_description,
                                type: "warning"
                            })
                            reject("err")
                        } else {
                            setToken(res.access_token)
                            setRefreshToken(res.refresh_token)
                            this.userInfo = res.user
                            this.token = res.access_token
                            this.refreshToken = res.refresh_token
                            this.menuList = res.menus
                            this.permissions = getButtonPermiss([], res.menus)
                            resolve()
                        }
                    })
                })
            },
            //边端登录
            edgeLogin(code) {
                return new Promise((resolve, reject) => {
                    login({
                        code,
                        source: VITE_EDGE_CLIENT_ID,
                        grant_type: "edge",
                        scope: "all",
                    }).then(res => {
                        setToken(res.access_token)
                        setRefreshToken(res.refresh_token)
                        this.userInfo = res.user
                        this.token = res.access_token
                        this.refreshToken = res.refresh_token
                        this.menuList = res.menus
                        this.permissions = getButtonPermiss([], res.menus)
                        resolve()
                    })
                })
            },
            // 退出系统
            logOut() {
                return new Promise((resolve, reject) => {
                    this.token = ""
                    this.refreshToken = ""
                    this.userInfo = {}
                    this.menuList = []
                    this.roles = []
                    this.permissions = []
                    removeToken()
                    removeRefreshToken()
                    resolve()
                })
            }
        }
    }
)

function getButtonPermiss(keys, List) {
    for (let li of List) {
        if (li.type == 2) {
            keys.push(li.code)
        }
        if (li.children && li.children.length > 0) {
            getButtonPermiss(keys, li.children)
        }
    }
    return keys
}