<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="tableRef"
      :data="tableData"
      v-loading="tableLoading"
      highlight-selection-row
      :row-key="nodeKey"
      :select-on-indeterminate="false"
      @select="select"
      @select-all="selectAll">
      <el-table-column 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 tableRef = ref(null) // 表格实例
const form = ref({}); // 表单对象
const tableHeaderList = ref([]);
const tableData = ref([]);
const tableLoading = ref(false);
const isOnlyLoadData = ref(false); // 仅加载数据（因为标签和数据是在一个对象传进来的）

const props = defineProps({
  // 结构+数据
  structData: {
    type: Object,
    required: true
  },
  // 选择的数据（要和 structData 里的 rows 数据一致）
  modelValue: {
    type: Array,
    default: () => [],
    required: true
  },
  // 查询参数
  queryParams: {
    type: Object,
    default: () => ({})
  },
  // 关键数据的属性
  nodeKey: {
    type: String,
    default: 'id'
  },
  // 是否单选
  isRadio: {
    type: Boolean,
    default: false
  }
});

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

// 更新表格行选中
const updateCheck = (newValue) => {
  nextTick(() => {
    if (newValue.length > 0) {
      // 遍历对比，选中/取消选中
      props.structData.rows.forEach(o => {
        // 参数 2：决定选中与否
        tableRef.value.toggleRowSelection(o, newValue.some(item => item[props.nodeKey] === o[props.nodeKey]), false)
      })
    } else {
      tableRef.value.clearSelection()
    }
  })
}

watch(() => props.modelValue, updateCheck, {
  deep: true,
  immediate: true
})

watch(() => props.structData, (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;
  updateCheck(props.modelValue)
}, {
  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 selectAll = (selection) => {
  if (props.isRadio) {
    // 实现单选
    emits('update:modelValue', selection.length > 0 ? [selection[selection.length - 1]] : []);
  } else {
    // 实现多选
    emits('update:modelValue', selection);
  }
};
// 手动选中
const select = (rows) => {
  if (props.isRadio) {
    // 实现单选
    emits('update:modelValue', rows.length > 0 ? [rows[rows.length - 1]] : []);
  } else {
    // 实现多选
    emits('update:modelValue', rows);
  }
};
</script>

<style scoped></style>
