<template>
  <view class="container">
    <ApprovalFlow
      :list="groupedNodes"
      :currentNode="currentNode"
      :loading="fetchFlowLoading"
    />
  </view>
</template>

<script setup lang="ts">
import { watch, computed, ref } from 'vue';
import ApprovalFlow from '@/components/ApprovalFlow.vue';
import { useFlowApi } from '@/api/flow/index';
import to from 'await-to-js';

/**
 * 接收来自父组件的流程属性配置
 */
const props = defineProps({
  id: { type: Number, default: 0 },
  businessCode: { type: String, default: '' },
  defCode: { type: String, default: '' },
  memberList: { type: Array, default: () => [] }
});

const flowApi = useFlowApi();

// 审批实例节点列表（组件内独立维护，避免多个 FlowTable 互相覆盖）
const apprList = ref<any[]>([]);
// 当前处于的节点
const currentNode = ref<string>('');
// 加载状态
const fetchFlowLoading = ref<boolean>(false);

// 将原始审批记录按节点分组
const groupedNodes = computed(() => {
  const list = apprList.value || [];
  if (!list.length) return [];
  const map: Record<string, any> = {};
  list.forEach((item: any) => {
    const key = item.nodeId || `node_${item.nodeTitle || ''}`;
    if (!map[key]) {
      map[key] = {
        nodeId: item.nodeId,
        nodeTitle: item.nodeTitle,
        nodeType: item.nodeType,
        nodeModel: item.nodeModel,
        items: [] as any[]
      };
    }
    map[key].items.push(item);
  });
  return Object.values(map);
});

const fetchFlowInstance = async () => {
  if (!props.id) return;
  fetchFlowLoading.value = true;
  apprList.value = [];
  currentNode.value = '';

  const params = { id: props.id, businessCode: props.businessCode, defCode: props.defCode };
  const [err, res] = await to(flowApi.getFlowInstance(params)) as [any, any];

  fetchFlowLoading.value = false;

  if (err) {
    console.error('获取审批流实例失败:', err);
    return;
  }

  if (res && res.code === 200) {
    const arr = res.data?.nodes || [];
    // 匹配附加数据
    apprList.value = arr.map((item: any) => {
      const obj = (props.memberList as any[]).find((i: any) => i.memberId === item.userId);
      return {
        ...item,
        templateContent: obj?.templateContent || null
      };
    });
    currentNode.value = res.data?.nodeId || '';
  }
};

/**
 * 监听属性变化并在有传入的时候触发拉取审批流信息
 */
watch(
  () => [props.id, props.businessCode, props.defCode],
  () => {
    fetchFlowInstance();
  },
  { deep: true, immediate: true }
);
</script>

<style lang="scss" scoped>
.container {
  padding: 0 10rpx;
}
</style>

