import { BtnClassName, BtnListType } from '@/common/components/btnList/interface';
import { EnumRouterName } from '@/common/constants/enumRouterName';
import { ModalName } from '@/common/constants/modalName';
import { OperationTabMenu } from '@/services/go/commonService/interface';
import { sessionStorageUtil } from "@/utils/storage";
import { inject, ref, Ref, toRaw, unref } from 'vue';
import { openModal } from "../modal";
import { ButtonListKey } from './interface';

/**
 * 获取class 名
 * @param val
 * @returns
 */
export function getClassName(val: string): BtnClassName {
    let result: BtnClassName = 'btnDeafault'
    const btnDanger = ['disable', 'cancle', 'cancel', 'delete', 'logout', 'locked', 'refuse']
    const operBtn = ['add', 'modify', 'reset', 'credit', 'payment', 'confirm_withdrawal', 'complete_stocking', 'upload_logistics', 'buy', 'listed', 'delisting',
        'receipt', 'confirm_pickup']
    const map = new Map<BtnClassName, string[]>([
        ['btnDanger', btnDanger],
        ['operBtn', operBtn],
    ])
    for (const [key, value] of map) {
        for (const item of value) {
            if (val.includes(item)) {
                result = key
                break;
            }
        }
    }
    return result
}

export function getThirdMenuData(): OperationTabMenu[] {
    const permissionData = inject('thirdMenuList') as Ref<OperationTabMenu[]>;
    const temp = unref(permissionData)
    const name = 'permissionData'
    // 存入sessionStorageUtil 是为了处理页面刷新的情况（这个时候重新从服务获取数据，但页面已经先加载了，vue 中的 依赖注入在异步中不能建立通信）
    const data: OperationTabMenu[] = temp.length ? toRaw(temp) : sessionStorageUtil.getItem(name)
    sessionStorageUtil.setItem(name, data)
    console.log('当前页面配置的数据： ', data)
    return data;
}
// 旧的获取配置按钮逻辑，
export function handleBtnList(list: OperationTabMenu | undefined, menuType: keyof ButtonListKey, hasDetail: boolean, commonName: string[] = ['新增']) {
    const commonBtn = ref<BtnListType[]>([]); // 通用按钮列表，不用选中数据才显示
    const forDataBtn = ref<BtnListType[]>([]); // 针对数据按钮列表，选中某条数据才显示
    if (list && list.children) {
        list.children.forEach(e => {
            const { code, type, title, isshow } = e;
            if (type === 2 && isshow) { // 按钮类型
                const { openAction } = openModal(code as keyof ModalName);
                const item = { lable: title, callback: openAction, className: getClassName(code), code: code }
                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(''), code: 'detail' })
    }
    return { commonBtn, forDataBtn }
}

// 新的获取按钮逻辑，有时间把旧的都替换掉
export function _handleBtnList_(list: OperationTabMenu | undefined, hasDetail: boolean,) {
    const result = ref<BtnListType[][]>([])
    const temp: [number, OperationTabMenu[] | undefined] = [0, list?.children]
    while (temp[1] && temp[1].length) {
        temp[1].forEach((e) => {
            const { code, type, title, isshow } = e;
            const index = temp[0]
            if (!Array.isArray(result.value[index])) {
                result.value[index] = []
            }
            if (type === 2 && isshow && code !== 'none_btn') {
                // 按钮类型 并且显示
                // 当code为 none_btn， 是空按钮，（返回按钮确保数据结构统一）
                const item = { lable: title, code, className: getClassName(code) }
                result.value[index].push(item)
            }
        })
        const children = temp[1][0].children
        if (children && children.length) {
            temp[0] = temp[0] + 1
            temp[1] = children
        } else {
            temp[1] = []
        }
    }
    // 详情
    if (hasDetail) {
        const { openAction } = openModal('detail')
        const item = { lable: '详情', code: 'detail', className: getClassName('') }
        const len = result.value.length;
        if (len) {
            result.value[len - 1].push(item)
        } else {
            result.value = [[], [item]]
        }
    }

    if (result.value.length === 0) {
        result.value = [[], []]
    }
    console.log('按钮列表数据', result);

    return result
}

export function _handleBtnList(list: OperationTabMenu | undefined, hasDetail: boolean,) {
    const result = ref<BtnListType[][]>([])
    const temp: [number, OperationTabMenu[] | undefined] = [0, list?.children]
    while (temp[1] && temp[1].length) {
        temp[1].forEach((e) => {
            const { code, type, title, isshow } = e;
            const index = temp[0]
            if (!Array.isArray(result.value[index])) {
                result.value[index] = []
            }
            if (type === 2 && isshow) { // 按钮类型 并且显示
                const { openAction } = openModal(code as keyof ModalName);
                const item = { lable: title, callback: openAction, className: getClassName(code), code: code }
                result.value[index].push(item)
            }
        })
        const children = temp[1][0].children
        if (children && children.length) {
            temp[0] = temp[0] + 1
            temp[1] = children
        } else {
            temp[1] = []
        }
    }
    // 详情
    if (hasDetail) {
        const { openAction } = openModal('detail')
        const item = { lable: '详情', callback: openAction, className: getClassName(''), code: 'detail' }
        const len = result.value.length;
        if (len) {
            result.value[len - 1].push(item)
        } else {
            result.value = [[], [item]]
        }
    }


    return result
}

// 获取单据按钮列表
export function getOrderBtnList(list: OperationTabMenu[], hasDetail = false) {
    const result = ref<BtnListType[]>([])
    list.forEach(el => {
        const { code, type, title, isshow } = el;
        if (type === 2 && isshow) {
            const item = { lable: title, code, className: getClassName(code) }
            result.value.push(item)
        }
    });
    // 详情
    if (hasDetail) {
        const item = { lable: '详情', code: 'detail', className: getClassName('') }
        result.value.push(item)
    }
    console.log('单据按钮列表', result);
    return result
}

/**
 * 获取表格操作按钮列表
 * @param menuType
 * @param hasDetail 操作按钮是否需要详情按钮（详情按钮服务 不配置）
 * @returns
 */
export function getBtnList(menuType: keyof ButtonListKey, hasDetail: boolean, commonName: string[] = ['新增']) {
    const data = getThirdMenuData()
    const list = data.find((e) => e.code === menuType);
    return handleBtnList(list, menuType, hasDetail, commonName)
}

export function _getBtnList(menuType: keyof ButtonListKey, hasDetail: boolean): Ref<BtnListType[][]> {
    const data = getThirdMenuData()
    const list = data.find((e) => e.code === menuType);
    return _handleBtnList(list, hasDetail)
}

/**
 * 根据当前tab页面的code 枚举查找对应的数据
 * @param menuType
 * @returns
 */
export function findChildList(menuType: EnumRouterName): OperationTabMenu | undefined {
    const data = getThirdMenuData()
    let list: OperationTabMenu | undefined = undefined
    // 这里处理有两层路由菜单
    function findFn(arr: OperationTabMenu[]) {
        for (let item of arr) {
            if (item.code === menuType) {
                list = item
                return
            } else {
                findFn(item.children)
            }
        }
        return null
    }
    findFn(data)
    return list
}
// 处理有三级路由的特殊情况，例如仓单贸易
export function getBtnList_(menuType: EnumRouterName, hasDetail: boolean) {
    const list = findChildList(menuType)
    return _handleBtnList_(list, hasDetail)
}
