<script setup>
import { ref, shallowRef, computed } from 'vue'
import { useRoute } from 'vue-router'
import { PlusOutlined } from '@ant-design/icons-vue'
import CrudTableModal from './components/ip-list-modal.vue'
import { getListApi, deleteApi } from '~@/api/list/gateway-group-ip-list.js'
import { useTableQuery } from '~@/composables/table-query'

const route = useRoute()
const message = useMessage()
const gatewayGroupId = computed(() => Number(route.query.id || 0))

const columns = shallowRef([
  { title: 'ID', dataIndex: 'id', key: 'id' },
  { title: '网关组ID', dataIndex: 'gatewayGroupId', key: 'gatewayGroupId' },
  { title: 'IP地址', dataIndex: 'ip', key: 'ip' },
  { title: '标签', dataIndex: 'tag', key: 'tag' },
  { title: '归属地', dataIndex: 'originPlace', key: 'originPlace' },
  { title: '备注', dataIndex: 'comment', key: 'comment' },
  { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt' },
  { title: '更新时间', dataIndex: 'updatedAt', key: 'updatedAt' },
  { title: '操作', dataIndex: 'action', key: 'action' },
])

const { state, initQuery, resetQuery, query } = useTableQuery({
  queryApi: getListApi,
  queryParams: {
    gatewayGroupId: gatewayGroupId.value,
    ip: undefined,
  },
  afterQuery: (res) => {
    console.log('afterQuery', res)
    if (!res || !Array.isArray(res.records)) {
      // 如果数据格式不正确，返回一个空状态，防止程序崩溃
      return { list: [], total: 0 }
    }
    return res
  },
})

const crudTableModal = ref()

async function handleDelete(record) {
  if (!record.id) return message.error('id 不能为空')
  try {
    const res = await deleteApi(record.id)
    if (res.code === 0) {
      await query()
      message.success('删除成功')
    }
  } catch (e) {
    console.log(e)
  }
}

function handleAdd() {
  crudTableModal.value?.open({ gatewayGroupId: gatewayGroupId.value })
}

function handleEdit(record) {
  crudTableModal.value?.open(record)
}
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form class="system-crud-wrapper" :label-col="{ span: 7 }" :model="state.queryParams">
        <a-row :gutter="[15, 0]">
          <a-col :span="6">
            <a-form-item name="ip" label="IP地址">
              <a-input v-model:value="state.queryParams.ip" placeholder="请输入IP地址" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-space flex justify-end w-full>
              <a-button :loading="state.loading" type="primary" @click="initQuery">
                查询
              </a-button>
              <a-button :loading="state.loading" @click="resetQuery">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card title="IP列表">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            新增
          </a-button>
        </a-space>
      </template>
      <a-table
        row-key="id"
        :loading="state.loading"
        :columns="columns"
        :data-source="state.dataSource"
        :pagination="state.pagination"
      >
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
            <div flex gap-2>
              <a-button type="link" @click="handleEdit(scope?.record)">
                编辑
              </a-button>
              <a-popconfirm
                title="确定删除该条数据？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(scope?.record)"
              >
                <a-button type="link">
                  删除
                </a-button>
              </a-popconfirm>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>

    <CrudTableModal ref="crudTableModal" @ok="query" />
  </page-container>
</template>