<template>
  <div class="commonPage-container">
    <!-- 条件查询区 -->
    <el-card class="cardStyle" v-if="showSearchForm">
      <el-row>
        <!-- 查询条件插槽 -->
        <div ref="searchFormRef" class="search-form-container" :class="{ expanded: isExpanded }">
          <slot name="searchForm"></slot>
        </div>

        <!-- 更多/收起按钮区域 -->
        <el-col :span="24" v-if="hasMoreCondition">
          <div class="moreBtn">
            <el-button v-if="!isExpanded" type="primary" link @click="toggleExpand">
              更多<el-icon><Bottom /></el-icon>
            </el-button>
            <el-button v-else type="primary" link @click="toggleExpand">
              收起<el-icon><Top /></el-icon>
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="cardStyle">
      <el-row>
        <!-- 按钮区域 -->
        <el-col :span="24" class="operationBtn">
          <div class="operationLeft">
            <!-- 左侧按钮 -->
            <template v-for="btn in leftButtons" :key="btn.key || btn.label">
              <el-button
                :type="btn.type || 'primary'"
                :icon="btn.icon"
                :size="btn.size || 'default'"
                @click="handleButtonClick(btn)"
                :disabled="btn.disabled"
                :loading="btn.loading"
                :class="btn.customClass"
              >
                {{ btn.label }}
              </el-button>
            </template>

            <!-- 左侧插槽 -->
            <slot name="leftButtons"></slot>
          </div>

          <div class="operationRight">
            <!-- 右侧按钮 -->
            <template v-for="btn in rightButtons" :key="btn.key || btn.label">
              <el-button
                :type="btn.type || 'primary'"
                :icon="btn.icon"
                :size="btn.size || 'default'"
                @click="handleButtonClick(btn)"
                :disabled="btn.disabled"
                :loading="btn.loading"
                :class="btn.customClass"
              >
                {{ btn.label }}
              </el-button>
            </template>

            <!-- 右侧插槽 -->
            <slot name="rightButtons"></slot>
          </div>
        </el-col>

        <!-- 表格插槽 -->
        <el-col :span="24">
          <slot name="table"></slot>
        </el-col>

        <!-- 分页区域 -->
        <el-col :span="24" v-if="showPagination">
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="pageSizes"
              :layout="paginationLayout"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted } from 'vue'

// 按钮类型定义
export interface OperationButton {
  // 按钮唯一标识（用于匹配默认按钮配置）
  key?: string
  // 显示文本（如果提供了key，会自动使用默认文本）
  label?: string
  // 按钮类型
  type?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'text'
  // 图标名称
  icon?: string
  // 按钮尺寸
  size?: 'large' | 'default' | 'small'
  // 显示位置
  direction?: 'left' | 'right'
  // 是否禁用
  disabled?: boolean
  // 加载状态
  loading?: boolean
  // 是否显示（默认显示）
  visible?: boolean
  // 点击事件回调函数
  click?: () => void | Promise<void>
  // 权限标识
  permission?: string
  // 自定义样式类
  customClass?: string
}

// 组件 Props
interface Props {
  // 操作按钮列表
  operationBtnList?: OperationButton[]
  // 是否显示查询表单
  showSearchForm?: boolean
  // 是否显示分页
  showPagination?: boolean
  // 总条数
  total?: number
  // 当前页码
  currentPage?: number
  // 每页显示条数
  pageSize?: number
  // 每页条数选项
  pageSizes?: number[]
  // 分页布局
  paginationLayout?: string
  // 默认显示的查询条件数量
  defaultVisibleConditions?: number
  // 是否显示默认按钮
  showDefaultButtons?: boolean
  // 需要显示的默认按钮
  visibleDefaultButtons?: ('add' | 'import' | 'export' | 'reset' | 'query')[]
}

const props = withDefaults(defineProps<Props>(), {
  operationBtnList: () => [],
  showSearchForm: true,
  showPagination: false,
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: () => [10, 20, 50, 100],
  paginationLayout: 'total, sizes, prev, pager, next, jumper',
  defaultVisibleConditions: 8,
  showDefaultButtons: true,
  visibleDefaultButtons: () => ['add', 'import', 'export', 'reset', 'query']
})

const emit = defineEmits<{
  // 分页事件
  'size-change': [size: number]
  'current-change': [page: number]
  // 按钮点击事件
  'btn-click': [btn: OperationButton]
  // 搜索展开/收起
  'search-toggle': [expanded: boolean]
  // 默认按钮事件（为方便使用保留）
  add: []
  import: []
  export: []
  reset: []
  query: []
}>()

// 响应式数据
const isExpanded = ref(false)
const hasMoreCondition = ref(false)
const searchFormRef = ref<HTMLElement | null>(null)
const currentPage = ref(props.currentPage)
const pageSize = ref(props.pageSize)

// 默认按钮配置（作为基础配置）
const defaultButtonConfigs = {
  add: {
    key: 'add',
    label: '新增',
    icon: 'Plus',
    type: 'primary' as const,
    direction: 'left' as const,
    size: 'default' as const
  },
  import: {
    key: 'import',
    label: '导入',
    icon: 'Upload',
    type: 'primary' as const,
    direction: 'left' as const,
    size: 'default' as const
  },
  export: {
    key: 'export',
    label: '导出',
    icon: 'Download',
    type: 'success' as const,
    direction: 'right' as const,
    size: 'default' as const
  },
  reset: {
    key: 'reset',
    label: '重置',
    icon: 'Refresh',
    type: 'info' as const,
    direction: 'right' as const,
    size: 'default' as const
  },
  query: {
    key: 'query',
    label: '查询',
    icon: 'Search',
    type: 'primary' as const,
    direction: 'right' as const,
    size: 'default' as const
  }
}

// 计算最终按钮配置
const computedButtons = computed(() => {
  const result: OperationButton[] = []

  // 1. 添加默认按钮（如果开启）
  if (props.showDefaultButtons) {
    props.visibleDefaultButtons.forEach(key => {
      if (defaultButtonConfigs[key]) {
        const defaultBtn = { ...defaultButtonConfigs[key] }
        // 查找是否有自定义配置覆盖
        const customConfig = props.operationBtnList.find(btn => btn.key === key)
        if (customConfig) {
          // 合并配置：自定义配置覆盖默认配置
          Object.assign(defaultBtn, customConfig)
        }
        result.push(defaultBtn)
      }
    })
  }

  // 2. 添加没有匹配到默认按钮的自定义按钮
  props.operationBtnList.forEach(customBtn => {
    // 如果这个按钮已经有默认配置了，就跳过（已经在上面处理了）
    const isDefaultBtn = customBtn.key && props.visibleDefaultButtons.includes(customBtn.key as any)
    const alreadyAdded = result.some(btn => btn.key === customBtn.key)

    if (!isDefaultBtn && !alreadyAdded) {
      result.push(customBtn)
    }
  })

  return result
})

// 计算左侧按钮
const leftButtons = computed(() => {
  return computedButtons.value.filter(
    btn =>
      (btn.direction === 'left' || (!btn.direction && props.showDefaultButtons)) &&
      btn.visible !== false
  )
})

// 计算右侧按钮
const rightButtons = computed(() => {
  return computedButtons.value.filter(btn => btn.direction === 'right' && btn.visible !== false)
})

// 方法
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
  emit('search-toggle', isExpanded.value)
  checkConditions()
}

const checkConditions = () => {
  if (!searchFormRef.value || !props.showSearchForm) return

  nextTick(() => {
    const formItems = Array.from(
      searchFormRef.value!.querySelectorAll('.el-form-item, .el-button-group')
    )

    hasMoreCondition.value = formItems.length > props.defaultVisibleConditions

    if (!isExpanded.value && hasMoreCondition.value) {
      formItems.forEach((item, index) => {
        if (index >= props.defaultVisibleConditions) {
          ;(item as HTMLElement).style.display = 'none'
        } else {
          ;(item as HTMLElement).style.display = ''
        }
      })
    } else {
      formItems.forEach(item => {
        ;(item as HTMLElement).style.display = ''
      })
    }
  })
}

// 处理按钮点击
const handleButtonClick = async (btn: OperationButton) => {
  // 触发通用按钮点击事件
  emit('btn-click', btn)

  // 触发默认按钮的特定事件（保持向后兼容）
  if (btn.key) {
    switch (btn.key) {
      case 'add':
        emit('add')
        break
      case 'import':
        emit('import')
        break
      case 'export':
        emit('export')
        break
      case 'reset':
        emit('reset')
        break
      case 'query':
        emit('query')
        break
    }
  }

  // 执行父组件传入的click函数
  if (btn.click && typeof btn.click === 'function') {
    try {
      const result = btn.click()
      // 如果是Promise，等待执行完成
      if (result instanceof Promise) {
        await result
      }
    } catch (error) {
      console.error('按钮点击事件执行失败:', error)
    }
  }
}

// 分页事件处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  emit('size-change', size)
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  emit('current-change', page)
}

// 更新按钮状态的方法
const updateButtonState = (key: string, updates: Partial<OperationButton>) => {
  // 这个方法可以在父组件中调用
  console.log(`更新按钮 ${key} 状态:`, updates)
}

// 暴露给父组件的方法
defineExpose({
  checkConditions,
  toggleExpand,
  updateButtonState,
  refresh: () => {
    checkConditions()
  }
})

// 监听器
watch(isExpanded, checkConditions)

watch(
  () => props.currentPage,
  val => {
    currentPage.value = val
  }
)

watch(
  () => props.pageSize,
  val => {
    pageSize.value = val
  }
)

watch(
  () => props.operationBtnList,
  () => {
    nextTick(() => {
      checkConditions()
    })
  },
  { deep: true }
)

// 生命周期
onMounted(() => {
  if (props.showSearchForm) {
    setTimeout(() => {
      checkConditions()
    }, 100)
  }
})
</script>

<style lang="scss" scoped>
.commonPage-container {
  width: 100%;
  box-sizing: border-box;
}

.cardStyle {
  margin-bottom: 10px;
  border: none !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.moreBtn {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.operationBtn {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}

.operationLeft,
.operationRight {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
}

/* 搜索表单容器样式 */
.search-form-container {
  width: 100%;
  transition: all 0.3s ease;

  &.expanded {
    .el-form-item {
      display: flex !important;
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .operationBtn {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .operationLeft,
  .operationRight {
    width: 100%;
    justify-content: center;
  }

  .cardStyle {
    margin-bottom: 8px;
  }

  .pagination-container {
    justify-content: center;
  }
}
</style>
