<template>
  <ArtTableFullScreen>
    <div class="package-commission-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="formFilters"
        :items="formItems"
        @reset="handleReset"
        @search="handleSearch"
      ></ArtSearchBar>

      <ElCard shadow="never" class="art-table-card">
        <!-- 表格头部 -->
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <ElButton type="primary" @click="handleSearch">搜索</ElButton>
            <ElButton type="success" @click="showAddDialog">新增</ElButton>
            <ElButton @click="exportExcel">导出excel</ElButton>
          </template>
        </ArtTableHeader>

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

        <!-- 新增套餐佣金网卡对话框 -->
        <ElDialog
          v-model="addDialogVisible"
          title="新增套餐佣金网卡"
          width="500px"
          align-center
          :close-on-click-modal="false"
        >
          <ElForm ref="addFormRef" :model="addFormData" :rules="addRules" label-width="120px">
            <ElFormItem label="卡号" prop="cardNumber">
              <ElInput v-model="addFormData.cardNumber" placeholder="请输入卡号" clearable />
            </ElFormItem>

            <ElFormItem label="月份" prop="month">
              <ElDatePicker
                v-model="addFormData.month"
                type="month"
                placeholder="请选择月份"
                style="width: 100%"
                format="YYYY-MM"
                value-format="YYYY-MM"
              />
            </ElFormItem>
          </ElForm>

          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="addDialogVisible = false">取消</ElButton>
              <ElButton type="primary" @click="handleAddSubmit" :loading="addLoading">
                确认新增
              </ElButton>
            </div>
          </template>
        </ElDialog>
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { ElTag, ElMessage, ElMessageBox, ElDatePicker } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { SearchChangeParams, SearchFormItem } from '@/types'

  defineOptions({ name: 'PackageCommission' })

  const addDialogVisible = ref(false)
  const loading = ref(false)
  const addLoading = ref(false)

  // 定义表单搜索初始值
  const initialSearchState = {
    cardNumber: '',
    virtualNumber: '',
    createDateRange: []
  }

  // 响应式表单数据
  const formFilters = reactive({ ...initialSearchState })

  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })

  // 表格数据
  const tableData = ref<any[]>([])

  // 表格实例引用
  const tableRef = ref()

  // 选中的行数据
  const selectedRows = ref<any[]>([])

  // 新增表单实例
  const addFormRef = ref<FormInstance>()

  // 新增表单数据
  const addFormData = reactive({
    cardNumber: '',
    month: ''
  })

  // 模拟数据
  const mockData = [
    {
      id: 1,
      cardNumber: '89860621370079892035',
      accessNumber: '1440012345678',
      virtualNumber: '100001',
      cardCompany: '联通',
      month: '2025-11',
      createTime: '2025-11-08 10:30:00',
      creator: '张若暄'
    },
    {
      id: 2,
      cardNumber: '89860621370079892036',
      accessNumber: '1440012345679',
      virtualNumber: '100002',
      cardCompany: '移动',
      month: '2025-11',
      createTime: '2025-11-07 14:15:00',
      creator: '孔丽娟'
    },
    {
      id: 3,
      cardNumber: '89860621370079892037',
      accessNumber: '1440012345680',
      virtualNumber: '100003',
      cardCompany: '电信',
      month: '2025-11',
      createTime: '2025-11-06 09:45:00',
      creator: '李佳音'
    },
    {
      id: 4,
      cardNumber: '89860621370079892038',
      accessNumber: '1440012345681',
      virtualNumber: '100004',
      cardCompany: '联通',
      month: '2025-10',
      createTime: '2025-10-20 16:20:00',
      creator: '赵强'
    },
    {
      id: 5,
      cardNumber: '89860621370079892039',
      accessNumber: '1440012345682',
      virtualNumber: '100005',
      cardCompany: '广电',
      month: '2025-10',
      createTime: '2025-10-15 11:30:00',
      creator: '张若暄'
    }
  ]

  // 重置表单
  const handleReset = () => {
    Object.assign(formFilters, { ...initialSearchState })
    pagination.currentPage = 1
    getCommissionCardList()
  }

  // 搜索处理
  const handleSearch = () => {
    console.log('搜索参数:', formFilters)
    pagination.currentPage = 1
    getCommissionCardList()
  }

  // 表单项变更处理
  const handleFormChange = (params: SearchChangeParams): void => {
    console.log('表单项变更:', params)
  }

  // 表单配置项
  const formItems: SearchFormItem[] = [
    {
      label: '卡号',
      prop: 'cardNumber',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入卡号'
      },
      onChange: handleFormChange
    },
    {
      label: '虚拟号',
      prop: 'virtualNumber',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入虚拟号'
      },
      onChange: handleFormChange
    },
    {
      label: '创建时间',
      prop: 'createDateRange',
      type: 'daterange',
      config: {
        type: 'daterange',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间'
      },
      onChange: handleFormChange
    }
  ]

  // 列配置
  const columnOptions = [
    { label: '勾选', type: 'selection' },
    { label: '卡号', prop: 'cardNumber' },
    { label: '接入号', prop: 'accessNumber' },
    { label: '虚拟号', prop: 'virtualNumber' },
    { label: '开卡公司', prop: 'cardCompany' },
    { label: '月份', prop: 'month' },
    { label: '创建时间', prop: 'createTime' },
    { label: '创建人', prop: 'creator' },
    { label: '操作', prop: 'operation' }
  ]

  // 导出Excel
  const exportExcel = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要导出的数据')
      return
    }
    ElMessage.success(`导出 ${selectedRows.value.length} 条套餐佣金网卡记录`)
  }

  // 显示新增对话框
  const showAddDialog = () => {
    addDialogVisible.value = true
    // 重置表单
    if (addFormRef.value) {
      addFormRef.value.resetFields()
    }
    addFormData.cardNumber = ''
    addFormData.month = ''
  }

  // 查看详情
  const viewDetails = (row: any) => {
    ElMessage.info(`查看详情: ${row.cardNumber}`)
  }

  // 编辑记录
  const editRecord = (row: any) => {
    ElMessage.info(`编辑记录: ${row.cardNumber}`)
  }

  // 删除记录
  const deleteRecord = (row: any) => {
    ElMessageBox.confirm(`确定要删除卡号为"${row.cardNumber}"的佣金记录吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        ElMessage.success('删除成功')
        getCommissionCardList()
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    { type: 'selection' },
    {
      prop: 'cardNumber',
      label: '卡号',
      minWidth: 180
    },
    {
      prop: 'accessNumber',
      label: '接入号',
      width: 140
    },
    {
      prop: 'virtualNumber',
      label: '虚拟号',
      width: 100
    },
    {
      prop: 'cardCompany',
      label: '开卡公司',
      width: 100
    },
    {
      prop: 'month',
      label: '月份',
      width: 100
    },
    {
      prop: 'createTime',
      label: '创建时间',
      width: 160
    },
    {
      prop: 'creator',
      label: '创建人',
      width: 100
    },
    {
      prop: 'operation',
      label: '操作',
      width: 220,
      formatter: (row: any) => {
        return h('div', { class: 'operation-buttons' }, [
          h(ArtButtonTable, {
            text: '查看',
            onClick: () => viewDetails(row)
          }),
          h(ArtButtonTable, {
            text: '编辑',
            onClick: () => editRecord(row)
          }),
          h(ArtButtonTable, {
            text: '删除',
            onClick: () => deleteRecord(row)
          })
        ])
      }
    }
  ])

  onMounted(() => {
    getCommissionCardList()
  })

  // 获取套餐佣金网卡列表
  const getCommissionCardList = async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 500))

      const startIndex = (pagination.currentPage - 1) * pagination.pageSize
      const endIndex = startIndex + pagination.pageSize
      const paginatedData = mockData.slice(startIndex, endIndex)

      tableData.value = paginatedData
      pagination.total = mockData.length
      loading.value = false
    } catch (error) {
      console.error('获取套餐佣金网卡列表失败:', error)
      loading.value = false
    }
  }

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

  // 处理表格行选择变化
  const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
  }

  // 处理表格分页变化
  const handleSizeChange = (newPageSize: number) => {
    pagination.pageSize = newPageSize
    getCommissionCardList()
  }

  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.currentPage = newCurrentPage
    getCommissionCardList()
  }

  // 新增表单验证规则
  const addRules = reactive<FormRules>({
    cardNumber: [
      { required: true, message: '请输入卡号', trigger: 'blur' },
      { min: 15, max: 20, message: '卡号长度在 15 到 20 个字符', trigger: 'blur' }
    ],
    month: [{ required: true, message: '请选择月份', trigger: 'change' }]
  })

  // 提交新增
  const handleAddSubmit = async () => {
    if (!addFormRef.value) return

    await addFormRef.value.validate((valid) => {
      if (valid) {
        addLoading.value = true

        // 模拟新增过程
        setTimeout(() => {
          ElMessage.success(
            `新增套餐佣金网卡成功！卡号：${addFormData.cardNumber}，月份：${addFormData.month}`
          )
          addDialogVisible.value = false
          addLoading.value = false
          getCommissionCardList()
        }, 2000)
      }
    })
  }
</script>

<style lang="scss" scoped>
  .package-commission-page {
    // 可以添加特定样式
  }

  :deep(.operation-buttons) {
    display: flex;
    gap: 8px;
  }

  .dialog-footer {
    text-align: right;
  }

  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
</style>
