<script setup lang="ts">
import { Alert, Segmented } from 'ant-design-vue'
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import { PlusOutlined, SyncOutlined } from '@ant-design/icons-vue'
import TopicFormModal from './TopicFormModal.vue'
import type { Topic } from '@/api/product/types'
import { TopicType } from '@/api/product/types'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import { deleteTopic, getTopicList } from '@/api/product/topic'
import { useSystemEnumStore } from '@/store/modules/systemEnum'
import { useModal } from '@/components/Modal'
import { useMessage } from '@/hooks/web/useMessage'
import { usePermission } from '@/hooks/web/usePermission'

const route = useRoute()
const { getSystemEnumLabel } = useSystemEnumStore()

const [registerModal, { openModal }] = useModal<Topic>()

const topicType = ref<TopicType>(TopicType.System)
const isCustomTopic = computed(() => topicType.value === TopicType.Custom)
const alertMessage = computed(
  () => isCustomTopic.value
    ? 'Topic用以将设备数据分类上报，进而分别进行处理。除了系统预置的Topic，您也可以自定义Topic，然后在设备侧开发时选择数据上报的Topic。'
    : '以下是系统Topic，设备侧通过系统预设的topic接收数据时，无需提前订阅。',
)

const { hasPermission } = usePermission()

const [register, { reload, setTableData }] = useTable({
  api(params) {
    return getTopicList({
      ...params,
      productId: route.params.id,
      topicCategory: topicType.value,
    })
  },
  columns: [
    {
      title: 'Topic',
      dataIndex: 'topic',
    },
    {
      title: '操作权限',
      dataIndex: 'topicType',
      customRender: ({ value }) => getSystemEnumLabel('eProductTopicType', value),
    },
    {
      title: '开启解析脚本',
      dataIndex: 'enableScript',
      ifShow: () => isCustomTopic.value,
    },
    {
      title: '描述',
      dataIndex: 'topicDesc',
    },
  ],
  bordered: true,
  inset: true,
  canResize: false,
  actionColumn: {
    width: 150,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    ifShow: () => isCustomTopic.value,
    auth: ['product_topic_edit', 'product_topic_delete'],
  },
})

function onChangeTopicType() {
  setTableData([])
  reload()
}

async function handleDelete(id: string) {
  try {
    await deleteTopic(id)
    useMessage().createMessage.success('删除成功')
    reload()
  }
  catch {}
}
</script>

<template>
  <div>
    <div flex="~ items-center justify-between gap-12px" mb="12px">
      <div flex="~ wrap gap-12px">
        <Segmented
          v-model:value="topicType"
          :options="[{ label: '系统 Topic', value: TopicType.System }, { label: '自定义 Topic', value: TopicType.Custom }]"
          @change="onChangeTopicType"
        />

        <a-button v-if="isCustomTopic && hasPermission('product_topic_add')" type="primary" @click="openModal">
          <PlusOutlined />
          新增 Topic
        </a-button>

        <Alert :message="alertMessage" type="info" show-icon class="py-4px" />
      </div>

      <div class="mr-10px flex cursor-pointer items-center">
        <a-button size="small" @click="reload">
          <template #icon>
            <SyncOutlined />
          </template>
          刷新
        </a-button>
      </div>
    </div>

    <BasicTable :api="async () => ([] as Topic[])" @register="register">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'i-ant-design:edit-outlined',
                label: '编辑',
                auth: 'product_topic_edit',
                onClick: () => openModal(true, record),
              },
              {
                icon: 'i-ant-design:delete-outlined',
                danger: true,
                label: '删除',
                auth: 'product_topic_delete',
                popConfirm: {
                  title: '是否要删除数据？',
                  placement: 'left',
                  confirm: () => handleDelete(record.id),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>

    <TopicFormModal @register="registerModal" @success="reload" />
  </div>
</template>
