import { BtnClassName, BtnList } from '@/common/components/buttonList/interface';
import { ModalName } from '@/common/constants/modalName';
import { OperationTabMenu } from '@/services/go/commonService/interface';
import { sessionStorageUtil } from "@/utils/storage";
import { inject, onUnmounted, Ref, ref } from "vue";
import { openModal } from "../modal";
import { ButtonListKey } from '../table/interface';

/**
 * 获取class 名
 * @param val 
 * @returns 
 */
function getClassName(val: string): BtnClassName {
    let result: BtnClassName = 'btnDeafault'
    if (val.includes('disable') || val.includes('cancle') || val.includes('delete')) {
        result = 'btnDanger'
    } else if (val === '') {
        result = 'btnDeafault'
    } else if (val.includes('add')) {
        result = 'operBtn'
    } else {
        result = 'btnPrimary'
    }
    return result
}

export function getBtnList(menuType: keyof ButtonListKey, hasDetail: boolean) {
    // 获取 数据
    const permissionData = inject('thirdMenuList') as Ref<OperationTabMenu[]>;
    const name = 'permissionData'
    // 存入sessionStorageUtil 是为了处理页面刷新的情况（这个时候重新从服务获取数据，但页面已经先加载了，vue 中的 依赖注入在异步中不能建立通信）
    const data: OperationTabMenu[] = permissionData.value.length ? permissionData.value : sessionStorageUtil.getItem(name)
    sessionStorageUtil.setItem(name, data)

    const commonBtn = ref<BtnList[]>([]); // 通用按钮列表，不用选中数据才显示
    const forDataBtn = ref<BtnList[]>([]); // 针对数据按钮列表，选中某条数据才显示

    const list = data.find((e) => e.code === menuType);
    if (list && list.children) {
        list.children.forEach(e => {
            const { code, type, title } = e;
            if (type === 2) { // 按钮类型
                const { openAction } = openModal(code as keyof ModalName);
                const item = { lable: title, callback: openAction, className: getClassName(code) }
                const commonName = ['新增'] // 目前通用的按钮只要新增，需要添加其它的时候需要往这里添加
                if (commonName.includes(title)) { // 
                    commonBtn.value.push(item)
                } else {
                    forDataBtn.value.push(item)
                }
            }
        })
    } else {
        console.warn(`menuType: ${menuType}未找到`)
    }
    // 详情
    if (hasDetail) {
        const { openAction } = openModal('detail')
        forDataBtn.value.push({ lable: '详情', callback: openAction, className: getClassName('') })
    }


    onUnmounted(() => {
        sessionStorageUtil.removeItem(name)
    });
    return { commonBtn, forDataBtn }
}