<template>
  <n-form
    ref="formRef" :model="formData" :inline="true" label-placement="left" class="dynamic-form">
    <div v-for="(item, index) in formData.items" :key="index">
      <div style="display: flex">
        <n-form-item
          :label="`${userName} (${index + 1})`"
        >
          <n-input v-model:value="item.name" clearable />
        </n-form-item>
        <n-form-item
          :label="`${userPhone} (${index + 1})`"
        >
          <n-input v-model:value="item.phone" clearable />
        </n-form-item>
        <n-form-item
          :label="`${userIdCard} (${index + 1})`"
        >
          <n-input v-model:value="item.idCard" clearable />
        </n-form-item>
        <n-form-item>
          <n-button  type="error" secondary  @click="removeItem(index)" v-if="index !== 0" :disabled="formData.items.length === 1">
            {{ removeButtonText }}
          </n-button>
        </n-form-item>
      </div>
    </div>
    <n-button type="primary" @click="addItem" class="add-btn">
      {{ addButtonText }}
    </n-button>
  </n-form>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from "vue";
  import type { FormInst, FormRules } from "naive-ui";
  interface FormItem {
    name: string;
    phone: string;
    idCard: string;
  }
  const props = withDefaults(defineProps<{
    modelValue: FormItem[]
    addButtonText?: string
    removeButtonText?: string
    userName:string,
    userPhone:'',
    userIdCard:''
  }>(), {
    modelValue: () => [{
      name: "",
      phone: "",
      idCard: ""
    }],
    addButtonText: '添加',
    removeButtonText: '删除',
    userName:'',
    userPhone:'',
    userIdCard:''
  });

  const emit = defineEmits<{
    'update:modelValue': [value: FormItem[]];
    'add': [index: number];
    'remove': [index: number];
  }>();

  // 表单验证规则
  const rules: FormRules = {
    name: {
      required: true,
      message: `${props.userName}不能为空`,
      trigger: [ 'input']
    },
    phone: {
      required: true,
      validator: (_, value: string) => {
        if (!/^1[3-9]\d{9}$/.test(value)) {
          return new Error("请输入有效的手机号码");
        }
        return true;
      },
      trigger: [ 'input']
    },
    idCard: {
      required: true,
      validator: (_, value: string) => {
        if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
          return new Error("请输入有效的身份证号码");
        }
        return true;
      },
      trigger: [ 'input']
    }
  };

  // 表单数据
  const formRef = ref<FormInst | null>(null);

  const formData = reactive<{ items: FormItem[] }>({
    items: [...props.modelValue]
  });

  // 监听数据变化
  watch(() => props.modelValue, (newVal) => {
    if (JSON.stringify(newVal) !== JSON.stringify(formData.items)) {
      formData.items = [...newVal];
    }
  });

  // 添加条目
  const addItem = () => {
    formData.items.push({
      name: "",
      phone: "",
      idCard: ""
    });
    emit('update:modelValue', formData.items);
    emit('add', formData.items.length - 1);
  };

  // 删除条目
  const removeItem = (index: number) => {
    if (formData.items.length > 1) {
      formData.items.splice(index, 1);
      emit('update:modelValue', formData.items);
      emit('remove', index);
    }
  };

  // 表单验证
  const validate = () => {
    return new Promise((resolve, reject) => {
      formRef.value?.validate((errors) => {
        if (!errors) {
          resolve(formData.items);
        } else {
          reject(errors);
        }
      });
    });
  };

  // 暴露验证方法
  defineExpose({ validate });
</script>

<style lang="scss" scoped>
  .dynamic-form {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    .add-btn{
      margin-left: 10px;
    }
  }
</style>