<template>
  <div class="comp-content">
    <el-drawer
      v-model="visible"
      :title="`${data.parameterName ? '编辑' : '新增'}参数`"
      :size="400"
      :close-on-click-modal="false"
      @close="closeFun"
    >
      <div class="content">
        <TableForm ref="tableFormRef" v-model:data="paramData" tableName="PARAMETER_LIST">
          <template #form-parameterClass>
            <ParamClass v-model="paramData.parameterClass" @change="paramClassChangeFun" />
          </template>
          <template #form-unit>
            <ParamUnit
              v-model="paramData.unit"
              :name="paramClassName"
              :disabled="!paramData.parameterClass"
            />
          </template>
        </TableForm>
      </div>
      <template #footer>
        <div>
          <el-button @click="closeFun">关闭</el-button>
          <el-button type="primary" @click="submitFun">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import TableForm from '@/components/common/table/tableForm.vue';
import ParamClass from '@/components/common/paramClass/index.vue';
import ParamUnit from '@/components/common/paramUnit/index.vue';
import { cloneDeep } from 'lodash-es';

interface Props {
  modelValue: boolean;
  data: any;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  data: {},
});

const emit = defineEmits(['update:modelValue', 'add', 'edit']);
const visible = ref(false);
const tableFormRef = ref<any>();
const paramData = ref<any>({});
const paramClassName = ref('');

watch(
  () => props.modelValue,
  (val: boolean) => {
    visible.value = val;
    if (val) {
      if (props.data.parameterName) {
        paramData.value = cloneDeep(props.data);
      }
    } else {
      paramData.value = {};
      if (tableFormRef.value) {
        tableFormRef.value.resetFun();
      }
    }
  }
);

const submitFun = async () => {
  const valid = await tableFormRef.value.validateFun();
  if (valid) {
    if (!props.data.parameterName) {
      emit('add', cloneDeep(paramData.value));
    } else {
      emit('edit', cloneDeep(paramData.value));
    }
    closeFun();
  }
};

const paramClassChangeFun = (data: any) => {
  paramClassName.value = data.name;
  paramData.value.unit = '';
};

const closeFun = () => {
  emit('update:modelValue', false);
};
</script>
