<template>
  <div class="batch-operations">
    <a-card title="批量操作" size="small">
      <template #extra>
        <a-space>
          <a-button 
            size="small" 
            @click="handleSelectAll"
            :disabled="!dataSource.length"
          >
            {{ isAllSelected ? '取消全选' : '全选' }}
          </a-button>
          <a-button 
            size="small" 
            @click="handleClearSelection"
            :disabled="!selectedItems.length"
          >
            清空选择
          </a-button>
        </a-space>
      </template>
      
      <div class="batch-info" v-if="selectedItems.length > 0">
        <a-alert
          :message="`已选择 ${selectedItems.length} 项`"
          type="info"
          show-icon
          closable
          @close="handleClearSelection"
        >
          <template #action>
            <a-space>
              <a-dropdown :trigger="['click']">
                <template #overlay>
                  <a-menu @click="handleBatchAction">
                    <a-menu-item 
                      v-for="action in availableActions" 
                      :key="action.key"
                      :disabled="action.disabled"
                    >
                      <component :is="action.icon" v-if="action.icon" />
                      {{ action.label }}
                    </a-menu-item>
                  </a-menu>
                </template>
                <a-button type="primary" size="small">
                  批量操作
                  <DownOutlined />
                </a-button>
              </a-dropdown>
            </a-space>
          </template>
        </a-alert>
      </div>
    </a-card>

    <!-- 批量状态更新模态框 -->
    <a-modal
      v-model:open="statusModalVisible"
      title="批量状态更新"
      @ok="handleStatusUpdate"
      :confirm-loading="statusUpdateLoading"
    >
      <a-form :model="statusForm" layout="vertical">
        <a-form-item label="新状态" required>
          <a-select v-model:value="statusForm.status" placeholder="请选择状态">
            <a-select-option 
              v-for="status in statusOptions" 
              :key="status.value" 
              :value="status.value"
            >
              <a-tag :color="status.color">{{ status.label }}</a-tag>
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="操作原因">
          <a-textarea
            v-model:value="statusForm.reason"
            placeholder="请输入操作原因（可选）"
            :rows="3"
            :maxlength="500"
            show-count
          />
        </a-form-item>
        
        <a-form-item>
          <a-alert
            :message="`将对 ${selectedItems.length} 个项目执行状态更新操作`"
            type="warning"
            show-icon
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 批量删除确认模态框 -->
    <a-modal
      v-model:open="deleteModalVisible"
      title="批量删除确认"
      @ok="handleBatchDelete"
      :confirm-loading="deleteLoading"
      ok-text="确认删除"
      ok-type="danger"
    >
      <a-alert
        message="危险操作"
        :description="`您即将删除 ${selectedItems.length} 个项目，此操作不可撤销！`"
        type="error"
        show-icon
      />
      
      <div style="margin-top: 16px;">
        <a-checkbox v-model:checked="deleteConfirm">
          我确认要执行此删除操作
        </a-checkbox>
      </div>
    </a-modal>

    <!-- 批量导出模态框 -->
    <a-modal
      v-model:open="exportModalVisible"
      title="批量导出"
      @ok="handleBatchExport"
      :confirm-loading="exportLoading"
    >
      <a-form :model="exportForm" layout="vertical">
        <a-form-item label="导出格式" required>
          <a-radio-group v-model:value="exportForm.format">
            <a-radio value="csv">CSV格式</a-radio>
            <a-radio value="excel">Excel格式</a-radio>
            <a-radio value="json">JSON格式</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item label="导出字段">
          <a-checkbox-group v-model:value="exportForm.fields">
            <a-row>
              <a-col :span="8" v-for="field in exportFields" :key="field.key">
                <a-checkbox :value="field.key">{{ field.label }}</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-item>
        
        <a-form-item>
          <a-alert
            :message="`将导出 ${selectedItems.length} 个项目的数据`"
            type="info"
            show-icon
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { 
  DownOutlined,
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined,
  SendOutlined,
  LockOutlined,
  UnlockOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'

interface BatchItem {
  id: number | string
  [key: string]: any
}

interface BatchAction {
  key: string
  label: string
  icon?: any
  disabled?: boolean
  danger?: boolean
}

interface StatusOption {
  value: string
  label: string
  color: string
}

interface ExportField {
  key: string
  label: string
}

interface Props {
  dataSource: BatchItem[]
  selectedItems: BatchItem[]
  operationType: 'user' | 'animal' | 'order' | 'travel'
  statusOptions?: StatusOption[]
  exportFields?: ExportField[]
}

const props = withDefaults(defineProps<Props>(), {
  statusOptions: () => [
    { value: 'active', label: '激活', color: 'green' },
    { value: 'inactive', label: '禁用', color: 'red' },
    { value: 'pending', label: '待审核', color: 'orange' }
  ],
  exportFields: () => [
    { key: 'id', label: 'ID' },
    { key: 'name', label: '名称' },
    { key: 'status', label: '状态' },
    { key: 'created_at', label: '创建时间' }
  ]
})

const emit = defineEmits<{
  'selection-change': [items: BatchItem[]]
  'batch-action': [action: string, items: BatchItem[], params?: any]
}>()

// 模态框状态
const statusModalVisible = ref(false)
const deleteModalVisible = ref(false)
const exportModalVisible = ref(false)

// 加载状态
const statusUpdateLoading = ref(false)
const deleteLoading = ref(false)
const exportLoading = ref(false)

// 表单数据
const statusForm = ref({
  status: '',
  reason: ''
})

const exportForm = ref({
  format: 'csv',
  fields: props.exportFields.map(f => f.key)
})

const deleteConfirm = ref(false)

// 计算属性
const isAllSelected = computed(() => {
  return props.dataSource.length > 0 && props.selectedItems.length === props.dataSource.length
})

const availableActions = computed((): BatchAction[] => {
  const baseActions: BatchAction[] = [
    {
      key: 'update-status',
      label: '更新状态',
      icon: EditOutlined
    },
    {
      key: 'export',
      label: '导出数据',
      icon: DownloadOutlined
    }
  ]

  // 根据操作类型添加特定操作
  switch (props.operationType) {
    case 'user':
      baseActions.push(
        {
          key: 'send-message',
          label: '发送消息',
          icon: SendOutlined
        },
        {
          key: 'lock',
          label: '锁定账户',
          icon: LockOutlined
        },
        {
          key: 'unlock',
          label: '解锁账户',
          icon: UnlockOutlined
        }
      )
      break
    
    case 'animal':
      baseActions.push(
        {
          key: 'batch-approve',
          label: '批量审核',
          icon: EditOutlined
        }
      )
      break
  }

  // 危险操作
  baseActions.push({
    key: 'delete',
    label: '批量删除',
    icon: DeleteOutlined,
    danger: true
  })

  return baseActions
})

/**
 * 全选/取消全选
 */
const handleSelectAll = () => {
  if (isAllSelected.value) {
    emit('selection-change', [])
  } else {
    emit('selection-change', [...props.dataSource])
  }
}

/**
 * 清空选择
 */
const handleClearSelection = () => {
  emit('selection-change', [])
}

/**
 * 处理批量操作
 */
const handleBatchAction = ({ key }: { key: string }) => {
  if (!props.selectedItems.length) {
    message.warning('请先选择要操作的项目')
    return
  }

  switch (key) {
    case 'update-status':
      statusModalVisible.value = true
      statusForm.value = { status: '', reason: '' }
      break
    
    case 'delete':
      deleteModalVisible.value = true
      deleteConfirm.value = false
      break
    
    case 'export':
      exportModalVisible.value = true
      exportForm.value.fields = props.exportFields.map(f => f.key)
      break
    
    default:
      // 直接执行其他操作
      emit('batch-action', key, props.selectedItems)
      break
  }
}

/**
 * 处理状态更新
 */
const handleStatusUpdate = async () => {
  if (!statusForm.value.status) {
    message.error('请选择新状态')
    return
  }

  statusUpdateLoading.value = true
  
  try {
    emit('batch-action', 'update-status', props.selectedItems, {
      status: statusForm.value.status,
      reason: statusForm.value.reason
    })
    
    statusModalVisible.value = false
    message.success(`成功更新 ${props.selectedItems.length} 个项目的状态`)
  } catch (error) {
    message.error('批量状态更新失败')
  } finally {
    statusUpdateLoading.value = false
  }
}

/**
 * 处理批量删除
 */
const handleBatchDelete = async () => {
  if (!deleteConfirm.value) {
    message.error('请确认删除操作')
    return
  }

  deleteLoading.value = true
  
  try {
    emit('batch-action', 'delete', props.selectedItems)
    
    deleteModalVisible.value = false
    message.success(`成功删除 ${props.selectedItems.length} 个项目`)
  } catch (error) {
    message.error('批量删除失败')
  } finally {
    deleteLoading.value = false
  }
}

/**
 * 处理批量导出
 */
const handleBatchExport = async () => {
  if (!exportForm.value.fields.length) {
    message.error('请选择要导出的字段')
    return
  }

  exportLoading.value = true
  
  try {
    emit('batch-action', 'export', props.selectedItems, {
      format: exportForm.value.format,
      fields: exportForm.value.fields
    })
    
    exportModalVisible.value = false
    message.success(`开始导出 ${props.selectedItems.length} 个项目的数据`)
  } catch (error) {
    message.error('批量导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 监听选择变化
watch(() => props.selectedItems, (newItems) => {
  // 可以在这里添加选择变化的逻辑
}, { deep: true })
</script>

<style scoped>
.batch-operations {
  margin-bottom: 16px;
}

.batch-info {
  margin-top: 12px;
}

.batch-info :deep(.ant-alert) {
  border: 1px solid #d9d9d9;
}

.batch-info :deep(.ant-alert-action) {
  margin-left: auto;
}
</style>