<template>
  <div class="pt-3 white">
    <!-- 筛选栏 -->
    <filter-list :option="filterOption" @search="handleSearch" />

    <!-- 工作流表格 -->
    <table-list
      :loading="loading"
      :headers="headers"
      :items="workflows"
      :total="total"
      :disable-sort="true"
      :page-info="pageInfo"
      :is-tools="false"
      :show-select="false"
      @pageHandleChange="pageHandleChange"
    >
      <template #active="{ item }">
        <v-chip
          :color="item.active ? 'success' : 'error'"
          small
          dark
        >
          {{ item.active ? '激活' : '停用' }}
        </v-chip>
      </template>
      <template #name="{ item }">
        <span class="defaultLink" @click="handleToN8N(item.id)">{{ item.name }}</span>
      </template>
      <template #tags="{ item }">
        <v-chip v-for="tag in item.tags" :key="tag" small class="mr-1">{{ tag }}</v-chip>
      </template>
      <template #actions="{ item }">
        <v-btn text color="primary" @click="handleDetail(item.id)">详情</v-btn>
        <!-- <v-btn text color="primary" @click="handleExecution(item.id)">执行</v-btn> -->
        <v-btn text v-if="!item.active" color="success" @click="handleStatus(item.id, true)">激活</v-btn>
        <v-btn text v-else color="error" @click="handleStatus(item.id, false)">停用</v-btn>
      </template>
    </table-list>

    <!-- 详情弹窗 -->
    <dialog-page :visible.sync="show" title="工作流详情" :width-type="1" :footer="false">
      <workflow-detail v-if="show" :workflowId="workflowId"/>
    </dialog-page>
  </div>
</template>

<script>
import { getWorkflows, activateWorkflow, deactivateWorkflow } from '@/api/dataFactory'
import TableList from '@/components/List/table'
import FilterList from '@/components/Filter'
import DialogPage from '@/components/Dialog'
import WorkflowDetail from './WorkflowDetail'

export default {
  name: 'WorkflowList',
  components: {
    TableList,
    FilterList,
    DialogPage,
    WorkflowDetail
  },
  data () {
    return {
      loading: false,
      workflows: [],
      filterOption: {
        list: [
          {
            type: 'textField',
            value: null,
            label: '工作流名称',
            key: 'search'
          },
          {
            type: 'autocomplete',
            value: 'true',
            label: '状态',
            key: 'active',
            items: [
              { label: '全部', value: null },
              { label: '激活', value: 'true' },
              { label: '停用', value: 'false' }
            ]
          }
        ]
      },
      headers: [
        { text: 'ID', value: 'id' },
        { text: '工作流名称', value: 'name' },
        { text: '状态', value: 'active' },
        { text: '标签', value: 'tags', sortable: false },
        { text: '创建时间', value: 'created_at' },
        { text: '更新时间', value: 'updated_at' },
        { text: '操作', value: 'actions', sortable: false }
      ],
      pageInfo: {
        size: 10,
        current: 1
      },
      total: 0,
      show: false,
      workflowId: null
    }
  },
  mounted () {
    this.fetchWorkflows()
  },
  methods: {
    // 搜索
    handleSearch (filterData) {
      this.pageInfo.current = 1
      this.fetchWorkflows(filterData)
    },
    // 获取工作流列表
    async fetchWorkflows (filterData = { active: true }) {
      this.loading = true
      try {
        const params = {
          page: this.pageInfo.current,
          page_size: this.pageInfo.size,
          active: filterData.active
          // filter: {
          //   isArchived: false,
          //   parentFolderId: 0
          // },
          // sortBy: 'updatedAt:desc'
        }
        if (filterData.search) params.search = filterData.search
        if (!filterData.active) delete params.active

        const { data } = await getWorkflows(params)
        this.workflows = data.items || []
        this.total = data.total || 0
      } catch (error) {
        this.$snackbar.error('获取工作流列表失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    pageHandleChange (pageInfo) {
      this.pageInfo = pageInfo
      this.fetchWorkflows()
    },
    // 详情
    async handleDetail (id) {
      this.workflowId = id
      this.show = true
    },
    // 跳转至n8n
    handleToN8N (id) {
      window.open(`${process.env.VUE_APP_N8N_URL}/workflow/${id}`, '_blank')
    },
    // 激活、停用
    async handleStatus (id, active) {
      if (!id) return
      const api = active ? activateWorkflow : deactivateWorkflow
      try {
        await api(id)
        this.$snackbar.success(active ? '工作流已激活' : '工作流已停用')
        this.fetchWorkflows()
      } catch (error) {
        this.$snackbar.error('操作失败')
      }
    },
    // 执行工作流
    async handleExecution (id) {
      // if (!id) return
      // try {
      //   await triggerWorkflow(id, {})
      //   this.$snackbar.success('工作流执行成功')
      // } catch (error) {
      //   this.$snackbar.error('执行失败')
      // }
    }
  }
}
</script>
