<script>
const XS = 0
const SM = 768
const MD = 992
const LG = 1200
const XL = 1920

export default {
  name: 'PageWrapperSearch',
  emits: ['update:advanced', 'search', 'reset'],
  components: {
    ElRow: () => import('element-ui/lib/row'),
    ElCol: () => import('element-ui/lib/col'),
    ElForm: () => import('element-ui/lib/form'),
    ElFormItem: () => import('element-ui/lib/form-item'),
    ElIcon: () => import('element-ui/lib/icon'),
    ElButton: () => import('element-ui/lib/button')
  },
  props: {
    xs: {
      type: Number,
      default: 24
    },
    sm: {
      type: Number,
      default: 24
    },
    md: {
      type: Number,
      default: 12
    },
    lg: {
      type: Number,
      default: 8
    },
    xl: {
      type: Number,
      default: 6
    },
    labelWidth: [Number, String]
  },
  data() {
    return {
      observer: null,
      ElFormRef: null,
      max: 0,
      isAdvanced: true,
      isFold: true, // 默认折叠状态
      labelWidthValue: '',
      inputEvents: [],
      screenWidth: 1920
    }
  },
  computed: {
    gutter() {
      return (24 / this.max % 24) || 0
    },
    // 计算每行最多能显示的列数
    maxItemsPerRow() {
      return Math.floor(24 / this.currentColWidth)
    },
    // 获取当前屏幕尺寸对应的列宽
    currentColWidth() {
      if (this.screenWidth >= XL) return this.xl
      if (this.screenWidth >= LG) return this.lg
      if (this.screenWidth >= MD) return this.md
      if (this.screenWidth >= SM) return this.sm
      return this.xs
    },
    // 是否显示折叠按钮
    shouldShowFoldButton() {
      const formItems = this.extractFormItems(this.$slots.default || [])
      return formItems.length > this.maxItemsPerRow - 1
    },
    // 折叠状态下每行最多显示的表单项数量（包括按钮列）
    maxVisibleItemsWhenFold() {
      return Math.max(1, this.maxItemsPerRow - 1) // 减去按钮列
    },
    // 是否需要将按钮放在单独一行
    shouldWrapButtons() {
      return !this.isFold && this.shouldShowFoldButton
    }
  },
  mounted() {
    this.screenWidth = document.documentElement.clientWidth
    this.observer = new ResizeObserver((entries) => {
      if (entries[0].contentRect.width > 0) {
        this.initSize()
      }
    })
    if (this.ElFormRef?.$el) {
      this.observer.observe(this.ElFormRef.$el)
    }
    this.initSize()
    
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    if (this.observer) {
      this.observer.disconnect()
      if (this.ElFormRef?.$el) {
        this.observer.unobserve(this.ElFormRef.$el)
      }
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    //  resetFields() {
    //   if (this.ElFormRef && typeof this.ElFormRef.resetFields === 'function') {
    //     this.ElFormRef.resetFields()
    //   }
    // },
    handleResize() {
      this.screenWidth = document.documentElement.clientWidth
      this.initSize()
    },
    initSize() {
      this.max = 24 / this.currentColWidth
      this.resetLabelWidth()
    },
    resetLabelWidth() {
      this.labelWidthValue = ''
      this.$nextTick().then(() => {
        const formItemLabels = this.ElFormRef?.$el ? this.ElFormRef.$el.querySelectorAll('.el-form-item__label') : []
        const arr = []
        formItemLabels.forEach(item => {
          arr.push(item.offsetWidth)
        })
        const max = Math.max.apply(null, arr)
        this.labelWidthValue = String(max + 16)
      })
    },
    toggleFold() {
      this.isFold = !this.isFold
      this.labelWidthValue = ''
      this.resetLabelWidth()
    },
    // 判断是否应该隐藏表单项
    shouldHideItem(index) {
      if (!this.isFold) return false
      return index >= this.maxVisibleItemsWhenFold
    },
    // 更可靠的 el-form-item 检测方法
    isFormItemNode(node) {
      if (!node) return false
      
      if (node.componentOptions && node.componentOptions.tag === 'el-form-item') {
        return true
      }
      
      if (node.data && node.data.attrs) {
        const attrs = node.data.attrs
        if (attrs.label || attrs.prop) {
          return true
        }
      }
      
      if (node.data && node.data.staticClass) {
        if (node.data.staticClass.includes('el-form-item')) {
          return true
        }
      }
      
      return false
    },
    // 递归查找所有表单项
    extractFormItems(nodes, result = []) {
      if (!nodes || !Array.isArray(nodes)) return result
      
      nodes.forEach(node => {
        if (!node) return
        
        if (this.isFormItemNode(node)) {
          result.push(node)
        } else if (node.children) {
          this.extractFormItems(node.children, result)
        } else if (node.componentOptions && node.componentOptions.children) {
          this.extractFormItems(node.componentOptions.children, result)
        }
      })
      
      return result
    }
  },
  render() {
    // 提取所有 el-form-item
    const defaultSlots = this.$slots.default || []
    const formItems = this.extractFormItems(defaultSlots)

    // 渲染表单项
    const formItemCols = formItems.map((item, index) => {
      const isHidden = this.shouldHideItem(index)
      
      return (
        <el-col
          class={{ 'hidden': isHidden }}
          key={`formitem-${index}`}
          xs={24}
          sm={this.sm}
          md={this.md}
          lg={this.lg}
          xl={this.xl}
        >
          {item}
        </el-col>
      )
    })

    // 渲染按钮
    const buttons = (
      <div class="buttons-space">
        <el-button
          plain={true}
          on-click={() => {
            this.$emit('reset', this.ElFormRef)
          }}
        >
          重置
        </el-button>
        <el-button
          type="primary"
          on-click={() => {
            this.$emit('search')
          }}
        >
          查询
        </el-button>
        {this.shouldShowFoldButton ? (
          <div
            class="advanced"
            on-click={this.toggleFold}
          >
            <span>{this.isFold ? '展开' : '收起'}</span>
            <i class={`el-icon-arrow-${this.isFold ? 'down' : 'up'} advanced-icon`}></i>
          </div>
        ) : null}
      </div>
    )

    // 按钮列
    const buttonsCol = (
      <el-col
        class="ElColButtons"
        xs={24}
        sm={this.sm}
        md={this.md}
        lg={this.lg}
        xl={this.xl}
        style={this.shouldWrapButtons ? 'margin-top: 18px;' : ''}
      >
        {this.$slots.buttons ? this.$slots.buttons : buttons}
      </el-col>
    )

    return (
      <el-form
        {...{ attrs: this.$attrs }}
        label-width={this.labelWidth || this.labelWidthValue}
        label-position="right"
        ref="ElFormRef"
        class="page-wrapper-search"
      >
        {/* 第一行：表单项 */}
        <el-row gutter={this.gutter}>
          {formItemCols}
          {/* 折叠状态：按钮列与表单项在同一行 */}
          {!this.shouldWrapButtons && buttonsCol}
        </el-row>
        
        {/* 展开状态：按钮列在第二行 */}
        {this.shouldWrapButtons && (
          <el-row gutter={this.gutter} style="margin-top: 0;display: flex;justify-content: flex-end;">
            {buttonsCol}
          </el-row>
        )}
      </el-form>
    )
  }
}
</script>

<style lang="scss" scoped>
.page-wrapper-search {
  position: relative;
  background: white;
  padding: 16px;

}

:deep(.el-form-item) {
  margin-bottom: 18px;
  
  .el-form-item__label {
    color: #606266;
    font-weight: normal;
  }
  
  .el-form-item__content {
    > div {
      width: 100%;
    }
    
    .el-input,
    .el-select,
    .el-date-editor {
      width: 100%;
      
      .el-input__inner {
        border-radius: 4px;
        border: 1px solid #DCDFE6;
        
        &:focus {
          border-color: #356CEF;
        }
      }
    }
    
    .el-select .el-input__inner {
      cursor: pointer;
    }
  }
}

.advanced {
  display: inline-flex;
  align-items: center;
  color: #356CEF;
  font-size: 14px;
  white-space: nowrap;
  cursor: pointer;
  margin-left: 10px;
  vertical-align: middle;
  
  &:hover {
    color: #1257f7;
  }
  
  &-icon {
    margin-left: 4px;
  }
}

.buttons-space {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  width: 100%;
  gap: 12px;
  
  .el-button {
    border-radius: 4px;
    font-size: 14px;
    padding: 10px 20px;
    height: 32px;
    line-height: 1;
    display: flex;
    align-items: center;
    justify-self: center;
    &.is-plain {
      border-color: #DCDFE6;
      color: #606266;
      
      &:hover {
        border-color: #356CEF;
        color: #356CEF;
        background-color: #ecf5ff;
      }
    }
    
    &.el-button--primary {
      background-color: #356CEF;
      border-color: #356CEF;
      
      &:hover {
        background-color: #1257f7;
        border-color: #1257f7;
      }
    }
  }
}

.ElColButtons {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 40px;
  }
}

.hidden {
  display: none !important;
}

@media (max-width: 768px) {
  .page-wrapper-search {
    padding: 12px;
  }
  
  .ElColButtons {
    :deep(.el-form-item__content) {
      justify-content: flex-start;
      height: auto;
    }
  }
  
  .buttons-space {
    justify-content: flex-start;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    
    .el-button, .advanced {
      width: 100%;
      justify-content: center;
    }
  }
}
</style>