<script lang="ts" name="PageWrapperSearch">
import {
  ref,
  computed,
  nextTick,
  defineComponent,
  h,
  isVNode,
  useSlots,
  withModifiers,
  onMounted,
  onBeforeUnmount,
  PropType
} from 'vue'
import type { Component } from 'vue'

import {
  ElRow,
  ElCol,
  ElForm,
  ElIcon,
  ElButton,
  ElSpace
} from 'element-plus'
import type {
  FormInstance,
  FormItemProp,
  FormRules,
  FormValidateCallback
} from 'element-plus'
import {
  ArrowDown,
  ArrowUp,
  Search,
  Refresh
} from '@element-plus/icons-vue'
const XS = 0
const SM = 768
const MD = 992
const LG = 1200
const XL = 1920


export default defineComponent({
  emits: ['update:advanced', 'search', 'reset'],
  components: {
    ElRow,
    ElCol,
    ElForm
  },
  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],
    extraButtons: {
    type: Array as PropType<Array<{
      text: string
      type?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'text'
      plain?: boolean
      round?: boolean
      icon?: Component
      onClick: () => void
    }>>,
    default: () => []
  }
  },
  setup(props, { emit, attrs, slots }) {
    let observer
    const ElFormRef = ref<FormInstance>()
    const max = ref(0)
    const isAdvanced = ref(true)
    const isFold = ref(true)
    const labelWidthValue = ref('')
    const inputEvents = ref([])
    const gutter = computed(() => (24 / max.value % 24) || 0)

    onMounted(() => {
      observer = new ResizeObserver((entries) => {
        if (entries[0].contentRect.width > 0) {
          const rect = ElFormRef.value?.$el.getBoundingClientRect()
          initSize()
          // console.log('ResizeObserver', entries[0])
          // console.log(rect)
        }
      })
      observer.observe(ElFormRef.value?.$el)
      initSize()
    })
    onBeforeUnmount(() => {
      observer.disconnect()
      observer.unobserve(ElFormRef.value?.$el)
    })

    function initSize() {
      const docW = document.documentElement.clientWidth
      // const rect = ElFormRef.value?.$el.getBoundingClientRect()
      // const docW = rect.width
      // console.log('initSize', docW)
      max.value = 24 / (docW >= XL ? props.xl
        : docW >= LG ? props.lg
          : docW >= MD ? props.md
            : docW >= SM ? props.sm
              : props.xs)
      resetLabelWidth()
    }
    // 重置表单label宽度
    function resetLabelWidth() {
      labelWidthValue.value = ''
      nextTick().then(() => {
        const formItemLabels = ElFormRef.value?.$el ? ElFormRef.value.$el.querySelectorAll('.el-form-item__label') : []
        const arr: number[] = []
        formItemLabels.forEach(item => {
          arr.push(item.offsetWidth)
        })
        const max = Math.max.apply(null, arr)
        labelWidthValue.value = String(max + 16)
      })
    }
    function toggleFold() {
      isFold.value = !isFold.value
      labelWidthValue.value = ''
      resetLabelWidth()
    }

    return () => {
      // 搜索 重置
      const buttons = h(
        ElCol,
        {
          class: 'ElColButtons',
          xs: 24,
          sm: props.sm,
          md: props.md,
          lg: props.lg,
          xl: props.xl
        },
        () => slots.buttons ? slots.buttons() : h(
          ElSpace,
          {
            class: 'buttons-space'
          },
          () => [
            ...props.extraButtons.map(btn => h(
              ElButton,
              {
                type: btn.type,
                plain: btn.plain,
                round: btn.round,
                onClick: btn.onClick
              },
              () => [
                btn.icon ? h(ElIcon, null, () => [h(btn.icon as Component)]) : null,
                btn.text
              ]
            )),
            h(
              ElButton,
              {
                round: false,
                plain: true,
                onClick: () => {
                  emit('reset', ElFormRef.value)
                }
              },
              () => [
                h(ElIcon, null, () => h(Refresh)),
                '重置'
              ]
            ),
            h(
              ElButton,
              {
                type: 'primary',
                round: false,
                onClick: () => {
                  emit('search')
                }
              },
               () => [
                h(ElIcon, null, () => h(Search)),
                '搜索'
              ]
            ),
            cols.length > max.value ? h(
              'div',
              {
                class: 'advanced',
                onClick: toggleFold
              },
              [
                h(
                  'span',
                  isFold.value ? '展开' : '收起'
                ),
                h(
                  ElIcon,
                  {
                    class: 'advanced-icon'
                  },
                  () => h(isFold.value ? ArrowDown : ArrowUp)
                )
              ]
            ) : null
          ]
        )
      )
      // 默认插槽包裹el-col
      const SLOTS_DEFAULT = slots.default ? slots?.default() : []
      SLOTS_DEFAULT.push({
        type: {},
        props: null,
        key: null,
        ref: null,
        scopeId: null,
        children: null,
        component: null,
        dirs: null,
        transition: null,
        el: null,
        anchor: null,
        target: null,
        targetAnchor: null,
        suspense: null,
        shapeFlag: 0,
        patchFlag: 0,
        appContext: null
      })
      const cols = SLOTS_DEFAULT
        .filter(item => typeof item.type === 'object')
        .map((item, index, arr) => {
          if (index === arr.length - 1) {
            return [h(
              ElCol,
              {
                xs: 24,
                sm: props.sm,
                md: props.md,
                lg: props.lg,
                xl: props.xl,
                style: 'height:50px'
              }
            ), buttons]
          }
          // item.children.default()[0].props.onKeyup = function (e) {
          //   console.log(e)
          //   console.log('keyupEnter')
          // }
          // console.log(item.children.default()[0])
          return h(
            ElCol,
            {
              class: { 'hidden': isAdvanced.value && index + 1 >= max.value && isFold.value },
              key: `formitem${index}`,
              xs: 24,
              sm: props.sm,
              md: props.md,
              lg: props.lg,
              xl: props.xl
            },
            () => h(item)
          )
        })

      return h(
        ElForm,
        {
          ...attrs,
          labelWidth: props.labelWidth || labelWidthValue.value,
          labelPosition: 'right',
          ref: ElFormRef
        },
        () => h(
          ElRow,
          {
            gutter: gutter.value
          },
          () => cols
        )
      )
    }
  }
})
</script>

<style lang="scss" scoped>

:deep(.el-form-item__content) {
  > div {
    width: 100%;
  }
}

:deep(.el-space) {
  .el-space__item {
    &:last-child {
      margin-right: 0 !important;
    }
  }
}

.advanced {
  color: rgba(53, 108, 236, 1);
  font-size: 12px;
  white-space: nowrap;
  cursor: pointer;
  &-icon {
    margin: 0 4px;
  }
}

.buttons {
  &-space {
    justify-content: flex-end;
    width: 100%;
    // position: absolute;
    // right: 6px;
    // bottom: 0;
    // padding-bottom: 19px;
  }
}

.ElColButtons{
  position: absolute;
  right: 0;
  bottom: 0;
  padding-bottom: 18px;
}
.hidden {
  // visibility: hidden;
  display: none !important;
  padding: 0 !important;
  width: 0;
  max-width: 0;
}
</style>
