<template>
  <div class="form-content">
    <div class="form" :class="{ input: mode === 'input' }">
      <div v-for="(item, index) in formData" :key="index" class="form-item">
        <div class="title">
          <el-input
            v-if="mode === 'edit'"
            v-model="item.title"
            placeholder="请输入标题"
            clearable
            :disabled="disabled"
          />
          <span v-else>{{ item.title }}</span>
        </div>
        <div v-if="mode === 'input'" class="inp">
          <el-input v-model="item.value" placeholder="请输入" clearable :disabled="disabled" />
        </div>
        <div v-else class="inp">
          <el-input v-model="item.key" placeholder="请输入key值" clearable :disabled="disabled" />
        </div>
        <el-link v-if="mode === 'edit'" class="del-btn" type="danger" @click="delFun(index)">
          删除
        </el-link>
      </div>
      <div v-if="mode === 'edit' && !disabled" class="add-column" @click="addDataFun">
        <el-icon :size="22"><Plus /></el-icon>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { Plus } from '@element-plus/icons-vue';

const emit = defineEmits(['update:value']);

interface Props {
  value: any;
  mode: string;
  disabled?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  value: [],
  mode: '',
  disabled: false,
});

const formData = ref<any>([
  {
    title: '',
    key: '',
  },
]);

watch(
  () => props.value,
  (val: any) => {
    formData.value = val || [];
  },
  { deep: true, immediate: true }
);

watch(
  () => formData.value,
  (val: any) => {
    emit('update:value', val);
  },
  { deep: true }
);

const addDataFun = () => {
  formData.value.push({
    title: '',
    key: '',
  });
};

const delFun = (index: any) => {
  formData.value.splice(index, 1);
};
</script>

<style lang="scss" scoped>
.form-content {
  width: 100%;
  padding: 10px;
  border-radius: 4px;
  .form {
    position: relative;
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding-bottom: 30px;
    &.input {
      padding-bottom: 0;
    }
    .form-item {
      width: calc(50% - 10px);
      display: flex;
      margin-bottom: 10px;
      .title {
        width: 40%;
        margin-right: 5px;
        display: flex;
        align-items: center;
      }
      .inp {
        flex: 1;
      }
      .del-btn {
        margin-left: 5px;
      }
    }
    .add-column {
      position: absolute;
      bottom: 0;
      left: 50%;
      width: 30px;
      height: 30px;
      margin-left: -15px;
      background-color: var(--el-color-primary);
      color: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
  }
}
</style>
