<template>
  <cacp-complex-table :actions="actions" :loading="loading" :data="tableData" stripe>
    <el-table-column prop="processCode" label="流程"></el-table-column>
    <el-table-column prop="bizTitle" label="标题"></el-table-column>
    <el-table-column prop="issueUserName" label="拟稿人"></el-table-column>
    <el-table-column prop="createTime" label="创建时间">
      <template #default="scope">
        {{ dayjs(scope.row.createTime).format('YYYY-MM-DD') }}
      </template>
    </el-table-column>
    <template #title>
      <div style="font-size: 18px;font-weight: 700; text-align: center">运行中工作流列表</div>
    </template>
  </cacp-complex-table>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

import {
  useLoading,
  useComplexTable,
  SuccessResultCode,
  type Result,
  type RuntimeProcess,
  type TableAction
} from '@cacp/ui'

import * as apis from '@/apis/workflow/runtime'
import config from '@/config'

const actions: Array<TableAction> = [
  {
    key: 'rollback',
    tooltip: '回滚',
    type: 'danger',
    limit: 'one',
    icon: 'Back',
    onclick: onRollback
  }
]

const { loading, setLoading } = useLoading()
const { tableData, setData } = useComplexTable(config)

onMounted(async () => {
  await onQuery()
})

async function onQuery(): Promise<void> {
  setLoading(true)

  const res: Result<Array<RuntimeProcess>> = await apis.getRunningProcessList()
  if (res.code === SuccessResultCode && res.data) {
    setData(res.data)
  } else {
    ElMessage.error({
      message: res.message,
      showClose: true
    })
  }

  setLoading(false)
}

async function onRollback(process: RuntimeProcess) {
  const res: Result<boolean> = await apis.rollback(process.processId)
  if (res.code === SuccessResultCode && res.data) {
    await onQuery()
  }
}
</script>

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