<!--
  Description: 订阅管理
  Author: 李亚光
  Date: 2025-05-27
 -->
<script name="subscriptionManagement" lang="ts" setup>
import { getDictByCode } from '@/api/system/dict'
import { deleteSubscribe, getSubscribeListPage } from '@/api/basic/subscribe'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import addSubscribeDialog from './addSubscribeDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  groupId: {
    type: String,
    required: true,
  },
})
// 查询条件
const searchQuery = ref({
  offset: 1,
  limit: 10,
  groupId: '',
  subscribeType: '', // 订阅方式
})
// 订阅方式列表
const subscribeLoading = ref(false)
const subscribeTypeList = ref<{ id: string, name: string, value: string }[]>([])
// 获取字典
const fetchDict = () => {
  subscribeLoading.value = true
  getDictByCode('messageType').then(res => {
    subscribeTypeList.value = res.data
    subscribeLoading.value = false
  }).catch(() => {
    subscribeLoading.value = false
  })
}
fetchDict()
// 表格表头数据
const columns = ref<TableColumn[]>([
  { text: '消息类别', value: 'messageTypeName', align: 'center' },
  { text: '订阅方式', value: 'subscribeTypeName', align: 'center' },
  { text: '订阅方URL', value: 'subscribeContentJson', align: 'center' },
  { text: '订阅开关', value: 'enable', align: 'center' },
  { text: '订阅状态', value: 'subscribeStatus', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center' },
  { text: '创建人', value: 'createUserName', align: 'center' },
])
const dataList = ref([]) // 订阅数据列表
const total = ref(0)
const loadingTable = ref(true)
// 获取列表数据
const fetchData = () => {
  loadingTable.value = true
  getSubscribeListPage({ ...searchQuery.value, groupId: props.groupId, }).then(res => {
    console.log(res.data, '订阅管理列表')
    total.value = res.data.total
    dataList.value = res.data.rows
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}
fetchData()
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  fetchData()
}
const addRef = ref()
// 新建
const addSubscribe = () => {
  addRef.value.initDialog('create', {})
}
// 编辑
const updateRow = (row: any) => {
  addRef.value.initDialog('update', JSON.parse(JSON.stringify(row)))
}
// 详情
const detailRow = (row: any) => {
  if (row.subscribeContentJson) {
    ElMessageBox.alert(row.subscribeContentJson, '详情', {
      confirmButtonText: '确定',
      customClass: 'log-info',
    })
  }
}
// 删除
const deleteRow = (id: string) => {
  ElMessageBox.confirm(
    `确定要删除该数据吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteSubscribe([id]).then(res => {
      ElMessage.success('删除成功')
      fetchData()
    })
  })
}
const recordSelected = ref([])
const recordMultiSelect = (e: any) => {
  recordSelected.value = e
}
// 批量删除
const batchDeleteRow = () => {
  if (!recordSelected.value.length) {
    ElMessage.warning('请先选择需要删除的数据')
    return
  }
  ElMessageBox.confirm(
    `确定要删除选中的这些数据吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteSubscribe(recordSelected.value.map((item: { id: string }) => item.id)).then(res => {
      ElMessage.success('删除成功')
      fetchData()
      recordSelected.value = []
    })
  })
}
</script>

<template>
  <app-container>
    <!-- 新增/编辑弹窗 -->
    <addSubscribeDialog ref="addRef" @closeRefresh="fetchData" />
    <!-- 筛选条件 -->
    <search-area :need-clear="false" @search="fetchData">
      <search-item>
        <el-select v-model="searchQuery.subscribeType" placeholder="设备类型" clearable style="width: 192px;" :loading="subscribeLoading">
          <el-option v-for="dict in subscribeTypeList" :key="dict.id" :label="dict.name" :value="dict.value" />
        </el-select>
      </search-item>
    </search-area>
    <!-- 表格数据展示 -->
    <table-container title="订阅列表">
      <!-- 表头区域 -->
      <template #btns-right>
        <el-button type="primary" @click="addSubscribe">
          新增
        </el-button>
        <el-button type="danger" @click="batchDeleteRow">
          批量删除
        </el-button>
      </template>
      <!-- 表格区域 -->
      <normal-table :data="dataList" :columns="columns" :total="total"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }" :list-loading="loadingTable"
        @change="changePage" :is-showmulti-select="true" :is-multi="true" @multi-select="recordMultiSelect">
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (searchQuery.offset! - 1) * searchQuery.limit! + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column fixed="right" label="操作" align="center" width="130">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="detailRow(row)">
                查看
              </el-button>
              <el-button size="small" type="primary" link @click="updateRow(row)">
                编辑
              </el-button>
              <el-button size="small" type="danger" link @click="deleteRow(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>
