//该组件适用于表格的查询条件等不太复杂的表单场景,通过透传props配置来驱动表单的渲染。
//该组件具备栅格功能,既可以配置model,也可以配置宽度
//其他较复杂的主页面表单场景还是简易手写组件和业务
<template>
  <div
    v-if="fields?.length"
    class="table-search"
    :class="{ 'in-padding': inPadding }"
  >
    <t-form ref="formRef" :model="params" :inline="true">
      <div class="first-row flex">
        <t-form-item
          v-for="item in firstLineItemsFilter"
          :key="item.prop"
          :label="item.label || ''"
          :labelWidth="item.labelWidth || 0"
          :style="{ width: colToWidth(item.colSpan || 0) }"
          :class="{ 'buttons-wrap': item.type == 'buttons' }"
        >
          <slot
            :name="item.cell || item.prop"
            v-bind="{ item, params, search }"
          >
            <SearchFormItem :item="item" :params="params" :search="search" />
          </slot>
        </t-form-item>
        <div class="flex-1"></div>
        <t-form-item
          v-for="item in firstLineItemsIsRight"
          :key="item.prop"
          :label="item.label || ''"
          :labelWidth="item.labelWidth || 0"
          :style="{ width: colToWidth(item.colSpan || 0) }"
          :class="{ 'buttons-wrap': item.type == 'buttons' }"
        >
          <slot
            :name="item.cell || item.prop"
            v-bind="{ item, params, search }"
          >
            <SearchFormItem :item="item" :params="params" :search="search" />
          </slot>
        </t-form-item>
        <div v-if="showExpandBtn && !showAll" class="flex-1 text-right">
          <t-button
            theme="primary"
            shape="square"
            variant="base"
            class="m-l-5px"
            @click="showMore = !showMore"
          >
            <ChevronDownIcon slot="icon" v-if="!showMore" />
            <ChevronUpIcon slot="icon" v-else />
          </t-button>
        </div>
        <!-- </div> -->
      </div>
      <div ref="otherRows" class="other-rows" :style="{ height: otherHeight }">
        <t-form-item
          v-for="item in otherLineItems"
          :key="item.prop"
          :label="item.label || ''"
          :labelWidth="item.labelWidth || 0"
          :style="{ width: colToWidth(item.colSpan || 0) }"
          :class="{ 'buttons-wrap': item.type == 'buttons' }"
        >
          <slot
            :name="item.cell || item.prop"
            v-bind="{ item, params, search }"
          >
            <SearchFormItem :item="item" :params="params" :search="search" />
          </slot>
        </t-form-item>
      </div>
    </t-form>
  </div>
</template>

<script setup name="searchForm">
import {
  ref,
  computed,
  onMounted,
  getCurrentInstance,
  onUnmounted,
  watch,
  nextTick,
} from 'vue';
import { ChevronDownIcon, ChevronUpIcon } from 'tdesign-icons-vue-next';
import SearchFormItem from './components/search-form-item.vue';
import elementResizeDetectorMaker from 'element-resize-detector';
import { cloneDeep } from 'lodash';
import { useAppStore } from '@/store';
const otherRows = ref(null);
const appStore = useAppStore();
let comWidth = ref(0);
const { proxy } = getCurrentInstance();
const listen = () => {
  comWidth.value = proxy.$el.clientWidth;
};
onMounted(() => {
  window.addEventListener('resize', listen);
  var erd = elementResizeDetectorMaker();
  let ele = document.querySelector('.left-menu');
  if (!ele) return false;
  erd.listenTo(ele, function (element) {
    listen();
  });
});
onUnmounted(() => {
  window.removeEventListener('resize', listen);
});

// 默认值
const props = defineProps({
  fields: Object, // 搜索配置列，见下方示例
  params: Object, // 搜索参数
  showAll: { type: Boolean, default: true }, //是否要求直接展开，无需折叠换行按钮
  inPadding: Boolean,
  search: { type: Function, default: () => {} },
});
//fields示例：（目前支持控件：input、select、dropdown按钮、treeSelect、date选择框、time选择框、timerange时间范围选择框、daterange日期范围选择框...后期可以按需求扩展）
/*
const fields = [
    {
      prop: 'b',
      label: '姓名',
      labelWidth: 60,
      colSpan: 3.6,
    },
    {
      prop: 'c',
      label: '来源',
      type: 'select',
      labelWidth: 60,
      colSpan: 3.6,
    },
    {
      type: 'button',
      text: '查询',
      attrs: {
        class: 'm-l-10px',
      },
    },
    {
      type: 'button',
      text: '新增',
      position: 'right',    //搜索条件中可能会有按钮在首行中居右，可以使用position:'right'
      attrs: {
        theme: 'success',
      },
      onClick: () => {},
    },
    {
    type: 'buttons',
    colSpan: 6,
    children: [
      {
        type: 'button',
        text: '查询',
        attrs: {
          theme: 'primary',
        },
        onClick: () => {},
      },
      {
        type: 'dropdown',
        text: '导入',
        attrs: {
          options: [
            { content: '科组长', value: 1 },
            { content: '复核员', value: 2 },
          ],
        },
        buttonAttrs: {
          theme: 'default',
        },
        onClick: (data) => {},
      },
    ],
  },
];
*/
if (props.showAll) {
  //假设配置为不显示展开按钮，则要考虑把"查询"按钮排到末尾端
  let buttonsFieldIndex = props.fields.findIndex(
    (item) => item.type === 'buttons'
  );
  if (buttonsFieldIndex > -1) {
    let buttonsFieldArr = props.fields.splice(buttonsFieldIndex, 1);
    props.fields.push(buttonsFieldArr[0]);
  }
}
const showExpandBtn = computed(() => {
  let allColSpanNum = props.fields.reduce((total, item) => {
    return total + item.colSpan;
  }, 0);
  return allColSpanNum > 24;
});
// const maxWidth = ref(1260);

// 是否展开更多搜索项
const showMore = ref(false);
const otherHeight = props.showAll ? ref('auto') : ref(0);
const cutIndex = ref(0);

watch(showMore, (val) => {
  if (val) {
    otherHeight.value = 'auto';
    nextTick(() => {
      let targetHeight = window.getComputedStyle(otherRows.value).height;
      otherHeight.value = 0;
      setTimeout(() => {
        otherHeight.value = targetHeight;
      }, 0);
    });
  } else {
    otherHeight.value = 0;
  }
});

// 根据是否展开配置搜索项长度
const firstLineItems = computed(() => {
  let init = 0;
  let arr = [];
  for (let i = 0; i < props.fields.length; i++) {
    let column = props.fields[i];
    if (init + (column.colSpan || 0) > 24) {
      break;
    } else {
      arr.push(cloneDeep(column));
      init += column.colSpan || 0;
    }
  }

  cutIndex.value = arr.length;

  return arr;
});
const firstLineItemsFilter = computed(() => {
  return firstLineItems.value.filter((item) => item.position !== 'right');
});
const firstLineItemsIsRight = computed(() => {
  return firstLineItems.value.filter((item) => item.position === 'right');
});

const otherLineItems = computed(() => {
  return props.fields?.slice(cutIndex.value) || [];
});
const colToWidth = (colSpan) => {
  if (colSpan === 0) {
    return 'auto';
  }
  // let canUseWidth = comWidth.value - (props.showAll ? 20 : 60);
  let canUseWidth = comWidth.value - (props.showAll ? 40 : 60);
  return Math.floor((canUseWidth * colSpan) / 24) + 'px';
};
</script>
