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

const message = useMessage()
const columns = shallowRef([
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '订单ID',
    dataIndex: 'hostId',
    key: 'hostId',
    width: 100,
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
    ellipsis: true,
  },
  {
    title: 'IP',
    dataIndex: 'ip',
    key: 'ip',
    width: 150,
  },
  {
    title: '备注',
    dataIndex: 'comment',
    key: 'comment',
    width: 200,
    ellipsis: true,
  },
  {
    title: '运营商',
    dataIndex: 'operator',
    key: 'operator',
    width: 100,
  },
  {
    title: '区域',
    dataIndex: 'nodeArea',
    key: 'nodeArea',
    width: 100,
  },
  {
    title: '是否封禁UDP',
    dataIndex: 'banUdp',
    key: 'banUdp',
    width: 120,
  },
  {
    title: '是否封海外',
    dataIndex: 'banOverseas',
    key: 'banOverseas',
    width: 120,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 180,
    sorter: true,
    customRender: ({ text }) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '',
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    width: 180,
    customRender: ({ text }) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 240,
    fixed: 'right',
  },
])
const { state, initQuery, resetQuery, query } = useTableQuery({
  queryApi: getListApi,
  queryParams: {
    name: '',
    ip: '',
    hostId: null,
    nodeArea: '',
    comment: '',
    column: '',
    order: '',
  },
  afterQuery: (res) => {
    if (!res || !Array.isArray(res.records)) {
      return { list: [], total: 0 }
    }
    return res
  },
})
const crudTableModal = ref()
function handleTableChange(pagination, filters, sorter) {
  if (sorter.field === 'createdAt' && sorter.order) {
    state.queryParams.column = 'createTime'
    state.queryParams.order = sorter.order === 'ascend' ? 'asc' : 'desc'
  } else {
    state.queryParams.column = ''
    state.queryParams.order = ''
  }
  query()
}

const selectedRowKeys = ref([])

const rowSelection = computed(() => {
  return {
    selectedRowKeys: selectedRowKeys.value,
    onChange: (keys) => {
      selectedRowKeys.value = keys
    },
  }
})

async function handleBatchDelete() {
  Modal.confirm({
    title: '确定删除选中的数据吗?',
    content: `即将删除 ${selectedRowKeys.value.length} 条数据。`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        const res = await deleteApiList({ ids: selectedRowKeys.value })
        if (res.code === 0) {
          await query()
          selectedRowKeys.value = []
          message.success('删除成功')
        }
      } catch (e) {
        console.log(e)
      }
    },
  })
}

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()
}
function handleEdit(record) {
  crudTableModal.value?.open(record)
}

const ipListModal = ref()
function handleViewIpList(record) {
  ipListModal.value?.open(record)
}
</script>

<template>
  <page-container>
    <a-card class="mb-4">
      <a-form class="system-crud-wrapper" :label-col="{ span: 7 }" :model="state.queryParams">
        <a-row :gutter="[15, 15]">
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <a-form-item label="名称">
              <a-input v-model:value="state.queryParams.name" placeholder="请输入名称" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <a-form-item label="IP">
              <a-input v-model:value="state.queryParams.ip" placeholder="请输入IP" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <a-form-item label="订单ID">
              <a-input-number v-model:value="state.queryParams.hostId" placeholder="请输入订单ID" class="w-full" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <a-form-item label="区域">
              <a-select v-model:value="state.queryParams.nodeArea" placeholder="请选择区域">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="宁波">宁波</a-select-option>
                <a-select-option value="香港">香港</a-select-option>
                <a-select-option value="test">test</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <a-form-item label="备注">
              <a-input v-model:value="state.queryParams.comment" placeholder="请输入备注" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <a-space flex justify-end w-full size="middle">
              <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="网关组列表">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            新增
          </a-button>
          <a-button type="primary" danger :disabled="!selectedRowKeys || selectedRowKeys.length === 0" @click="handleBatchDelete">
            批量删除
          </a-button>
        </a-space>
      </template>
      <a-table
        row-key="id"
        :row-selection="rowSelection"
        :loading="state.loading"
        :columns="columns"
        :data-source="state.dataSource"
        :pagination="state.pagination"
        bordered
        striped
        :scroll="{ x: 1820 }"
        @change="handleTableChange"
      >
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
            <div class="flex items-center justify-start gap-x-1">
              <a-button type="link" class="!pl-0" @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>
              <a-button type="link" @click="handleViewIpList(scope?.record)">
                查看IP列表
              </a-button>
            </div>
          </template>

          <template v-else-if="scope?.column?.dataIndex === 'operator'">
            <a-tag v-if="scope?.text === 1" color="blue">
              电信
            </a-tag>
            <a-tag v-else-if="scope?.text === 2" color="purple">
              BGP
            </a-tag>
            <a-tag v-else>
              未知
            </a-tag>
          </template>

          <template v-else-if="scope?.column?.dataIndex === 'banUdp'">
            <a-tag v-if="scope?.text === 1" color="red">
              是
            </a-tag>
            <a-tag v-else-if="scope?.text === 0" color="green">
              否
            </a-tag>
            <a-tag v-else>
              未知
            </a-tag>
          </template>

          <template v-else-if="scope?.column?.dataIndex === 'banOverseas'">
            <a-tag v-if="scope?.text === 1" color="red">
              是
            </a-tag>
            <a-tag v-else-if="scope?.text === 0" color="green">
              否
            </a-tag>
            <a-tag v-else>
              未知
            </a-tag>
          </template>
        </template>
      </a-table>
    </a-card>

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

<style lang="less" scoped>
.system-crud-wrapper {
  .ant-form-item {
    margin: 0;
  }
}

:deep(.ant-table-tbody > tr > td) {
  font-size: 16px;
}
</style>
