<template>
  <el-form ref="elform" :model="listQuery" :label-width="props.labelWidth" :rules="props.rules" :inline="props.inline"
    label-position="left" :disabled="props.disabled">
    <el-form-item v-for="(item, idx) in props.formList" :style="item.width && { width: item.width }" :prop="item.prop"
      :label="item.label" :label-width="item.labelWidth" :key="idx">
      <el-input v-model="listQuery[item.prop]"  :placeholder="`请输入${item.label}`" :disabled="item.disabled" />
    </el-form-item>
  </el-form>
</template>
<script setup>
import { ref, defineProps, defineEmits, defineExpose, watch, watchEffect } from "vue";
const props = defineProps({
  //循环的值
  formList: {
    default: [],
    type: Array
  },
  rules: {
    default: {},
    type: Object
  },
  labelWidth: {
    default: "140px",
    type: String
  },
  modelValue: {
    type: Object,
    default: {}
  },
  inline: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  }
});
const elform = ref();
const listQuery = ref({});
const emits = defineEmits(["update:modelValue"]);
// 提交
const submit = (resfun) => {
  elform.value.validate((valid) => {
    if (!valid) return false;
    resfun(listQuery.value);
  });
};

const getdep = (e, val) => {
  if (val) listQuery.value[val] = e ? e.orgName : '';
}
const reset = () => {
  elform.value.resetFields()
}

// 修改这里的watch逻辑，避免无限循环
let isUpdatingFromProps = false;

watch(() => listQuery.value, (newVal) => {
  if (newVal && !isUpdatingFromProps) {
    emits("update:modelValue", newVal);
  }
}, { deep: true });

watch(() => props.modelValue, (newVal) => {
  // 只有在新值确实变化时才更新（避免空值覆盖）
  if (newVal && Object.keys(newVal).length > 0) {
    isUpdatingFromProps = true;
    listQuery.value = { ...newVal };
    setTimeout(() => {
      isUpdatingFromProps = false;
    }, 0);
  }
}, { immediate: true, deep: true });

defineExpose({ submit, reset });
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__label {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;

  flex: 0 0 auto;
  text-align: center;
  line-height: 32px;
  padding: 0 12px 0 0;
  box-sizing: border-box;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;

}
::v-deep .el-form-item {
margin-right: 0;
}
::v-deep .el-input__inner{
  height: 34px;
  line-height: 34px;
  border-radius: 0;
}
</style>
