import { h, defineComponent, computed, ref } from 'vue'
import { ElForm, ElFormItem } from 'element-plus'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import CipButton from '../cip-button'
import CipFormItem from '../cip-form-item'
import { debounce, isNumber, getUsingConfig } from '@cip/utils/util'
import { useFormProvide } from '../hooks/use-form'
import { useObserveDomResize } from '../hooks/use-dom-resize'
import { cipSearchFormProps } from './props'
import './index.less'
import { useCipConfig } from '@cip/components/hooks/use-cip-config'
// cip-search-form 强制开启grid模式
export default defineComponent({
  name: 'CipSearchForm',
  props: cipSearchFormProps,
  emits: ['update:model', 'search'],
  setup (props, { emit, attrs }) {
    useFormProvide(props)
    const cipConfig = useCipConfig()
    const cipSearchForm = ref()
    const contentWidth = ref(1000)
    useObserveDomResize(() => cipSearchForm.value.$el, (e) => {
      contentWidth.value = e.contentRect.width
    })
    // 值更新
    const updateModel = (val) => { emit('update:model', val) }
    // 触发搜索
    const emitSearch = debounce((type) => { emit('search', type) }, 200, false)

    const resetSearch = () => {
      // 重置的时候载入默认model
      updateModel({ })
      emitSearch('reset')
    }

    const isExpand = ref(false)
    const toggleExpand = () => {
      isExpand.value = !isExpand.value
    }

    // 1366使用3列，1920使用5列，默认4列
    const gridCount = computed(() => {
      const grid = getUsingConfig(props.grid, cipConfig.searchGrid)
      if (isNumber(grid) && grid > 0) return grid // 过滤grid为数字且grid>0 则使用固定的列
      return Math.max(2, Math.floor(contentWidth.value / 335)) // contentWidth.value < 1300 ? 3 : (contentWidth.value > 1900 ? 5 : 4)
    })

    // 展示数量列表
    const fieldShowList = computed(() => {
      if (!props.collapse) {
        return props.fieldList
      } else {
        return isExpand.value ? props.fieldList : props.fieldList.filter((item, index) => index < gridCount.value - 1)
      }
    })

    const isImmediateSearch = (config) => {
      return config.immediateSearch === true || config.autoSelect === true
    }

    const showResetButton = computed(() => {
      return getUsingConfig(props.searchReset, cipConfig.searchReset)
    })

    const showExpandButton = computed(() => {
      return props.collapse && props.fieldList.length >= gridCount.value
    })

    const arrowIcon = computed(() => {
      return isExpand.value ? ArrowUp : ArrowDown
    })

    const formModel = computed(() => Object.assign({}, props.defaultModel, props.model))

    const formItem = ({ key, config } = {}) => {
      return h(CipFormItem, {
        key,
        model: formModel.value,
        fieldKey: key,
        config: config,
        grid: true,
        onKeyup: (e) => {
          const { keyCode } = e
          if (keyCode === 13) {
            emitSearch()
          }
        },
        onSearch: () => {
          emitSearch()
        },
        'onUpdate:model': (val) => {
          updateModel(val)
          // 值变更时立即搜索
          if (isImmediateSearch(config)) emitSearch()
        }
      })
    }

    const formItemList = () => fieldShowList.value.map(formItem)
    const formDefaultSlots = () => {
      const slots = formItemList() || []
      // 隐藏搜索按钮 或
      // 当搜索条件整行时 且 为展开时
      if (!props.hideSearch) {
        // 是否仅一个搜索条件
        const isOne = fieldShowList.value.length === 1
        const buttonList = <ElFormItem class={
          [
            'cip-search-button',
            {
              'cip-search-button--right': !isOne,
              'cip-search-button--absolute': props.handleAbsolute && isExpand.value && (props.fieldList.length % gridCount.value === 0)
            }
          ]
        }
        style={{
          alignItems: props.labelPosition === 'top' ? 'flex-end' : 'flex-start',
          gridColumn: !isOne ? `${gridCount.value} / span 1` : undefined
        }}
        >
          <CipButton buttonType={'search'} loading={props.listLoading} onClick={() => emitSearch()}>
            {{ default: ({ text }) => props.searchButtonText ?? text }}
          </CipButton>
          {showResetButton.value && <CipButton loading={props.listLoading} buttonType={'reset'} onClick={() => resetSearch()}/>}
          {showExpandButton.value && <CipButton square={true} icon={arrowIcon.value} onClick={() => toggleExpand()}/>}
        </ElFormItem>
        slots.push(buttonList)
      }
      return slots
    }
    if (props.hideSearch) { // 一次性配置不进行响应
      isExpand.value = true
    }

    return () => h(ElForm, {
      ...attrs,
      ref: cipSearchForm,
      class: 'cip-search-form',
      labelPosition: props.labelPosition,
      size: 'default',
      style: { gridTemplateColumns: `repeat(${gridCount.value}, 1fr)` },
      onSubmit: (e) => {
        e.preventDefault()
        emitSearch()
      } // 防止只有一个搜索项时按会车直接提交form的默认行为
    }, { default: formDefaultSlots })
  }

})
