<template>
  <div class="complete-example">
    <h2>完整的 EditTable 使用示例</h2>
    
    <!-- 基础配置示例 -->
    <el-card class="example-card">
      <template #header>
        <div class="card-header">
          <span>基础功能示例</span>
          <el-switch
            v-model="isReadonly"
            active-text="只读模式"
            inactive-text="编辑模式"
          />
        </div>
      </template>
      
      <EditTable
        ref="basicTableRef"
        v-model="basicTableData"
        :config="basicTableConfig"
        title="员工信息"
        addButtonText="添加员工"
        :empty-row="getEmptyEmployeeRow"
        :readonly="isReadonly"
        @add="handleBasicAdd"
        @delete="handleBasicDelete"
        @copy="handleBasicCopy"
        @validate="handleBasicValidate"
      />
    </el-card>

    <!-- 高级功能示例 -->
    <el-card class="example-card">
      <template #header>
        <span>高级功能示例（含分页、导入导出）</span>
      </template>
      
      <EditTable
        ref="advancedTableRef"
        v-model="advancedTableData"
        :config="advancedTableConfig"
        title="产品明细"
        addButtonText="添加产品"
        :empty-row="getEmptyProductRow"
        :on-import="handleImport"
        :on-export="handleExport"
        :on-download-template="handleDownloadTemplate"
        @add="handleAdvancedAdd"
        @delete="handleAdvancedDelete"
        @copy="handleAdvancedCopy"
        @validate="handleAdvancedValidate"
      />
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="validateAllTables">验证所有表格</el-button>
      <el-button type="success" @click="exportAllData">导出所有数据</el-button>
      <el-button type="warning" @click="clearAllData">清空所有数据</el-button>
      <el-button @click="resetToDefault">重置为默认数据</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import EditTable from '../index.vue'
import {
  createInputField,
  createNumberField,
  createSelectField,
  createMultiSelectField,
  createDateField,
  createDateRangeField,
  createTreeSelectField,
  createCascaderField,
  createPopupSelectField,
  setRequired,
  type ActionEventParams,
  type ImportParams,
  type ExportParams
} from '../helpers'

// 响应式数据
const basicTableRef = ref()
const advancedTableRef = ref()
const isReadonly = ref(false)

// 基础表格数据
const basicTableData = ref([
  {
    id: 1,
    name: '张三',
    age: 28,
    gender: 'male',
    department: 'dev',
    email: 'zhangsan@example.com',
    phone: '13800138001',
    joinDate: Date.now() - 365 * 24 * 60 * 60 * 1000 // 一年前
  }
])

// 高级表格数据
const advancedTableData = ref([
  {
    id: 1,
    productName: 'iPhone 15 Pro',
    category: ['electronics', 'mobile'],
    price: 7999,
    stock: 100,
    supplier: 'apple',
    region: ['asia', 'china', 'beijing'],
    productionDate: Date.now() - 30 * 24 * 60 * 60 * 1000, // 30天前
    dateRange: [Date.now() - 7 * 24 * 60 * 60 * 1000, Date.now()], // 最近7天
    description: '最新款苹果手机'
  }
])

// 基础表格配置
const basicTableConfig = {
  fields: [
    setRequired(createInputField('name', '姓名'), '姓名不能为空'),
    createNumberField('age', '年龄', { min: 18, max: 65, precision: 0 }),
    createSelectField('gender', '性别', {
      options: [
        { label: '男', value: 'male' },
        { label: '女', value: 'female' }
      ]
    }),
    createSelectField('department', '部门', {
      options: [
        { label: '研发部', value: 'dev' },
        { label: '产品部', value: 'product' },
        { label: '市场部', value: 'marketing' },
        { label: '人事部', value: 'hr' }
      ],
      filterable: true,
      clearable: true
    }),
    createInputField('email', '邮箱', {
      placeholder: '请输入邮箱地址',
      clearable: true
    }),
    createInputField('phone', '手机号', {
      placeholder: '请输入手机号',
      clearable: true
    }),
    createDateField('joinDate', '入职日期', {
      type: 'date',
      format: 'YYYY-MM-DD',
      valueFormat: 'x'
    })
  ],
  showIndex: true,
  indexWidth: 60,
  showAction: true,
  actionWidth: 160,
  border: true,
  stripe: true,
  maxHeight: 400,
  size: 'default'
}

// 高级表格配置
const advancedTableConfig = {
  fields: [
    setRequired(createInputField('productName', '产品名称'), '产品名称不能为空'),
    createMultiSelectField('category', '产品分类', {
      options: [
        { label: '电子产品', value: 'electronics' },
        { label: '手机', value: 'mobile' },
        { label: '电脑', value: 'computer' },
        { label: '家电', value: 'appliance' },
        { label: '服装', value: 'clothing' }
      ]
    }),
    createNumberField('price', '价格', { 
      precision: 2, 
      step: 0.01, 
      min: 0 
    }),
    createNumberField('stock', '库存', { 
      precision: 0, 
      min: 0 
    }),
    createSelectField('supplier', '供应商', {
      options: [
        { label: '苹果', value: 'apple' },
        { label: '三星', value: 'samsung' },
        { label: '华为', value: 'huawei' },
        { label: '小米', value: 'xiaomi' }
      ],
      filterable: true
    }),
    createCascaderField('region', '地区', {
      options: [
        {
          label: '亚洲',
          value: 'asia',
          children: [
            {
              label: '中国',
              value: 'china',
              children: [
                { label: '北京', value: 'beijing' },
                { label: '上海', value: 'shanghai' },
                { label: '广州', value: 'guangzhou' }
              ]
            },
            {
              label: '日本',
              value: 'japan',
              children: [
                { label: '东京', value: 'tokyo' },
                { label: '大阪', value: 'osaka' }
              ]
            }
          ]
        },
        {
          label: '欧洲',
          value: 'europe',
          children: [
            {
              label: '德国',
              value: 'germany',
              children: [
                { label: '柏林', value: 'berlin' },
                { label: '慕尼黑', value: 'munich' }
              ]
            }
          ]
        }
      ],
      cascaderProps: {
        expandTrigger: 'hover',
        checkStrictly: false
      }
    }),
    
    // 弹窗选择器示例
    createPopupSelectField('productId', '产品编号', {
      // 弹窗配置
      title: '选择产品',
      width: '900px',
      height: '600px',

      // 模拟接口
      api: {
        getList: async (params: any) => {
          // 模拟异步接口调用
          console.log('产品查询参数:', params)
          
          // 模拟数据
          const mockData = [
            { id: 1, productId: 'P001', productName: 'iPhone 15 Pro', category: '手机', price: 8999, stock: 100 },
            { id: 2, productId: 'P002', productName: 'MacBook Pro 16', category: '电脑', price: 19999, stock: 50 },
            { id: 3, productId: 'P003', productName: 'AirPods Pro', category: '耳机', price: 1999, stock: 200 },
            { id: 4, productId: 'P004', productName: 'iPad Air', category: '平板', price: 4599, stock: 80 }
          ]
          
          // 模拟筛选逻辑
          let filteredData = mockData
          if (params.productName) {
            filteredData = filteredData.filter(item => 
              item.productName.toLowerCase().includes(params.productName.toLowerCase())
            )
          }
          if (params.category) {
            filteredData = filteredData.filter(item => item.category === params.category)
          }
          
          return {
            list: filteredData,
            total: filteredData.length
          }
        }
      },

      // 默认查询参数
      queryParams: {
        category: '手机',  // 默认只显示手机类产品
        status: 'active'  // 默认只显示激活状态的产品
      },

      // 查询条件
      searchForm: {
        items: [
          {
            field: 'productName',
            label: '产品名称',
            type: 'input',
            placeholder: '请输入产品名称'
          },
          {
            field: 'category',
            label: '产品分类',
            type: 'select',
            placeholder: '请选择产品分类',
            options: [
              { label: '全部', value: '' },
              { label: '手机', value: 'mobile' },
              { label: '电脑', value: 'computer' },
              { label: '耳机', value: 'headphone' },
              { label: '平板', value: 'tablet' }
            ]
          }
        ]
      },

      // 表格列配置
      columns: [
        {
          prop: 'productId',
          label: '产品编号',
          width: 120,
          align: 'center'
        },
        {
          prop: 'productName',
          label: '产品名称',
          minWidth: 150
        },
        {
          prop: 'category',
          label: '产品分类',
          width: 100,
          align: 'center'
        },
        {
          prop: 'price',
          label: '价格',
          width: 100,
          align: 'center'
        },
        {
          prop: 'stock',
          label: '库存',
          width: 80,
          align: 'center'
        }
      ],

      // 选择配置
      selection: {
        labelKey: 'productName', // 显示产品名称
        valueKey: 'productId'   // 保存产品编号
      },

      // 分页配置
      pagination: {
        pageSize: 5,
        showSizeChanger: true,
        pageSizeOptions: [5, 10, 20]
      }
    }, {
      // 字段宽度配置
      width: 160,
      align: 'center'
    }),

    createDateField('productionDate', '生产日期', {
      type: 'date',
      format: 'YYYY-MM-DD',
      valueFormat: 'x'
    }),
    createDateRangeField('dateRange', '有效期范围', {
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
      valueFormat: 'x'
    }),
    createInputField('description', '描述', {
      minWidth: 200,
      placeholder: '请输入产品描述'
    })
  ],
  
  // 分页配置
  pagination: {
    enabled: true,
    pageSize: 5,
    showSizeChanger: true,
    pageSizeOptions: [5, 10, 20, 50],
    showQuickJumper: true,
    showTotal: true
  },
  
  // 导入导出配置
  importExport: {
    showImport: true,
    showExport: true,
    importButtonText: '导入产品',
    exportButtonText: '导出数据',
    templateFileName: '产品数据导入模板.xlsx',
    acceptFileTypes: ['.xlsx', '.xls', '.csv']
  },
  
  showIndex: true,
  indexWidth: 60,
  showAction: true,
  actionWidth: 160,
  border: true,
  stripe: true,
  maxHeight: 400,
  size: 'small'
}

// 空行数据
const getEmptyEmployeeRow = () => ({
  id: undefined,
  name: '',
  age: undefined,
  gender: '',
  department: '',
  email: '',
  phone: '',
  joinDate: undefined
})

const getEmptyProductRow = () => ({
  id: undefined,
  productName: '',
  category: [],
  price: undefined,
  stock: undefined,
  supplier: '',
  region: [],
  productId: '',  // 弹窗选择器选中的产品编号
  productionDate: undefined,
  dateRange: [],
  description: ''
})

// 基础表格事件处理
const handleBasicAdd = (params: ActionEventParams) => {
  console.log('基础表格 - 添加员工:', params)
  ElMessage.success(`添加员工: ${params.row.name}`)
}

const handleBasicCopy = (params: ActionEventParams) => {
  console.log('基础表格 - 复制员工:', params)
  ElMessage.success(`复制员工: ${params.row.name}`)
}

const handleBasicDelete = (params: ActionEventParams) => {
  console.log('基础表格 - 删除员工:', params)
  ElMessage.warning(`删除员工: ${params.row.name}`)
}

const handleBasicValidate = (valid: boolean) => {
  console.log('基础表格 - 验证结果:', valid)
  if (valid) {
    ElMessage.success('基础表格验证通过')
  } else {
    ElMessage.error('基础表格验证失败')
  }
}

// 高级表格事件处理
const handleAdvancedAdd = (params: ActionEventParams) => {
  console.log('高级表格 - 添加产品:', params)
  ElMessage.success(`添加产品: ${params.row.productName}`)
}

const handleAdvancedCopy = (params: ActionEventParams) => {
  console.log('高级表格 - 复制产品:', params)
  ElMessage.success(`复制产品: ${params.row.productName}`)
}

const handleAdvancedDelete = (params: ActionEventParams) => {
  console.log('高级表格 - 删除产品:', params)
  ElMessage.warning(`删除产品: ${params.row.productName}`)
}

const handleAdvancedValidate = (valid: boolean) => {
  console.log('高级表格 - 验证结果:', valid)
  if (valid) {
    ElMessage.success('高级表格验证通过')
  } else {
    ElMessage.error('高级表格验证失败')
  }
}

// 导入导出功能
const handleDownloadTemplate = async () => {
  console.log('下载导入模板')
  try {
    const templateData = [
      {
        '产品名称': '示例产品',
        '产品分类': ['电子产品', '手机'],
        '价格': 1999,
        '库存': 50,
        '供应商': '示例供应商',
        '地区': ['亚洲', '中国', '北京'],
        '生产日期': new Date().toISOString().split('T')[0],
        '有效期范围': ['2024-01-01', '2024-12-31'],
        '描述': '示例产品描述'
      }
    ]
    
    console.log('模板数据:', templateData)
    ElMessage.success('模板下载成功（查看控制台）')
  } catch (error) {
    ElMessage.error('下载模板失败')
  }
}

const handleImport = async (params: ImportParams) => {
  console.log('导入数据:', params)
  try {
    // 模拟导入延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const importedData = [
      {
        id: undefined,
        productName: `导入产品 ${Date.now()}`,
        category: ['electronics'],
        price: Math.floor(Math.random() * 10000),
        stock: Math.floor(Math.random() * 100),
        supplier: 'imported',
        region: ['asia', 'china', 'beijing'],
        productionDate: Date.now() - 30 * 24 * 60 * 60 * 1000,
        dateRange: [Date.now(), Date.now() + 30 * 24 * 60 * 60 * 1000],
        description: '通过导入添加的产品'
      }
    ]
    
    ElMessage.success(`成功导入 ${importedData.length} 条数据`)
    return importedData
  } catch (error) {
    ElMessage.error('导入失败')
    throw error
  }
}

const handleExport = async (params: ExportParams) => {
  console.log('导出数据:', params)
  try {
    console.log('导出的数据:', params.data)
    console.log('字段配置:', params.fields)
    ElMessage.success('导出成功（查看控制台）')
  } catch (error) {
    ElMessage.error('导出失败')
    throw error
  }
}

// 全局操作
const validateAllTables = async () => {
  const basicValid = await basicTableRef.value?.validate()
  const advancedValid = await advancedTableRef.value?.validate()
  
  if (basicValid && advancedValid) {
    ElMessage.success('所有表格验证通过')
  } else {
    ElMessage.error('存在验证失败的数据')
  }
}

const exportAllData = () => {
  const allData = {
    basicTable: basicTableData.value,
    advancedTable: advancedTableData.value
  }
  console.log('所有数据:', allData)
  ElMessage.success('数据导出成功（查看控制台）')
}

const clearAllData = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有数据吗？', '确认操作', {
      type: 'warning'
    })
    
    basicTableData.value = []
    advancedTableData.value = []
    ElMessage.success('数据清空成功')
  } catch {
    ElMessage.info('操作已取消')
  }
}

const resetToDefault = () => {
  basicTableData.value = [
    {
      id: 1,
      name: '张三',
      age: 28,
      gender: 'male',
      department: 'dev',
      email: 'zhangsan@example.com',
      phone: '13800138001',
      joinDate: Date.now() - 365 * 24 * 60 * 60 * 1000
    }
  ]
  
  advancedTableData.value = [
    {
      id: 1,
      productName: 'iPhone 15 Pro',
      category: ['electronics', 'mobile'],
      price: 7999,
      stock: 100,
      supplier: 'apple',
      region: ['asia', 'china', 'beijing'],
      productionDate: Date.now() - 30 * 24 * 60 * 60 * 1000,
      dateRange: [Date.now() - 7 * 24 * 60 * 60 * 1000, Date.now()],
      description: '最新款苹果手机'
    }
  ]
  
  ElMessage.success('数据重置成功')
}
</script>

<style scoped>
.complete-example {
  padding: 20px;
}

.example-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

.action-buttons .el-button {
  margin: 0 8px;
}
</style>