<template>
  <el-dialog
    :model-value="visible"
    title="查看子流程"
    :width="600"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    :append-to-body="true"
    @open="onOpen"
    @close="onClose"
  >
    <el-skeleton v-if="loading" :rows="5" animated />
    <trace-list v-else :process="state.trace" @on-trace-child="onTraceChild" />
    <trace-detail
      :visible="state.trace && state.trace.activities.length > 0 && state.visible"
      :assign-id="state.assignId"
      @on-close="state.visible = false"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive } from 'vue'

import { SuccessResultCode, type TraceInfo, useLoading } from '@cacp/ui'

import * as apis from '@/apis/workflow/runtime'
import TraceList from './ProcessTraceList.vue'
import TraceDetail from './ProcessTraceDetail.vue'

const { loading, setLoading } = useLoading()

const props = defineProps<{
  visible: boolean
  assignId: string
}>()
const emits = defineEmits<{
  (e: 'on-close'): void
}>()

const state = reactive<{
  trace?: TraceInfo
  visible: boolean
  assignId: string
}>({
  visible: false,
  assignId: ''
})

async function onOpen() {
  setLoading(true)

  const res = await apis.traceBranch(props.assignId)
  if (res.code === SuccessResultCode && res.data) {
    state.trace = res.data!
  }

  setLoading(false)
}

function onClose() {
  emits('on-close')
}

function onTraceChild(assignId: string) {
  state.visible = true
  state.assignId = assignId
}
</script>
