<template>
  <CommonPage show-footer title="代理管理">
    <template #action>
      <n-space>
        <n-button v-if="activeTab === 'config'" type="primary" @click="handleAdd">
          新增代理
        </n-button>
        <n-button v-else type="primary" @click="handleAddProvider">新增解析规则</n-button>
      </n-space>
    </template>

    <n-tabs v-model:value="activeTab" type="line">
      <n-tab-pane name="config" tab="代理配置">
        <CrudTable
          ref="tableRef"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="handleGetList"
        >
          <template #queryBar>
            <QueryBarItem label="名称" :label-width="40">
              <n-input
                v-model:value="queryItems.name"
                placeholder="名称"
                clearable
                @keyup.enter="tableRef?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="平台" :label-width="40">
              <n-select
                v-model:value="queryItems.platform"
                :options="platformOptions"
                placeholder="平台"
                clearable
                style="width: 180px"
              />
            </QueryBarItem>
            <QueryBarItem label="类型" :label-width="40">
              <n-select
                v-model:value="queryItems.proxy_type"
                :options="typeOptions"
                placeholder="代理类型"
                clearable
                style="width: 180px"
              />
            </QueryBarItem>
          </template>
        </CrudTable>
      </n-tab-pane>

      <n-tab-pane name="provider" tab="解析规则">
        <CrudTable
          ref="providerTableRef"
          v-model:query-items="providerQueryItems"
          :columns="providerColumns"
          :get-data="handleGetProviderList"
        >
          <template #queryBar>
            <QueryBarItem label="名称" :label-width="40">
              <n-input
                v-model:value="providerQueryItems.name"
                placeholder="名称"
                clearable
                @keyup.enter="providerTableRef?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="平台" :label-width="40">
              <n-select
                v-model:value="providerQueryItems.platform"
                :options="platformOptions"
                placeholder="平台"
                clearable
                style="width: 180px"
              />
            </QueryBarItem>
            <QueryBarItem label="模式" :label-width="40">
              <n-select
                v-model:value="providerQueryItems.mode"
                :options="modeOptions"
                placeholder="解析模式"
                clearable
                style="width: 180px"
              />
            </QueryBarItem>
          </template>
        </CrudTable>
      </n-tab-pane>
    </n-tabs>

    <CrudModal
      :title="modalTitle"
      :visible="modalVisible"
      :loading="modalLoading"
      @save="() => handleSave(tableRef?.handleSearch)"
    >
      <n-form ref="modalFormRef" :model="modalForm" label-placement="left" label-width="90">
        <n-form-item label="名称" path="name" :rule="{ required: true, message: '请输入名称' }">
          <n-input v-model:value="modalForm.name" />
        </n-form-item>
        <n-form-item label="平台" path="platform" :rule="{ required: true, message: '请选择平台' }">
          <n-select v-model:value="modalForm.platform" :options="platformOptions" />
        </n-form-item>
        <n-form-item
          label="代理类型"
          path="proxy_type"
          :rule="{ required: true, message: '请选择代理类型' }"
        >
          <n-select v-model:value="modalForm.proxy_type" :options="typeOptions" />
        </n-form-item>
        <n-form-item
          label="代理地址"
          path="proxy_url"
          :rule="{ required: true, message: '请输入代理地址' }"
        >
          <n-input
            v-model:value="modalForm.proxy_url"
            placeholder="例如 http://user:pass@ip:port 或 socks5://user:pass@ip:port"
          />
        </n-form-item>
        <n-form-item label="是否启用" path="is_active">
          <n-switch v-model:value="modalForm.is_active" />
        </n-form-item>
      </n-form>
    </CrudModal>

    <CrudModal
      :title="providerModalTitle"
      :visible="providerModalVisible"
      :loading="providerModalLoading"
      @save="() => handleSaveProvider(providerTableRef?.handleSearch)"
    >
      <n-form
        ref="providerModalFormRef"
        :model="providerModalForm"
        label-placement="left"
        label-width="90"
      >
        <n-form-item label="名称" path="name" :rule="{ required: true, message: '请输入名称' }">
          <n-input v-model:value="providerModalForm.name" />
        </n-form-item>
        <n-form-item label="平台" path="platform" :rule="{ required: true, message: '请选择平台' }">
          <n-select v-model:value="providerModalForm.platform" :options="platformOptions" />
        </n-form-item>
        <n-form-item
          label="解析模式"
          path="mode"
          :rule="{ required: true, message: '请选择解析模式' }"
        >
          <n-select v-model:value="providerModalForm.mode" :options="modeOptions" />
        </n-form-item>
        <n-form-item v-if="providerModalForm.mode === 'json'" label="列表路径" path="list_path">
          <n-input
            v-model:value="providerModalForm.list_path"
            placeholder="例如 data.list 或 result.items"
          />
        </n-form-item>
        <n-form-item v-if="providerModalForm.mode === 'json'" label="IP路径" path="ip_path">
          <n-input v-model:value="providerModalForm.ip_path" placeholder="例如 ip 或 proxy.ip" />
        </n-form-item>
        <n-form-item v-if="providerModalForm.mode === 'json'" label="端口路径" path="port_path">
          <n-input
            v-model:value="providerModalForm.port_path"
            placeholder="例如 port 或 proxy.port"
          />
        </n-form-item>
        <n-form-item
          v-if="providerModalForm.mode === 'json'"
          label="用户名路径"
          path="username_path"
        >
          <n-input
            v-model:value="providerModalForm.username_path"
            placeholder="例如 auth.username，可选"
          />
        </n-form-item>
        <n-form-item v-if="providerModalForm.mode === 'json'" label="密码路径" path="password_path">
          <n-input
            v-model:value="providerModalForm.password_path"
            placeholder="例如 auth.password，可选"
          />
        </n-form-item>
        <n-form-item
          v-if="providerModalForm.mode === 'text'"
          label="文本正则"
          path="pattern"
          :rule="{ required: true, message: '请输入正则规则' }"
        >
          <n-input
            v-model:value="providerModalForm.pattern"
            type="textarea"
            :rows="3"
            placeholder="例如 ^(?P&lt;ip&gt;\\d+\\.\\d+\\.\\d+\\.\\d+):(?P&lt;port&gt;\\d+)$"
          />
        </n-form-item>
        <n-form-item label="模板" path="template" :rule="{ required: true, message: '请输入模板' }">
          <n-input
            v-model:value="providerModalForm.template"
            placeholder="例如 {ip}:{port} 或 http://{ip}:{port}"
          />
        </n-form-item>
      </n-form>
    </CrudModal>
  </CommonPage>
</template>

<script setup>
import { h, onMounted, ref } from 'vue'
import { NButton } from 'naive-ui'
import CommonPage from '@/components/page/CommonPage.vue'
import proxyApi from '@/api/proxy'
import useCRUD from '@/composables/useCRUD'

const activeTab = ref('config')

const queryItems = ref({ name: null, platform: null, proxy_type: null })
const tableRef = ref(null)

const providerQueryItems = ref({ name: null, platform: null, mode: null })
const providerTableRef = ref(null)

const platformOptions = [
  { label: '通用', value: 'all' },
  { label: 'Boss直聘', value: 'boss' },
  { label: '前程无忧', value: 'qcwy' },
  { label: '智联招聘', value: 'zhilian' },
]

const typeOptions = [
  { label: 'HTTP 代理', value: 'http' },
  { label: 'SOCKS 代理', value: 'socks' },
  { label: '隧道代理', value: 'tunnel' },
]

const modeOptions = [
  { label: 'JSON', value: 'json' },
  { label: '文本', value: 'text' },
]

const columns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '名称', key: 'name', minWidth: 140 },
  {
    title: '平台',
    key: 'platform',
    width: 120,
    render(row) {
      const map = {
        all: '通用',
        boss: 'Boss直聘',
        qcwy: '前程无忧',
        zhilian: '智联招聘',
      }
      return map[row.platform] || row.platform
    },
  },
  {
    title: '类型',
    key: 'proxy_type',
    width: 120,
    render(row) {
      const map = {
        http: 'HTTP 代理',
        socks: 'SOCKS 代理',
        tunnel: '隧道代理',
      }
      return map[row.proxy_type] || row.proxy_type
    },
  },
  { title: '代理地址', key: 'proxy_url', minWidth: 260, ellipsis: { tooltip: true } },
  {
    title: '启用',
    key: 'is_active',
    width: 90,
    render: (row) => (row.is_active ? '是' : '否'),
  },
  { title: '创建时间', key: 'created_at', minWidth: 180 },
  {
    title: '操作',
    key: 'actions',
    width: 160,
    render(row) {
      return h('div', { style: 'display:flex;gap:8px' }, [
        h(
          NButton,
          { type: 'primary', size: 'small', onClick: () => handleEdit(row) },
          { default: () => '编辑' }
        ),
        h(
          NButton,
          { size: 'small', onClick: () => handleDelete(row.id) },
          { default: () => '删除' }
        ),
      ])
    },
  },
]

const providerColumns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '名称', key: 'name', minWidth: 140 },
  {
    title: '平台',
    key: 'platform',
    width: 120,
    render(row) {
      const map = {
        all: '通用',
        boss: 'Boss直聘',
        qcwy: '前程无忧',
        zhilian: '智联招聘',
      }
      return map[row.platform] || row.platform
    },
  },
  {
    title: '解析模式',
    key: 'mode',
    width: 100,
    render(row) {
      const map = {
        json: 'JSON',
        text: '文本',
      }
      return map[row.mode] || row.mode
    },
  },
  { title: '列表路径', key: 'list_path', minWidth: 180, ellipsis: { tooltip: true } },
  { title: 'IP路径', key: 'ip_path', minWidth: 160, ellipsis: { tooltip: true } },
  { title: '端口路径', key: 'port_path', minWidth: 160, ellipsis: { tooltip: true } },
  { title: '用户名路径', key: 'username_path', minWidth: 160, ellipsis: { tooltip: true } },
  { title: '密码路径', key: 'password_path', minWidth: 160, ellipsis: { tooltip: true } },
  { title: '文本正则', key: 'pattern', minWidth: 200, ellipsis: { tooltip: true } },
  { title: '模板', key: 'template', minWidth: 220, ellipsis: { tooltip: true } },
  {
    title: '操作',
    key: 'actions',
    width: 160,
    render(row) {
      return h('div', { style: 'display:flex;gap:8px' }, [
        h(
          NButton,
          { type: 'primary', size: 'small', onClick: () => handleEditProvider(row) },
          { default: () => '编辑' }
        ),
        h(
          NButton,
          { size: 'small', onClick: () => handleDeleteProvider(row.id) },
          { default: () => '删除' }
        ),
      ])
    },
  },
]

async function handleGetList(params) {
  const res = await proxyApi.list(params)
  return res
}

async function handleGetProviderList(params) {
  const res = await proxyApi.listProviders(params)
  return res
}

const initForm = {
  id: null,
  name: '',
  platform: 'all',
  proxy_type: 'http',
  proxy_url: '',
  is_active: true,
}

const initProviderForm = {
  id: null,
  name: '',
  platform: 'all',
  mode: 'json',
  list_path: '',
  ip_path: '',
  port_path: '',
  username_path: '',
  password_path: '',
  pattern: '',
  template: '{ip}:{port}',
}

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '代理',
  initForm,
  doCreate: (data) => proxyApi.create(data),
  doUpdate: (data) => proxyApi.update(data.id, data),
  doDelete: (id) => proxyApi.remove(id),
  refresh: () => tableRef?.value?.handleSearch(),
})

const {
  modalVisible: providerModalVisible,
  modalTitle: providerModalTitle,
  modalLoading: providerModalLoading,
  handleAdd: handleAddProvider,
  handleDelete: handleDeleteProvider,
  handleEdit: handleEditProvider,
  handleSave: handleSaveProvider,
  modalForm: providerModalForm,
  modalFormRef: providerModalFormRef,
} = useCRUD({
  name: '解析规则',
  initForm: initProviderForm,
  doCreate: (data) => proxyApi.createProvider(data),
  doUpdate: (data) => proxyApi.updateProvider(data.id, data),
  doDelete: (id) => proxyApi.removeProvider(id),
  refresh: () => providerTableRef?.value?.handleSearch(),
})

onMounted(() => {
  tableRef.value?.handleSearch()
})
</script>
