import { defineStore } from 'pinia'
import { addLog } from '@/api'
import { loadShopInfo } from '@/api/user'
import { addDynamicRoutes } from '@/router/vue-router'
import { appModules,mainMenu } from '@/utils/setup'
import dayjs from 'dayjs'

const make_routes = (app_list) => {
    return appModules.filter(item => app_list.includes(item.name))
}

const make_menus = (app_list) => {
    return appModules.filter(item => app_list.includes(item.name)).map(item => item.title)
}

export const useUserStore = defineStore('user-info',{
    state: () => {
        return {
            userInfo: {},
            shopInfo: {},
            routerList: [],
            menuList: [],
            groups: [],
            partner: [],
        }
    },
    actions: {
        async setInfo(userinfo) {
            this.userInfo = userinfo
            let config = userinfo.config ? JSON.parse(userinfo.config) : {groups: [],app: []}
            switch (+userinfo.role) {
                case 0:
                    this.routerList = appModules
                    break
                case 1:
                    this.routerList = make_routes(config.app)
                    break
                case 2:
                    this.routerList = make_routes(config.app)
                    break
            }
            await addDynamicRoutes(this.routerList)
            this.menuList = mainMenu
            const {data: res} = await loadShopInfo()
            if (res.error === 0) {
                this.shopInfo = res.data
            } else {
                this.shopInfo = {}
            }
            this.groups = []
            if(+userinfo.role == 0) {
                this.userInfo.team = this.shopInfo.account.map(item => item.id)
                this.groups.push({
                    name: '成员组',
                    member: this.shopInfo.account.filter(item => +item.role != 0).map(item => item.id)
                })
            } else {
                this.groups = config.groups
                if(+userinfo.role == 1 && config.groups.length == 0) {
                    this.groups.push({
                        name: '默认组',
                        member: this.shopInfo.account.filter(item => +item.role == 2).map(item => item.id)
                    })
                }
            }
            await addLog(0,this.logName,'login',dayjs().format('YYYY-MM-DD HH:mm:ss'))
        },
        async addMainRoute() {
            await addDynamicRoutes(this.routerList)
        },
        clearInfo() {
            this.userInfo = {}
            this.groups = []
            this.partner = []
            this.shopInfo = {}
            this.routerList = []
            this.menuList = []
        },
        async setUserGroup(name, member=[],idx=-1) {
            if (!name || name.trim() === '') {
                throw new Error('工作组名称不能为空')
            }
            if (idx === -1) {
                this.groups.push({name,member})
            } else {
                this.groups[idx] = {name,member}
            }
        },
        async logout() {
            await addLog(0,this.logName,'logout',dayjs().format('YYYY-MM-DD HH:mm:ss'))
            this.clearInfo()
        }
    },
    getters: {
        userId: (state) => {
            return +state.userInfo.id || 0
        },
        userName: (state) => {
            return state.userInfo.name || ''
        },
        logName: (state) => {
            return `${state.userInfo.name || ''}|${state.userInfo.id || ''}`
        },
        nickname: (state) => {
            return state.userInfo.nickname || ''
        },
        sellerId: (state) => {
            return +state.userInfo.seller_id || 0
        },
        sellerName: (state) => {
            return state.shopInfo.seller_name || state.shopInfo.true_name || ''
        },
        isAdmin: (state) => {
            return +state.userInfo.role == 0 || +state.userInfo.role == 1
        },
        isSalesman: (state) => {
            return +state.userInfo.role == 2
        },
        isLoggedIn: (state) => {
            return state.userInfo.id && +state.userInfo.id > 0 ? true : false
        },
        hasRouterList: (state) => {
            return state.routerList.length > 0
        },
        userArray: (state) => {
            return [state.userInfo.id,...new Set([...state.groups.map(g => g.member).flat()])]
        },
        shopMember: (state) => {
            return Object.fromEntries(state.shopInfo.account.map(m => [m.id,m.nickname]))
        },
        groupsInfo: (state) => {
            let new_groups = []
            state.groups.forEach(group => {
                let members = []
                group.member.forEach(id => {
                    let name = ''
                    let item = state.shopInfo.account.find(el => el.id === id)
                    if(item) {
                        name = item.nickname || item.name
                    }
                    members.push({
                        id,
                        name
                    })
                })
                new_groups.push({
                    name: group.name,
                    member: members
                })
            })
            return new_groups
        },
    },
    persist: true
})

export const useInquiryListStore = defineStore('inquiry-list',{
    state: () => {
        return {
            currentPage: 1,
            pageSize: 20,
            keys: {}
        }
    },
    actions: {
        reset() {
            this.currentPage = 1
            this.pageSize = 20
            this.keys = {}
        }
    },
    getters: {}
})

export const useOrderListStore = defineStore('order-list',{
    state: () => {
        return {
            currentPage: 1,
            pageSize: 20,
            keys: {}
        }
    },
    actions: {
        reset() {
            this.currentPage = 1
            this.pageSize = 20
            this.keys = {}
        }
    },
    getters: {}
})
