<template>
  <cacp-search-layout>
    <template #search>
      <cacp-search-panel-layout label-position="left" :gutter="30" :colSpan="8">
        <el-form-item label="应用程序">
          <el-input v-model="appCode"></el-input>
        </el-form-item>
        <template #buttonGroup>
          <el-button type="primary" @click="onQuery">查询</el-button>
          <!-- <el-button type="info" @click="onReset">重置</el-button> -->
        </template>
      </cacp-search-panel-layout>
    </template>
    <cacp-complex-table :actions="actions" :data="tableData" v-loading="loading">
      <template #title>
        <div class="cacp-group__title">业务计数器</div>
      </template>
      <el-table-column prop="appCode" label="应用程序"></el-table-column>
      <el-table-column prop="counterPrefix" label="计数器前缀"></el-table-column>
      <el-table-column prop="counterValue" label="数值"></el-table-column>
    </cacp-complex-table>
  </cacp-search-layout>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { SuccessResultCode, useComplexTable, useLoading, type Result, type TableAction } from '@cacp/ui'
import type { CacpCounter } from '@/types/counter'
import config from '@/config'
import * as apis from '@/apis/counter'

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

const actions: Array<TableAction> = [
  {
    key: 'delete',
    text: '删除',
    limit: 'one',
    confirm: '确实要删除？',
    onclick: onDelete
  }
]

const appCode = ref<string>('')

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

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

  setLoading(false)
}

async function onDelete(info: CacpCounter) {
  const res = await apis.del(info.appCode, info.counterPerfix)
  if (res.code === SuccessResultCode) {
    ElMessage.success('删除成功')
    await onQuery()
  }
}
</script>
