<template>
  <div class="index_box">
    <el-form label-width="90px" :inline="true">
      <!-- ✅ 主搜索项 -->
      <el-form-item
        v-for="(item, i) in seekListRow"
        :key="i"
        :label="item.label"
        :label-width="(item.labelWidth || 90) + 'px'"
      >
        <component
          :is="getFieldComponent(item)"
          v-model="defaultWhere[item.value]"
          v-bind="getFieldProps(item)"
          @keydown.enter.native.stop="search"
        >
          <el-option
            v-for="(op, j) in item.planList || []"
            :key="j"
            :label="op.label"
            :value="op.value"
          />
        </component>
      </el-form-item>

      <!-- ✅ 更多选项（竖向排列） -->
      <el-form-item v-if="deboListRow.length" class="more_option">
        <el-dropdown
          ref="dropdownRef"
          trigger="click"
          :hide-on-click="false"
          v-model="dropdownVisible"
        >
          <div class="el-dropdown-link">
            更多选项 <i class="el-icon-arrow-down el-icon--right"></i>
          </div>

          <el-dropdown-menu slot="dropdown">
            <div class="padding">
              <el-form label-position="left">
                <!-- 去掉 :inline="true" 即可竖排 -->
                <el-form-item
                  v-for="(item, i) in deboListRow"
                  :key="i"
                  :label="item.label"
                  :label-width="(item.labelWidth || 90) + 'px'"
                >
                  <component
                    :is="getFieldComponent(item)"
                    v-model="defaultWhere[item.value]"
                    v-bind="getFieldProps(item)"
                    @change="handleChange"
                    @keydown.enter.native.stop="search"
                  >
                    <el-option
                      v-for="(op, j) in item.planList || []"
                      :key="j"
                      :label="op.label"
                      :value="op.value"
                    />
                  </component>
                </el-form-item>
              </el-form>
            </div>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>

      <!-- ✅ 操作按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search">
          查询
        </el-button>
        <el-button icon="el-icon-refresh-left" type="primary" @click="reset">
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    props: {
      maxLength: { type: Number, default: 3 },
      seekList: { type: Array, default: () => [] },
      keyValue: { type: String, default: '' }
    },

    data() {
      return {
        defaultWhere: {},
        dropdownVisible: false,
        seekListRow: [],
        deboListRow: []
      };
    },

    watch: {
      seekList: {
        immediate: true,
        deep: true,
        handler(val) {
          if (!Array.isArray(val)) return;
          this.seekListRow = val.slice(0, this.maxLength);
          this.deboListRow = val.slice(this.maxLength);
        }
      },
      defaultWhere: {
        deep: true,
        handler(val) {
          if (!this.keyValue) return;
          if (Object.keys(val).length) {
            sessionStorage.setItem(this.keyValue, JSON.stringify(val));
          } else {
            sessionStorage.removeItem(this.keyValue);
          }
        }
      }
    },

    mounted() {
      const cache = this.keyValue && sessionStorage.getItem(this.keyValue);
      if (cache) {
        this.defaultWhere = JSON.parse(cache);
        this.search();
      }
    },

    methods: {
      /** 根据字段类型返回对应组件 */
      getFieldComponent(item) {
        switch (item.type) {
          case 'input':
            return 'el-input';
          case 'select':
            return 'el-select';
          case 'selectTree':
            return 'ele-tree-select';
          case 'date':
            return 'el-date-picker';
          default:
            return 'el-input';
        }
      },

      /** 生成字段属性 */
      getFieldProps(item) {
        const base = {
          placeholder:
            item.placeholder ||
            (item.type === 'input' ? '请输入内容' : '请选择'),
          style: {
            width: (item.width || (item.type === 'date' ? 350 : 200)) + 'px'
          }
        };

        switch (item.type) {
          case 'select':
            return {
              ...base,
              multiple: !!item.multiple,
              filterable: item.filterable !== false
            };
          case 'selectTree':
            return {
              ...base,
              data: item.planList || [],
              childrenKey: item.childrenKey || 'children',
              valueKey: 'id',
              labelKey: 'name',
              'default-expand-all': true
            };
          case 'date':
            return {
              ...base,
              type: item.dateType || 'daterange',
              'value-format': item.valueFormat || 'yyyy-MM-dd HH:mm:ss',
              'range-separator': '至',
              'start-placeholder': '开始日期',
              'end-placeholder': '结束日期'
            };
          default:
            return base;
        }
      },

      /** 下拉框保持展开 */
      handleChange() {
        if (this.$refs.dropdownRef?.show) this.$refs.dropdownRef.show();
      },

      /** 查询 */
      search() {
        const temp = { ...this.defaultWhere };
        this.seekList
          .filter((it) => it.valueAr)
          .forEach((it) => {
            const data = temp[it.value];
            if (data) {
              temp[it.valueAr[0]] = data[0];
              temp[it.valueAr[1]] = data[1];
            } else {
              delete temp[it.valueAr[0]];
              delete temp[it.valueAr[1]];
            }
            delete temp[it.value];
          });
        this.$emit('search', temp);
      },

      /** 重置 */
      reset() {
        this.defaultWhere = {};
        this.search();
      }
    }
  };
</script>

<style scoped lang="scss">
  .index_box {
    display: flex;
  }

  .padding {
    padding: 20px;
    max-height: 400px;
    overflow-y: auto;
  }

  ::v-deep(.more_option.el-form--inline.el-form-item) {
    margin-right: 0 !important;
  }

  /* ✅ 更多选项表单竖排间距优化 */
  ::v-deep(.el-dropdown-menu .el-form-item) {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
</style>
