<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: 12
    },
    md: {
      type: Number,
      default: 8
    },
    lg: {
      type: Number,
      default: 6
    },
    xl: {
      type: Number,
      default: 6
    },
    labelWidth: [Number, String]
  },
  data() {
    return {
      observer: null,
      ElFormRef: null,
      max: 0,
      isAdvanced: true,
      isFold: true,
      labelWidthValue: '',
      inputEvents: [],
      screenWidth: 1920,
      visibleFormItemsCount: 0 // 新增：跟踪可见表单项数量
    }
  },
  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)
    },
    // 修改：计算按钮列应该占用的实际列宽
    buttonColWidth() {
      if (this.shouldWrapButtons) {
        return 24 // 按钮在单独一行时占满整行
      }
      
      // 计算剩余空间，使按钮右对齐
      const visibleCount = this.visibleFormItemsCount
      const itemsInRow = this.maxItemsPerRow
      
      // 如果没有可见的表单项，按钮占整行
      if (visibleCount === 0) return 24
      
      // 计算当前行已有的列数
      const occupiedCols = visibleCount * this.currentColWidth
      const remainingCols = 24 - occupiedCols
      
      // 如果剩余空间足够放下按钮列，使用剩余空间
      if (remainingCols >= this.currentColWidth) {
        return remainingCols
      } else {
        // 如果剩余空间不够，按钮换行并右对齐
        return 24
      }
    },
    // 修改：是否需要换行显示按钮
    shouldWrapButtons() {
      if (!this.isFold) {
        // 展开状态下，如果可见表单项数量大于等于每行最大数量，按钮换行
        return this.visibleFormItemsCount >= this.maxItemsPerRow
      }
      
      // 折叠状态下，如果有需要隐藏的表单项，按钮和表单项在同一行
      return false
    }
  },
  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()
    this.updateVisibleCount()
    
    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)
  },
  updated() {
    this.updateVisibleCount()
  },
  methods: {
    handleResize() {
      this.screenWidth = document.documentElement.clientWidth
      this.initSize()
      this.$nextTick(() => {
        this.updateVisibleCount()
      })
    },
    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()
      this.$nextTick(() => {
        this.updateVisibleCount()
      })
    },
    shouldHideItem(index) {
      if (!this.isFold) return false
      return index >= this.maxVisibleItemsWhenFold
    },
    // 新增：更新可见表单项数量
    updateVisibleCount() {
      const formItems = this.extractFormItems(this.$slots.default || [])
      this.visibleFormItemsCount = formItems.filter((item, index) => !this.shouldHideItem(index)).length
    },
    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() {
    const defaultSlots = this.$slots.default || []
    const formItems = this.extractFormItems(defaultSlots)
    
    // 更新可见数量
    this.visibleFormItemsCount = formItems.filter((item, index) => !this.shouldHideItem(index)).length

    const formItemCols = formItems.map((item, index) => {
      const isHidden = this.shouldHideItem(index)
      
      return (
        <el-col
          class={{ 'hidden': isHidden }}
          key={`formitem-${index}`}
          xs={this.xs}
          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.buttonColWidth}
        md={this.buttonColWidth}
        lg={this.buttonColWidth}
        xl={this.buttonColWidth}
        style={this.shouldWrapButtons ? 'margin-top: 18px;' : ''}
      >
        {this.$slots.buttons ? this.$slots.buttons : buttons}
      </el-col>
    )

    // 计算按钮对齐方式
    const buttonJustify = this.shouldWrapButtons ? 'flex-end' : 'flex-end'

    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: 18px; display: flex; justify-content: ${buttonJustify};`}>
            {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: 50%;
      
      .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;
    
    // 确保按钮内容右对齐
    .buttons-space {
      justify-content: flex-end;
      width: 100%;
    }
  }
}

.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>