<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="通知渠道管理"
      search-button-text="查询"
      reset-button-text="重置"
      refresh-tooltip-text="刷新数据"
      density-tooltip-text="表格密度"
      column-setting-tooltip-text="列设置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <!-- 工具栏左侧按钮 -->
      <template #toolbar-left>
        <a-button type="primary" @click="handleCreate">
          <template #icon>
            <icon-plus />
          </template>
          新建渠道
        </a-button>
      </template>

      <!-- 表格自定义列：序号 -->
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
      </template>

      <!-- 表格自定义列：渠道类型 -->
      <template #type="{ record }">
        <a-tag :color="getChannelTypeColor(record.type)">
          {{ getChannelTypeName(record.type) }}
        </a-tag>
      </template>

      <!-- 表格自定义列：操作 -->
      <template #actions="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="handleDetail(record)">
            详情
          </a-button>
          <a-button type="text" size="small" @click="handleEdit(record)">
            编辑
          </a-button>
          <a-popconfirm
            content="确认删除该通知渠道吗？"
            @ok="handleDelete(record)"
          >
            <a-button type="text" size="small" status="danger">
              删除
            </a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </search-table>

    <!-- 表单对话框 -->
    <channel-form-dialog
      v-model:visible="formDialogVisible"
      :channel="currentChannel"
      @success="fetchList"
    />

    <!-- 详情对话框 -->
    <channel-detail-dialog
      v-model:visible="detailDialogVisible"
      :channel-id="currentChannelId"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import SearchTable from '@/components/search-table/index.vue'
import ChannelFormDialog from './components/ChannelFormDialog.vue'
import ChannelDetailDialog from './components/ChannelDetailDialog.vue'
import type { FormItem } from '@/components/search-form/types'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import { fetchNoticeChannelList, deleteNoticeChannel } from '@/api/ops/noticeChannel'

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

const formModel = ref<Record<string, any>>({
  keyword: '',
  type: '',
})

const handleFormModelUpdate = (value: Record<string, any>) => {
  formModel.value = value
}

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '渠道名称',
    type: 'input',
    placeholder: '请输入渠道名称',
  },
  {
    field: 'type',
    label: '渠道类型',
    type: 'select',
    placeholder: '请选择渠道类型',
    options: [
      { label: '邮件', value: 'email' },
      { label: '短信', value: 'sms' },
      { label: 'Webhook', value: 'webhook' },
      { label: '钉钉', value: 'dingtalk' },
      { label: '企业微信', value: 'wechat' },
      { label: '飞书', value: 'feishu' },
      { label: 'Slack', value: 'slack' },
    ],
  },
])

// 表格列配置
const columns = computed<TableColumnData[]>(() => [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 80,
  },
  {
    title: '渠道名称',
    dataIndex: 'name',
    width: 150,
  },
  {
    title: '渠道类型',
    dataIndex: 'type',
    slotName: 'type',
    width: 120,
  },
  {
    title: '限流次数',
    dataIndex: 'rate_limit',
    width: 100,
  },
  {
    title: '限流窗口',
    dataIndex: 'rate_limit_window',
    width: 100,
  },
  {
    title: '操作',
    dataIndex: 'actions',
    slotName: 'actions',
    width: 200,
    fixed: 'right',
  },
])

// 表单对话框
const formDialogVisible = ref(false)
const currentChannel = ref<any>(null)

// 详情对话框
const detailDialogVisible = ref(false)
const currentChannelId = ref<number | null>(null)

// 渠道类型映射
const channelTypeMap: Record<string, { name: string; color: string }> = {
  email: { name: '邮件', color: 'blue' },
  sms: { name: '短信', color: 'cyan' },
  webhook: { name: 'Webhook', color: 'purple' },
  dingtalk: { name: '钉钉', color: 'red' },
  wechat: { name: '企业微信', color: 'green' },
  feishu: { name: '飞书', color: 'orange' },
  slack: { name: 'Slack', color: 'arcoblue' },
}

// 获取渠道类型名称
const getChannelTypeName = (type?: string) => {
  return channelTypeMap[type || '']?.name || type || '-'
}

// 获取渠道类型颜色
const getChannelTypeColor = (type?: string) => {
  return channelTypeMap[type || '']?.color || 'gray'
}

// 获取列表
const fetchList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      ...formModel.value,
    }

    const res = await fetchNoticeChannelList(params)
    if (res.code === 0) {
      tableData.value = res.details?.data || []
      pagination.total = res.details?.total || 0
    } else {
      Message.error(res.message || '获取列表失败')
    }
  } catch (error) {
    Message.error('获取列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchList()
}

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    type: '',
  }
  pagination.current = 1
  fetchList()
}

// 分页变化
const handlePageChange = (current: number) => {
  pagination.current = current
  fetchList()
}

const handleRefresh = () => {
  fetchList()
  Message.success('数据已刷新')
}

// 新建
const handleCreate = () => {
  currentChannel.value = null
  formDialogVisible.value = true
}

// 编辑
const handleEdit = (record: any) => {
  currentChannel.value = { ...record }
  formDialogVisible.value = true
}

// 详情
const handleDetail = (record: any) => {
  currentChannelId.value = record.id
  detailDialogVisible.value = true
}

// 删除
const handleDelete = async (record: any) => {
  try {
    const res = await deleteNoticeChannel(record.id)
    if (res.code === 0) {
      Message.success('删除成功')
      fetchList()
    } else {
      Message.error(res.message || '删除失败')
    }
  } catch (error) {
    Message.error('删除失败')
    console.error(error)
  }
}

// 初始化加载
onMounted(() => {
  fetchList()
})
</script>

<script lang="ts">
export default {
  name: 'NoticeChannel',
}
</script>

<style scoped lang="less">
.container {
  margin-top: 20px;
}
</style>
