<script setup lang="ts">
import Node from "./Node.vue";
import type { NotifyNode } from "./type";
import type { Ref } from "vue";
import type { ErrorInfo } from "./type";
import { getById } from "@/api/modules/role";
import { getByUsername } from "@/api/modules/user";

const props = defineProps<{
    node: NotifyNode & { formOrg?: string };
}>();
const { fields, nodesError } = inject<{
    fields: Ref<any[]>;
    nodesError: Ref<Recordable<ErrorInfo[] | undefined>>;
}>("flowDesign", { fields: ref([]), nodesError: ref({}) });

const content = ref<string>("");

watchEffect(() => {
    const errors: ErrorInfo[] = [];
    const { id, assigneeType, name, users, roles, leader, choice, formUser, formOrg, orgLeader } = props.node;

    if (assigneeType === "user") {
        if (users.length > 0) {
            Promise.all(users.map(user => getByUsername(user))).then(res => {
                content.value = res.map(r => r.data.name).join("、");
            });
        } else {
            errors.push({ id, name, message: "未指定人员" });
            content.value = "未指定人员";
        }
    } else if (assigneeType === "role") {
        if (roles.length > 0) {
            Promise.all(roles.map(id => getById(id))).then(res => {
                content.value = res.map(r => r.data.name).join("、");
            });
        } else {
            errors.push({ id, name, message: "未指定角色" });
            content.value = "未指定角色";
        }
    } else if (assigneeType === "choice") {
        content.value = `发起人自选（${choice ? "多选" : "单选"}）`;
    } else if (assigneeType === "self") {
        content.value = "发起人自己";
    } else if (assigneeType === "leader") {
        content.value = leader === 1 ? "直属上级" : `${leader}级上级`;
    } else if (assigneeType === "orgLeader") {
        content.value = orgLeader === 1 ? "直属主管" : `${orgLeader}级主管`;
    } else if (assigneeType === "formUser") {
        if (!formUser) {
            errors.push({ id, name, message: "未指定表单内人员" });
        }
        const title = fields.value.find(e => e.id === formUser)?.label || formUser || "?";
        content.value = `表单内（${title}）人员`;
    }
    // 新增：表单内组织处理逻辑
    else if (assigneeType === "formOrg") {
        if (!formOrg) {
            errors.push({ id, name, message: "未指定表单内组织" });
        }
        const title = fields.value.find(e => e.id === formOrg)?.label || formOrg || "?";
        content.value = `表单内（${title}）组织`;
    }
    // 原有逻辑保持不变
    else {
        errors.push({ id, name, message: "未知通知类型" });
        content.value = "未知类型";
    }

    nodesError.value[id] = errors.length > 0 ? errors : undefined;
});
</script>

<template>
    <Node v-bind="$attrs" icon="el:Bell" color="#faad14" :node="node">
        <el-text>{{ content }}</el-text>
    </Node>
</template>

<style scoped lang="scss"></style>
