<template>
  <ArtTableFullScreen>
    <div class="polling-config-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        :show-expand="true"
        label-width="100"
        @reset="handleReset"
        @search="handleSearch"
      />

      <el-card shadow="never" class="art-table-card">
        <!-- 表格头部 -->
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <el-button type="primary" @click="handleCreate" v-permission="'polling_config_create'">
              新增配置
            </el-button>
          </template>
        </ArtTableHeader>

        <!-- 表格 -->
        <ArtTable
          ref="tableRef"
          row-key="id"
          :loading="loading"
          :data="tableData"
          :currentPage="pagination.page"
          :pageSize="pagination.page_size"
          :total="pagination.total"
          :marginTop="10"
          :actions="getActions"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #default>
            <el-table-column v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
          </template>
        </ArtTable>
      </el-card>

      <!-- 新增/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'create' ? '新增轮询配置' : '编辑轮询配置'"
        width="900px"
        :close-on-click-modal="false"
        @closed="handleDialogClosed"
      >
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
          <!-- 基本信息 -->
          <el-divider content-position="left">基本信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="配置名称" prop="config_name">
                <el-input
                  v-model="formData.config_name"
                  placeholder="请输入配置名称"
                  maxlength="100"
                  show-word-limit
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-input-number
                  v-model="formData.priority"
                  :min="1"
                  :max="1000"
                  :controls="false"
                  placeholder="数字越小优先级越高"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="配置说明" prop="description">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入配置说明(最多500字符)"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 筛选条件 -->
          <el-divider content-position="left">筛选条件</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="卡业务类型" prop="card_category">
                <el-select
                  v-model="formData.card_category"
                  placeholder="请选择卡业务类型"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="普通卡" value="normal" />
                  <el-option label="行业卡" value="industry" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="卡状态条件" prop="card_condition">
                <el-select
                  v-model="formData.card_condition"
                  placeholder="请选择卡状态条件"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="未实名" value="not_real_name" />
                  <el-option label="已实名" value="real_name" />
                  <el-option label="已激活" value="activated" />
                  <el-option label="已停用" value="suspended" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="运营商" prop="carrier_id">
                <el-select
                  v-model="formData.carrier_id"
                  placeholder="请选择运营商"
                  style="width: 100%"
                  filterable
                  remote
                  :remote-method="remoteSearchCarrier"
                  clearable
                >
                  <el-option
                    v-for="carrier in carrierList"
                    :key="carrier.id"
                    :label="carrier.carrier_name"
                    :value="carrier.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 检查间隔配置 -->
          <el-divider content-position="left">检查间隔配置（秒）</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="实名检查" prop="realname_check_interval">
                <el-input-number
                  v-model="formData.realname_check_interval"
                  :min="30"
                  :controls="false"
                  placeholder="最小30"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="套餐检查" prop="package_check_interval">
                <el-input-number
                  v-model="formData.package_check_interval"
                  :min="60"
                  :controls="false"
                  placeholder="最小60"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="流量检查" prop="carddata_check_interval">
                <el-input-number
                  v-model="formData.carddata_check_interval"
                  :min="60"
                  :controls="false"
                  placeholder="最小60"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保护期检查" prop="protect_check_interval">
                <el-input-number
                  v-model="formData.protect_check_interval"
                  :min="30"
                  :controls="false"
                  placeholder="最小30"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="卡状态检查" prop="card_status_check_interval">
                <el-input-number
                  v-model="formData.card_status_check_interval"
                  :min="30"
                  :controls="false"
                  placeholder="最小30"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted, nextTick, h } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { PollingConfigService, CarrierService } from '@/api/modules'
  import type {
    PollingConfig,
    PollingConfigQueryParams,
    CreatePollingConfigRequest,
    UpdatePollingConfigRequest,
    PollingCardCategory,
    CardCondition
  } from '@/types/api'
  import type { SearchFormItem } from '@/types'
  import { formatDateTime } from '@/utils/business/format'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'

  const loading = ref(false)
  const tableData = ref<PollingConfig[]>([])
  const tableRef = ref()
  const dialogVisible = ref(false)
  const dialogType = ref<'create' | 'edit'>('create')
  const formRef = ref<FormInstance>()
  const carrierList = ref<any[]>([])

  // 分页数据
  const pagination = reactive({
    page: 1,
    page_size: 10,
    total: 0
  })

  // 搜索表单
  const searchForm = reactive({
    config_name: '',
    card_category: undefined as PollingCardCategory | undefined,
    card_condition: undefined as CardCondition | undefined,
    carrier_id: undefined as number | undefined,
    status: undefined as number | undefined
  })

  const formData = reactive<CreatePollingConfigRequest & { id?: number }>({
    config_name: '',
    priority: 1,
    description: '',
    card_category: undefined,
    card_condition: undefined,
    carrier_id: undefined,
    realname_check_interval: null,
    package_check_interval: null,
    carddata_check_interval: null,
    protect_check_interval: null,
    card_status_check_interval: null
  })

  const formRules: FormRules = {
    config_name: [
      { required: true, message: '请输入配置名称', trigger: 'blur' },
      { min: 1, max: 100, message: '配置名称长度为1-100字符', trigger: 'blur' }
    ],
    priority: [
      { required: true, message: '请输入优先级', trigger: 'blur' },
      { type: 'number', min: 1, max: 1000, message: '优先级范围为1-1000', trigger: 'blur' }
    ],
    description: [{ max: 500, message: '配置说明最多500字符', trigger: 'blur' }],
    realname_check_interval: [
      { type: 'number', min: 30, message: '实名检查间隔最小30秒', trigger: 'blur' }
    ],
    package_check_interval: [
      { type: 'number', min: 60, message: '套餐检查间隔最小60秒', trigger: 'blur' }
    ],
    carddata_check_interval: [
      { type: 'number', min: 60, message: '流量检查间隔最小60秒', trigger: 'blur' }
    ],
    protect_check_interval: [
      { type: 'number', min: 30, message: '保护期检查间隔最小30秒', trigger: 'blur' }
    ],
    card_status_check_interval: [
      { type: 'number', min: 30, message: '卡状态检查间隔最小30秒', trigger: 'blur' }
    ]
  }

  // 搜索表单配置
  const searchFormItems = computed<SearchFormItem[]>(() => [
    {
      label: '配置名称',
      prop: 'config_name',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入配置名称'
      }
    },
    {
      label: '卡业务类型',
      prop: 'card_category',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '请选择卡业务类型'
      },
      options: () => [
        { label: '普通卡', value: 'normal' },
        { label: '行业卡', value: 'industry' }
      ]
    },
    {
      label: '卡状态条件',
      prop: 'card_condition',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '请选择卡状态'
      },
      options: () => [
        { label: '未实名', value: 'not_real_name' },
        { label: '已实名', value: 'real_name' },
        { label: '已激活', value: 'activated' },
        { label: '已停用', value: 'suspended' }
      ]
    },
    {
      label: '运营商',
      prop: 'carrier_id',
      type: 'select',
      config: {
        clearable: true,
        filterable: true,
        remote: true,
        remoteMethod: remoteSearchCarrier,
        placeholder: '请选择运营商'
      },
      options: () =>
        carrierList.value.map((c) => ({
          label: c.carrier_name,
          value: c.id
        }))
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '请选择状态'
      },
      options: () => [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 }
      ]
    }
  ])

  const getCardConditionLabel = (condition: string) => {
    const labels: Record<string, string> = {
      not_real_name: '未实名',
      real_name: '已实名',
      activated: '已激活',
      suspended: '已停用'
    }
    return labels[condition] || condition
  }

  const getCarrierName = (carrierId: number) => {
    const carrier = carrierList.value.find((c) => c.id === carrierId)
    return carrier?.carrier_name || '-'
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'config_name',
      label: '配置名称',
      minWidth: 150
    },
    {
      prop: 'description',
      label: '配置说明',
      minWidth: 200,
      showOverflowTooltip: true
    },
    {
      prop: 'card_category',
      label: '卡业务类型',
      width: 120,
      formatter: (row: any) =>
        row.card_category ? (row.card_category === 'normal' ? '普通卡' : '行业卡') : '-'
    },
    {
      prop: 'card_condition',
      label: '卡状态条件',
      width: 120,
      formatter: (row: any) =>
        row.card_condition ? getCardConditionLabel(row.card_condition) : '-'
    },
    {
      prop: 'carrier_id',
      label: '运营商',
      width: 120,
      formatter: (row: any) => getCarrierName(row.carrier_id)
    },
    {
      prop: 'priority',
      label: '优先级',
      width: 100
    },
    {
      prop: 'status',
      label: '状态',
      width: 100,
      formatter: (row: any) => (row.status === 1 ? '启用' : '禁用')
    },
    {
      label: '检查间隔(秒)',
      width: 220,
      slots: {
        default: ({ row }: any) =>
          h('div', { style: 'font-size: 12px; line-height: 1.5' }, [
            h('div', `实名: ${row.realname_check_interval ?? '-'}`),
            h('div', `套餐: ${row.package_check_interval ?? '-'}`),
            h('div', `流量: ${row.carddata_check_interval ?? '-'}`),
            h('div', `保护期: ${row.protect_check_interval ?? '-'}`),
            h('div', `卡状态: ${row.card_status_check_interval ?? '-'}`)
          ])
      }
    },
    {
      prop: 'created_at',
      label: '创建时间',
      width: 180,
      formatter: (row: any) => formatDateTime(row.created_at)
    },
    {
      prop: 'updated_at',
      label: '更新时间',
      width: 180,
      formatter: (row: any) => formatDateTime(row.updated_at)
    }
  ])

  const columnOptions = computed(() =>
    columns.value.map((col) => ({
      label: col.label,
      prop: col.prop || col.label,
      visible: true
    }))
  )

  const getActions = (row: PollingConfig) => {
    const actions: any[] = [
      {
        label: '编辑',
        handler: () => handleEdit(row)
      }
    ]

    actions.push({
      label: row.status === 1 ? '禁用' : '启用',
      type: row.status === 1 ? 'danger' : 'primary',
      handler: () => handleToggleStatus(row)
    })

    actions.push({
      label: '删除',
      type: 'danger',
      handler: () => handleDelete(row)
    })

    return actions
  }

  const loadCarriers = async (carrierName?: string) => {
    try {
      const { data } = await CarrierService.getCarriers({
        page: 1,
        page_size: 20,
        carrier_name: carrierName
      })
      carrierList.value = data.items || []
    } catch (error) {
      console.error('加载运营商列表失败', error)
    }
  }

  const remoteSearchCarrier = (query: string) => {
    if (query) {
      loadCarriers(query)
    } else {
      loadCarriers()
    }
  }

  const loadData = async () => {
    loading.value = true
    try {
      const queryParams: PollingConfigQueryParams = {
        page: pagination.page,
        page_size: pagination.page_size,
        ...searchForm
      }
      const { data } = await PollingConfigService.getPollingConfigs(queryParams)
      tableData.value = data.items
      pagination.total = data.total
    } catch {
      console.log('加载配置列表失败')
    } finally {
      loading.value = false
    }
  }

  const handleSearch = () => {
    pagination.page = 1
    loadData()
  }

  const handleReset = () => {
    Object.assign(searchForm, {
      config_name: '',
      card_category: undefined,
      card_condition: undefined,
      carrier_id: undefined,
      status: undefined
    })
    pagination.page = 1
    loadData()
  }

  const handleRefresh = () => {
    loadData()
  }

  const handleSizeChange = (size: number) => {
    pagination.page_size = size
    loadData()
  }

  const handleCurrentChange = (page: number) => {
    pagination.page = page
    loadData()
  }

  const handleCreate = () => {
    dialogType.value = 'create'
    Object.assign(formData, {
      id: undefined,
      config_name: '',
      priority: 1,
      description: '',
      card_category: undefined,
      card_condition: undefined,
      carrier_id: undefined,
      realname_check_interval: null,
      package_check_interval: null,
      carddata_check_interval: null,
      protect_check_interval: null,
      card_status_check_interval: null
    })
    dialogVisible.value = true
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  const handleEdit = async (row: PollingConfig) => {
    try {
      const { data } = await PollingConfigService.getPollingConfigById(row.id)
      dialogType.value = 'edit'
      Object.assign(formData, {
        id: data.id,
        config_name: data.config_name,
        priority: data.priority,
        description: data.description,
        card_category: data.card_category,
        card_condition: data.card_condition,
        carrier_id: data.carrier_id,
        realname_check_interval: data.realname_check_interval,
        package_check_interval: data.package_check_interval,
        carddata_check_interval: data.carddata_check_interval,
        protect_check_interval: data.protect_check_interval,
        card_status_check_interval: data.card_status_check_interval
      })
      dialogVisible.value = true
      nextTick(() => {
        formRef.value?.clearValidate()
      })
    } catch {
      console.log('获取配置详情失败')
    }
  }

  const handleToggleStatus = async (row: PollingConfig) => {
    const newStatus = row.status === 1 ? 0 : 1
    try {
      await PollingConfigService.updatePollingConfigStatus(row.id, { status: newStatus })
      ElMessage.success(newStatus === 1 ? '已启用' : '已禁用')
      await loadData()
    } catch {
      console.log('状态更新失败')
    }
  }

  const handleDelete = async (row: PollingConfig) => {
    try {
      await ElMessageBox.confirm(`确定要删除配置 "${row.config_name}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      await PollingConfigService.deletePollingConfig(row.id)
      ElMessage.success('删除成功')
      await loadData()
    } catch (error) {
      if (error !== 'cancel') {
        console.log('删除失败')
      }
    }
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (!valid) return

      try {
        const submitData: CreatePollingConfigRequest | UpdatePollingConfigRequest = {
          config_name: formData.config_name,
          priority: formData.priority,
          description: formData.description,
          card_category: formData.card_category,
          card_condition: formData.card_condition,
          carrier_id: formData.carrier_id,
          realname_check_interval: formData.realname_check_interval,
          package_check_interval: formData.package_check_interval,
          carddata_check_interval: formData.carddata_check_interval,
          protect_check_interval: formData.protect_check_interval,
          card_status_check_interval: formData.card_status_check_interval
        }

        if (dialogType.value === 'create') {
          await PollingConfigService.createPollingConfig(submitData as CreatePollingConfigRequest)
          ElMessage.success('创建成功')
        } else {
          await PollingConfigService.updatePollingConfig(formData.id!, submitData)
          ElMessage.success('更新成功')
        }

        dialogVisible.value = false
        await loadData()
      } catch {
        console.log(dialogType.value === 'create' ? '创建失败' : '更新失败')
      }
    })
  }

  const handleDialogClosed = () => {
    formRef.value?.resetFields()
  }

  onMounted(() => {
    loadCarriers()
    loadData()
  })
</script>

<style scoped lang="scss">
  .polling-config-page {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
</style>
