<template>
  <div>
    <el-form
      :model="form"
      inline>
      <el-form-item v-for="(obj, key) in form"
        :key="key"
        :label="obj.name">
        <template v-if="obj.type === 'input'">
          <el-input prefix-icon="Search"
            v-model="obj.value"
            clearable
            @input="sel"></el-input>
        </template>
        <!-- 添加其他表单类型的模板 -->
      </el-form-item>
    </el-form>
    <!-- 添加表格和其他内容 -->
    <el-table ref="myTable"
      :data="tableData"
      v-loading="tableLoading"
      highlight-selection-row
      @select="selectFn"
      @select-all="selectAllFn">
      <el-table-column v-if="tableData.length > 0"
        type="selection"
        width="50">
      </el-table-column>
      <el-table-column v-for="obj in tableHeaderList"
        :prop="Object.keys(obj)[0]"
        :label="Object.values(obj)[0]"
        :formatter="formatterFn"
        show-overflow-tooltip
        width="130">
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { debounce } from '@/utils';

const form = ref({}); // 表单对象
const tableHeaderList = ref([]);
const tableData = ref([]);
const tableLoading = ref(false);
const isOnlyLoadData = ref(false); // 仅加载数据（因为标签和数据是在一个对象传进来的）

const props = defineProps({
  // 结构+数据
  modelValue: {
    type: Object,
    required: true
  },
  // 查询参数
  queryParams: {
    type: Object,
    required: true
  }
});

const emits = defineEmits(['sel', 'update:queryParams']);

watch(() => props.modelValue, (newValue) => {
  // 加载结构
  if (!isOnlyLoadData.value) {
    // 准备表单结构
    newValue.boxhead.forEach(obj => {
      form.value[obj.select_key] = obj;
    });
    tableHeaderList.value = newValue.queryDisplay;
  }
  // 加载数据
  tableData.value = newValue.rows;
  tableLoading.value = false;
}, {
  deep: true,
  immediate: true
});

const formatterFn = (row, column) => {
  return row[column.property] || '无';
};

// 搜索框值变化
const sel = debounce(() => {
  tableLoading.value = true;
  isOnlyLoadData.value = true;
  const query = {};
  Object.entries(form.value).forEach(([key, value]) => {
    if (value.value) {
      query[key] = value.value.trim();
    }
  });
  emits('update:queryParams', query);
  emits('sel');
});

const selectAllFn = (rows) => {
  if (!props.isCheckBox) {
    table.clearSelection();
    emits('input', []);
  }
};

const selectFn = (rows) => {
  if (!props.isCheckBox) {
    table.clearSelection();
    rows.length > 0 && table.toggleRowSelection(rows[rows.length - 1]);
  }
  emits('input', rows.length > 0 ? [rows[rows.length - 1]] : []);
};
</script>

<style scoped></style>
