<template>
  <div class="search-form-container">
<el-form
      ref="formRef"
      :model="formData"
      :label-width="labelWidth"
      :label-position="labelPosition"
      :inline="inline"
      :size="size"
      :disabled="disabled"
      :class="formClass"
    >
      <!-- 前置插槽 -->
      <slot v-if="prefixSlot" name="prefix"></slot>
      
      <el-row :gutter="gutter" :class="rowClass">
        <template v-for="field in visibleFields" :key="field.field">
          <el-col 
            :span="getColSpan(field, 'span')" 
            :xs="getColSpan(field, 'xs')" 
            :sm="getColSpan(field, 'sm')"
            :md="getColSpan(field, 'md')"
            :lg="getColSpan(field, 'lg')"
            :xl="getColSpan(field, 'xl')"
          >
            <el-form-item 
              :label="field.label" 
              :prop="field.field"
              :rules="getRules(field)"
              :class="field.class"
              :style="field.style"
              :label-width="field.labelWidth"
            >
              <!-- 输入框 -->
              <template v-if="field.type === 'input'">
                <el-input
                  v-model="formData[field.field]"
                  :placeholder="field.placeholder || `请输入${field.label}`"
                  :clearable="field.clearable ?? true"
                  :disabled="field.disabled"
                  :readonly="field.readonly"
                  :show-password="field.type === 'password'"
                  :show-word-limit="field.showWordLimit"
                  :maxlength="field.maxlength"
                  :style="{ width: getFieldWidth(field) }"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 文本域 -->
              <template v-else-if="field.type === 'textarea'">
                <el-input
                  v-model="formData[field.field]"
                  type="textarea"
                  :placeholder="field.placeholder || `请输入${field.label}`"
                  :clearable="field.clearable ?? true"
                  :disabled="field.disabled"
                  :readonly="field.readonly"
                  :rows="field.minRows || 3"
                  :max-rows="field.maxRows"
                  :show-word-limit="field.showWordLimit"
                  :maxlength="field.maxlength"
                  :style="{ width: getFieldWidth(field) }"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 数字输入框 -->
              <template v-else-if="field.type === 'number'">
                <el-input-number
                  v-model="formData[field.field]"
                  :placeholder="field.placeholder || `请输入${field.label}`"
                  :disabled="field.disabled"
                  :readonly="field.readonly"
                  :step="field.step"
                  :precision="field.precision"
                  :min="field.min"
                  :max="field.max"
                  :style="{ width: getFieldWidth(field) }"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 普通下拉框（单选） -->
              <template v-else-if="field.type === 'select'">
                <el-select
                  v-model="formData[field.field]"
                  :placeholder="field.placeholder || `请选择${field.label}`"
                  :clearable="field.clearable ?? true"
                  :disabled="field.disabled"
                  :style="{ width: getFieldWidth(field) }"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                >
                  <el-option
                    v-for="option in getOptions(field)"
                    :key="getOptionValue(option, field)"
                    :label="getOptionLabel(option, field)"
                    :value="getOptionValue(option, field)"
                    :disabled="option.disabled"
                  />
                </el-select>
              </template>
              
              <!-- 多选下拉框 -->
              <template v-else-if="field.type === 'multi-select'">
                <el-select
                  v-model="formData[field.field]"
                  :placeholder="field.placeholder || `请选择${field.label}`"
                  :clearable="field.clearable ?? true"
                  :multiple="true"
                  :collapse-tags="true"
                  :max-collapse-tags="1"
                  :disabled="field.disabled"
                  :style="{ width: getFieldWidth(field) }"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                >
                  <el-option
                    v-for="option in getOptions(field)"
                    :key="getOptionValue(option, field)"
                    :label="getOptionLabel(option, field)"
                    :value="getOptionValue(option, field)"
                    :disabled="option.disabled"
                  />
                </el-select>
              </template>
              
              <!-- 远程搜索下拉框（单选） -->
              <template v-else-if="field.type === 'remote-select'">
                <RemoteSelect
                  v-model="formData[field.field]"
                  :config="field.remoteConfig!"
                  :placeholder="field.placeholder || `请搜索选择${field.label}`"
                  :clearable="field.clearable ?? true"
                  :disabled="field.disabled"
                  :style="{ width: getFieldWidth(field) }"
                  :option-label="field.optionLabel"
                  :option-value="field.optionValue"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 远程搜索下拉框（多选） -->
              <template v-else-if="field.type === 'remote-multi-select'">
                <RemoteMultiSelect
                  v-model="formData[field.field]"
                  :config="field.remoteConfig!"
                  :placeholder="field.placeholder || `请搜索选择${field.label}`"
                  :clearable="field.clearable ?? true"
                  :disabled="field.disabled"
                  :style="{ width: getFieldWidth(field) }"
                  :option-label="field.optionLabel"
                  :option-value="field.optionValue"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 日期选择器 -->
              <template v-else-if="field.type === 'date'">
                <el-date-picker
                  v-model="formData[field.field]"
                  type="date"
                  :placeholder="field.placeholder || `请选择${field.label}`"
                  :clearable="field.clearable ?? true"
                  :disabled="field.disabled"
                  :readonly="field.readonly"
                  :format="field.dateFormat"
                  :value-format="field.dateFormat"
                  :style="{ width: getFieldWidth(field) }"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 日期范围选择器 -->
              <template v-else-if="field.type === 'daterange'">
                <el-date-picker
                  v-model="formData[field.field]"
                  type="daterange"
                  :range-separator="field.rangeSeparator || '至'"
                  :start-placeholder="field.startPlaceholder || '开始日期'"
                  :end-placeholder="field.endPlaceholder || '结束日期'"
                  :clearable="field.clearable ?? true"
                  :disabled="field.disabled"
                  :readonly="field.readonly"
                  :format="field.dateFormat"
                  :value-format="field.dateFormat"
                  :style="{ width: getFieldWidth(field) }"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 日期时间选择器 -->
              <template v-else-if="field.type === 'datetime'">
                <el-date-picker
                  v-model="formData[field.field]"
                  type="datetime"
                  :placeholder="field.placeholder || `请选择${field.label}`"
                  :clearable="field.clearable ?? true"
                  :disabled="field.disabled"
                  :readonly="field.readonly"
                  :format="field.dateFormat"
                  :value-format="field.dateFormat"
                  :style="{ width: getFieldWidth(field) }"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 日期时间范围选择器 -->
              <template v-else-if="field.type === 'datetimerange'">
                <el-date-picker
                  v-model="formData[field.field]"
                  type="datetimerange"
                  :range-separator="field.rangeSeparator || '至'"
                  :start-placeholder="field.startPlaceholder || '开始时间'"
                  :end-placeholder="field.endPlaceholder || '结束时间'"
                  :clearable="field.clearable ?? true"
                  :disabled="field.disabled"
                  :readonly="field.readonly"
                  :format="field.dateFormat"
                  :value-format="field.dateFormat"
                  :style="{ width: getFieldWidth(field) }"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 单选框 -->
              <template v-else-if="field.type === 'radio'">
                <el-radio-group
                  v-model="formData[field.field]"
                  :disabled="field.disabled"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                >
                  <el-radio
                    v-for="option in getOptions(field)"
                    :key="getOptionValue(option, field)"
                    :label="getOptionValue(option, field)"
                    :disabled="option.disabled"
                  >
                    {{ getOptionLabel(option, field) }}
                  </el-radio>
                </el-radio-group>
              </template>
              
              <!-- 复选框 -->
              <template v-else-if="field.type === 'checkbox'">
                <el-checkbox-group
                  v-model="formData[field.field]"
                  :disabled="field.disabled"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                >
                  <el-checkbox
                    v-for="option in getOptions(field)"
                    :key="getOptionValue(option, field)"
                    :label="getOptionValue(option, field)"
                    :disabled="option.disabled"
                  >
                    {{ getOptionLabel(option, field) }}
                  </el-checkbox>
                </el-checkbox-group>
              </template>
              
              <!-- 开关 -->
              <template v-else-if="field.type === 'switch'">
                <el-switch
                  v-model="formData[field.field]"
                  :disabled="field.disabled"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 级联选择器 -->
              <template v-else-if="field.type === 'cascader'">
                <el-cascader
                  v-model="formData[field.field]"
                  :options="getOptions(field)"
                  :placeholder="field.placeholder || `请选择${field.label}`"
                  :clearable="field.clearable ?? true"
                  :disabled="field.disabled"
                  :style="{ width: getFieldWidth(field) }"
                  @change="handleChange(field.field, $event)"
                  v-bind="field.props"
                />
              </template>
              
              <!-- 自定义组件 -->
              <template v-else-if="field.type === 'custom'">
                <component
                  :is="field.component"
                  v-model="formData[field.field]"
                  v-bind="field.props"
                  @change="handleChange(field.field, $event)"
                >
                  <template v-for="(slotContent, slotName) in field.slots" #[slotName]>
                    <component :is="slotContent" />
                  </template>
                </component>
              </template>
              
              <!-- 其他类型可以在这里扩展 -->
            </el-form-item>
          </el-col>
        </template>
      </el-row>
      
      <!-- 后置插槽 -->
      <slot v-if="suffixSlot" name="suffix"></slot>
      
      <!-- 操作按钮 -->
      <el-form-item v-if="showSearch || showReset" class="form-actions">
        <el-button 
          v-if="showSearch" 
          type="primary" 
          :loading="searchLoading"
          @click="handleSearch"
        >
          {{ searchText }}
        </el-button>
        <el-button 
          v-if="showReset" 
          @click="handleReset"
        >
          {{ resetText }}
        </el-button>
      </el-form-item>
      
      <!-- 额外插槽 -->
      <slot v-if="extraSlot" name="extra"></slot>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, toRefs } from 'vue'
import type { FormInstance } from 'element-plus'
import RemoteSelect from './RemoteSelect.vue'
import RemoteMultiSelect from './RemoteMultiSelect.vue'
import type {
  SearchFormProps,
  SearchFormEmits,
  FormField,
  FormOption
} from '@/types/search-form'

const props = withDefaults(defineProps<SearchFormProps>(), {
  labelWidth: '150px',
  labelPosition: 'right',
  inline: false,
  size: 'default',
  disabled: false,
  showReset: false,
  showSearch: false,
  resetText: '重置',
  searchText: '搜索',
  gutter: 20,
  rowClass: '',
  formClass: '',
  prefixSlot: false,
  suffixSlot: false,
  extraSlot: false
})

const emit = defineEmits<SearchFormEmits>()

// 表单引用
const formRef = ref<FormInstance>()
const searchLoading = ref(false)

// 表单数据
const formData = reactive<Record<string, any>>({})

// 初始化表单数据
const initFormData = () => {
  // 设置默认值
  props.fields.forEach(field => {
    if (field.field in props.modelValue) {
      formData[field.field] = props.modelValue[field.field]
    } else if (field.defaultValue !== undefined) {
      formData[field.field] = field.defaultValue
    } else {
      // 根据类型设置默认值
      switch (field.type) {
        case 'input':
        case 'textarea':
        case 'password':
          formData[field.field] = ''
          break
        case 'select':
        case 'radio':
          formData[field.field] = ''
          break
        case 'multi-select':
        case 'checkbox':
        case 'remote-multi-select':
          formData[field.field] = []
          break
        case 'switch':
          formData[field.field] = false
          break
        case 'number':
          formData[field.field] = null
          break
        case 'date':
        case 'datetime':
          formData[field.field] = ''
          break
        case 'daterange':
        case 'datetimerange':
          formData[field.field] = []
          break
        case 'cascader':
          formData[field.field] = []
          break
        default:
          formData[field.field] = null
      }
    }
  })
}

// 计算可见的字段
const visibleFields = computed(() => {
  return props.fields.filter(field => !field.hidden)
})

// 获取字段宽度
const getFieldWidth = (field: FormField) => {
  if (field.width) {
    return typeof field.width === 'number' ? `${field.width}px` : field.width
  }
  return '100%'
}

// 获取栅格跨度
const getColSpan = (field: FormField, type: 'span' | 'xs' | 'sm' | 'md' | 'lg' | 'xl') => {
  const userColSpan = field.colSpan || 6 // 默认6（大屏4列）
  
  switch (type) {
    case 'xs': // 超小屏幕（手机）
      return 24 // 1列
    case 'sm': // 小屏幕（平板）
      return userColSpan * 2 // 转换为栅格跨度
    case 'md': // 中等屏幕
      return userColSpan
    case 'lg': // 大屏幕
      return userColSpan
    case 'xl': // 超大屏幕
      return userColSpan
    case 'span': // 默认
      return userColSpan
  }
}

// 获取选项列表
const getOptions = (field: FormField): FormOption[] => {
  return field.options || []
}

// 获取选项标签
const getOptionLabel = (option: FormOption, field: FormField) => {
  if (field.optionLabel && option[field.optionLabel]) {
    return option[field.optionLabel]
  }
  return option.label
}

// 获取选项值
const getOptionValue = (option: FormOption, field: FormField) => {
  if (field.optionValue && option[field.optionValue]) {
    return option[field.optionValue]
  }
  return option.value
}

// 获取校验规则
const getRules = (field: FormField) => {
  const rules = field.rules || []
  
  // 自动添加必填校验
  if (field.rules?.some(rule => rule.required)) {
    return rules
  }
  
  // 如果有required属性但没有规则，自动创建
  if (field.props?.required) {
    return [
      {
        required: true,
        message: `${field.label}不能为空`,
        trigger: field.type.includes('select') ? 'change' : 'blur'
      },
      ...rules
    ]
  }
  
  return rules
}

// 处理字段变化
const handleChange = (field: string, value: any) => {
  emit('change', field, value)
  emit('update:modelValue', { ...formData })
}

// 处理搜索
const handleSearch = async () => {
  if (!formRef.value) return
  
  try {
    searchLoading.value = true
    
    // 执行表单验证
    const isValid = await formRef.value.validate()
    if (!isValid) return
    
    // 执行前置钩子
    if (props.beforeSearch) {
      const canProceed = await props.beforeSearch(formData)
      if (!canProceed) return
    }
    
    // 触发搜索事件
    emit('search', formData)
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    searchLoading.value = false
  }
}

// 处理重置
const handleReset = async () => {
  if (!formRef.value) return
  
  // 执行前置钩子
  if (props.beforeReset) {
    const canProceed = await props.beforeReset()
    if (!canProceed) return
  }
  
  // 重置表单
  formRef.value.resetFields()
  
  // 重置为默认值
  initFormData()
  
  // 触发重置事件
  emit('reset', formData)
  emit('update:modelValue', { ...formData })
}

// 监听外部modelValue变化
watch(() => props.modelValue, (newVal) => {
  Object.keys(formData).forEach(key => {
    if (key in newVal) {
      formData[key] = newVal[key]
    }
  })
}, { deep: true })

// 监听字段配置变化
watch(() => props.fields, () => {
  initFormData()
}, { deep: true })

// 暴露方法给父组件
defineExpose({
  validate: () => formRef.value?.validate(),
  resetFields: () => {
    formRef.value?.resetFields()
    initFormData()
  },
  clearValidate: () => formRef.value?.clearValidate(),
  getFormData: () => ({ ...formData }),
  getFormRef: () => formRef.value
})

// 初始化
initFormData()
</script>
<style scoped lang="scss">
.search-form-container {
  width: 100%;
  
  .form-actions {
    margin-bottom: 0;
    margin-top: 20px;
    
    .el-button + .el-button {
      margin-left: 10px;
    }
  }
}

// 统一所有表单项的宽度和高度
:deep(.el-form) {
  &.el-form--label-top {
    .el-form-item {
      margin-bottom: 24px;
      
      .el-form-item__label {
        display: block;
        text-align: left;
        margin-bottom: 8px;
        padding-bottom: 0;
        line-height: 1.4;
        font-weight: 500;
        color: #606266;
        font-size: 14px;
        height: 20px;
      }
      
      .el-form-item__content {
        margin-left: 0 !important;
        height: 40px; // 固定内容高度
        width: 100%; // 确保内容区域宽度100%
        
        // 基础容器样式
        > * {
          display: block !important;
          width: 100% !important;
          box-sizing: border-box !important;
        }
        
        // 日期选择器 - 修复日期区间宽度
        .el-date-editor {
          &.el-range-editor {
            // 日期区间选择器的特殊处理
            height: 40px !important;
            width: 100% !important;
            line-height: 38px !important;
            display: flex !important;
            align-items: center !important;
            padding: 0 !important;
            
            // 修复内部flex布局
            .el-range-input {
              height: 38px !important;
              line-height: 38px !important;
              flex: 1 !important; // 让两个输入框平分剩余空间
              min-width: 0 !important; // 防止内容溢出
              padding: 0 8px !important;
              font-size: 14px !important;
              border: none !important;
              background: transparent !important;
              outline: none !important;
              
              // 修复placeholder样式
              &::placeholder {
                color: var(--el-text-color-placeholder);
                font-size: 14px;
              }
            }
            
            // 分隔符
            .el-range-separator {
              height: 38px !important;
              line-height: 38px !important;
              padding: 0 4px !important;
              font-size: 14px !important;
              color: var(--el-text-color-placeholder);
              flex: none !important;
              width: auto !important;
              min-width: 20px !important;
            }
            
            // 关闭图标
            .el-range__close-icon {
              height: 38px !important;
              line-height: 38px !important;
              flex: none !important;
              width: 30px !important;
              display: flex !important;
              align-items: center !important;
              justify-content: center !important;
              
              .el-icon {
                font-size: 14px !important;
              }
            }
            
            // 日历图标
            .el-range__icon {
              height: 38px !important;
              line-height: 38px !important;
              flex: none !important;
              width: 30px !important;
              display: flex !important;
              align-items: center !important;
              justify-content: center !important;
              
              .el-icon {
                font-size: 14px !important;
              }
            }
            
            // 悬停和聚焦状态
            &:hover,
            &:focus-within {
              .el-range-input {
                background: transparent !important;
              }
            }
            
            // 禁用的日期区间
            &.is-disabled {
              .el-range-input {
                color: var(--el-disabled-text-color) !important;
                background: var(--el-disabled-bg-color) !important;
              }
            }
          }
          
          // 单个日期选择器
          &:not(.el-range-editor) {
            height: 40px;
            width: 100% !important;
            
            .el-input__wrapper {
              height: 40px;
              width: 100%;
              padding: 1px 30px 1px 11px; // 为图标留出空间
              box-sizing: border-box;
              
              .el-input__inner {
                height: 38px;
                line-height: 38px;
                width: 100%;
                padding-right: 20px; // 为图标留出空间
              }
            }
          }
          
          // 日期时间选择器
          &.el-date-editor--datetime {
            .el-input__wrapper {
              padding-right: 30px;
            }
          }
        }
        
        // 其他组件样式保持不变...
        // 输入框
        .el-input {
          height: 40px;
          width: 100%;
          
          .el-input__wrapper {
            height: 40px;
            width: 100%;
            padding: 1px 11px;
            border-radius: 4px;
            box-sizing: border-box;
            
            .el-input__inner {
              height: 38px;
              line-height: 38px;
              width: 100%;
            }
          }
        }
        
        // 下拉选择框（单选）
        .el-select:not(.is-multiple) {
          height: 40px;
          width: 100%;
          
          .el-select__wrapper {
            height: 40px;
            width: 100%;
            padding: 1px 30px 1px 11px; // 为下拉箭头留出空间
            border-radius: 4px;
            box-sizing: border-box;
            
            .el-select__placeholder,
            .el-select__selected-item {
              line-height: 38px;
              width: 100%;
              padding-right: 20px; // 为下拉箭头留出空间
            }
            
            // 下拉箭头
            .el-select__suffix {
              right: 8px;
            }
          }
        }
        
        // 下拉选择框（多选）
        .el-select.is-multiple {
          height: auto;
          min-height: 40px;
          width: 100%;
          
          .el-select__wrapper {
            min-height: 40px;
            width: 100%;
            padding: 3px 30px 3px 11px;
            border-radius: 4px;
            box-sizing: border-box;
            
            .el-select__tags-wrapper {
              min-height: 32px;
              line-height: 32px;
              width: 100%;
            }
          }
        }
        
        // 数字输入框
        .el-input-number {
          height: 40px;
          width: 100% !important;
          
          .el-input {
            height: 40px;
            width: 100%;
            
            .el-input__wrapper {
              height: 40px;
              width: 100%;
              padding: 1px 40px 1px 11px; // 左右都为按钮留出空间
              box-sizing: border-box;
              
              .el-input__inner {
                height: 38px;
                line-height: 38px;
                width: 100%;
                text-align: left;
              }
            }
          }
        }
        
        // 确保远程搜索组件继承样式
        .remote-select,
        .remote-multi-select {
          width: 100% !important;
          
          .el-select {
            width: 100% !important;
          }
        }
      }
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  :deep(.el-form) {
    &.el-form--label-top {
      .el-form-item {
        margin-bottom: 20px;
        
        .el-form-item__content {
          height: 38px;
          
          .el-date-editor {
            &.el-range-editor {
              height: 38px !important;
              
              .el-range-input {
                height: 36px !important;
                line-height: 36px !important;
                padding: 0 6px !important;
                font-size: 13px !important;
              }
              
              .el-range-separator {
                height: 36px !important;
                line-height: 36px !important;
                padding: 0 2px !important;
                font-size: 13px !important;
              }
              
              .el-range__close-icon,
              .el-range__icon {
                height: 36px !important;
                line-height: 36px !important;
                width: 26px !important;
              }
            }
          }
          
          .el-input,
          .el-select,
          .el-input-number {
            height: 38px;
            
            .el-input__wrapper,
            .el-select__wrapper {
              height: 38px;
              padding: 1px 8px;
              
              .el-input__inner,
              .el-select__placeholder,
              .el-select__selected-item {
                height: 36px;
                line-height: 36px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
