<template>
  <el-form
    ref="formRef"
    :model="modelValue"
    :label-width="`${labelWidth}px`"
    :disabled="disabled"
  >
    <el-row>
      <el-col :span="24">
        <el-form-item
          :label="`${title}:`"
          :prop="fieldKey"
          :rules="[
            {
              type: 'array',
              message: '请输入并添加',
              trigger: 'change',
            },
          ]"
        >
          <el-row type="flex" justify="space-between">
            <el-col :span="20">
              <el-input v-model="dataVal" :placeholder="placeholder"></el-input>
            </el-col>
            <el-col :span="3">
              <el-button type="primary" @click="keyWordAdd">添加</el-button>
            </el-col>
          </el-row>

          <div class="e_tag">
            <el-tag
              v-for="(tag, index) in modelValue[fieldKey]"
              :key="index"
              closable
              @close="handleFieldClose(fieldKey, index)"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script setup name="InputBoxAdd">
import { industry } from "@/api/config";
import { ElMessage } from "element-plus";
import { ref, toRefs } from "vue";

const props = defineProps({
  modelValue: Object,
  labelWidth: {
    type: Number,
    default: 120,
  },
  title: {
    type: String,
    default: "",
  },
  placeholder: {
    type: String,
    default: "",
  },
  fieldKey: {
    require: true,
    type: String,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const { modelValue, title, fieldKey, placeholder, disabled, labelWidth } =
  toRefs(props);
const dataVal = ref("");
const formRef = ref(null);
const keyWordAdd = () => {
  if (!dataVal.value.length) return ElMessage.error(`请输入${title.value}`);
  modelValue.value[fieldKey.value].push(dataVal.value);
  dataVal.value = "";
};
const handleFieldClose = (val, index) => {
  modelValue.value[val].splice(index, 1);
};

const validateForm = async () => {
  try {
    return await formRef.value.validate();
  } catch (error) {
    return false;
  }
};

defineExpose({
  validateForm,
});
</script>

<style lang="scss" scoped>
.e_tag {
  width: 100%;
  .el-tag {
    margin-right: 10px;
  }
}
</style>
