import { toRefs, shallowReadonly, ShallowRef } from 'vue'
import { queryTableDefine } from '@/services/api/common'
import { VueStore } from '../base'
import WebStorage from '@/utils/storage/base'

interface StoreState {
    loading: boolean;
    tableColumns: ShallowRef<Ermcp.TableDefineRsp[]>;
}

const store = new (class extends VueStore<StoreState>{
    constructor() {
        const storage = new WebStorage<Ermcp.TableDefineRsp[]>(sessionStorage, 'tableColumns', [])
        const state: StoreState = {
            loading: false,
            tableColumns: storage.getRef()
        }
        super(state)
    }

    actions = {
        /** 获取表格列列表 */
        getTableColumnList: () => {
            if (this.state.tableColumns.length) {
                return Promise.resolve()
            }
            this.state.loading = true
            return queryTableDefine({
                data: {
                    tableType: 2
                },
                success: (res) => {
                    this.state.tableColumns = res.data
                },
                complete: () => {
                    this.state.loading = false
                }
            })
        }
    }
})

export function useTableColumnStore() {
    return shallowReadonly({
        ...toRefs(store.state),
        ...store.actions,
        ...store.methods,
    })
}