import { getFlowDetail, startFlow } from "/@/api/flow/flow";
import { useGlobalFlowStore } from '/@/stores/flow';
import { h, ref, createApp } from "vue";
import { i18n } from '/@/i18n';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
/**
 * 处理用户选择逻辑
 * @param process 流程节点
 * @param params 流程参数
 * @param flowId
 * @returns 流程实例ID或错误
 */
const handleUserSelection = (process: any, params: any,flowId:string): Promise<{ processInstanceId: string }> => {
    if (!params.paramMap) params.paramMap = {};

    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve, reject) => {
        const container = document.createElement('div');
        container.id = 'dialog-container';
        document.body.appendChild(container);
        // 确保容器可见
        container.style.display = 'block';
        const visible = ref(true);
        let isResolved = false;

        // 将 timeout 声明移到函数开头
        let timeout:any;

        // 动态导入组件
        const {default: EmployeesDialog} = await import("/@/components/OrgSelector/employeesDialog.vue");

        // 创建应用实例
        const app = createApp({
            setup() {
                const handleConfirm = (checkedList: any[]) => {
                    if (checkedList.length > 0 && !isResolved) {
                        params.paramMap[`${process.childNode.id}_assignee_select`] = checkedList;
                        visible.value = false;
                        setTimeout(async () => {
                            destroy();
                            try {
                              const res =  await startProcessDirectly(flowId, params);
                              resolve(res);
                            } catch (err) {
                                reject(err);
                            }
                            isResolved = true;
                        }, 300);
                    }
                };

                const handleCancel = () => {
                    if (!isResolved) {
                        visible.value = false;
                        setTimeout(() => {
                            destroy();
                            reject(new Error('用户取消选择'));
                            isResolved = true;
                        }, 300);
                    }
                };

                return () => h(EmployeesDialog, {
                    visible: visible.value,
                    'onUpdate:visible': (val: boolean) => {
                        if (!val && !isResolved) {
                            handleCancel();
                        }
                    },
                    type: 'user',
                    multiple: process.multiple,
                    selectSelf: true,
                    data: [],
                    onChange: handleConfirm
                });
            }
        });

        app.use(i18n);
        app.use(ElementPlus); // 添加 Element Plus
        app.mount(container);

        const destroy = () => {
            if (!isResolved) {
                if (timeout) clearTimeout(timeout);
                app.unmount();
                if (container.parentNode) {
                    document.body.removeChild(container);
                }
            }
        };

    });
};


// 其他函数保持不变...
/**
 * 调用流程函数（主入口）
 * @param flowIdKey 流程ID Key
 * @param params 流程参数
 * @returns 流程实例ID或错误
 */
export const flowFn = async (flowIdKey: string, params: { paramMap?: Record<string, any>, startUserId?: string, processInstanceId?: string }): Promise<{ processInstanceId: string } | Error> => {
    const flowStore = useGlobalFlowStore();

    try {
        // 1. 获取流程ID
        const flowId = await getFlowIdFromStore(flowStore, flowIdKey);
        if (!flowId) {
            return Promise.reject(new Error('流程ID未找到'));
        }

        // 2. 获取流程详情
        const process = await getParsedProcessDetails(flowId);

        // 3. 检查是否是"发起人自选"节点
        if (process.childNode.placeHolder === '发起人自选') {
            return await handleUserSelection(process, params,flowId);
        }

        // 4. 直接启动流程
        return await startProcessDirectly(flowId, params);
    } catch (err) {
        return Promise.reject(err);
    }
};

/**
 * 从全局存储中获取流程ID
 * @param flowStore 流程存储
 * @param flowIdKey 流程ID Key
 * @returns 流程ID
 */
const getFlowIdFromStore = async (
    flowStore: ReturnType<typeof useGlobalFlowStore>,
    flowIdKey: string
): Promise<string | undefined> => {
    if (!flowStore.loaded) {
        await flowStore.loadFlowList();
    }
    return flowStore.getFlowId(flowIdKey);
};

/**
 * 获取并解析流程详情
 * @param flowId 流程ID
 * @returns 解析后的流程节点
 */
const getParsedProcessDetails = async (flowId: string): Promise<any> => {
    const getFlow = await getFlowDetail(flowId);
    return JSON.parse(getFlow.data.process);
};

/**
 * 直接启动流程（非"发起人自选"）
 * @param flowId 流程ID
 * @param params 流程参数
 * @returns 流程实例ID
 */
const startProcessDirectly = async (
    flowId: string,
    params: { paramMap?: Record<string, any>, startUserId?: string, processInstanceId?: string }
): Promise<{ processInstanceId: string }> => {
    if (!params.paramMap){
        params.paramMap = {};
    }
    const res = await startFlow({ flowId, ...params });
    if (res.data) {
        return { processInstanceId: res.data };
    } else {
        throw new Error('流程启动失败');
    }
};