<template>
  <div class="comp-content">
    <el-drawer
      v-model="visible"
      :title="`${data.uuid ? '编辑' : '新增'}字典类型`"
      :size="400"
      :close-on-click-modal="false"
      @close="closeFun"
    >
      <div class="content">
        <TableForm ref="tableFormRef" :tableName="tableName" :showDisabled="!!data.uuid" />
      </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 { ElMessage } from 'element-plus';
import { addDictionaryClassApi, updateDictionaryClassApi, getDictionaryClassDetailApi } from '@/api/system/systemData';
import TableForm from '@/components/common/table/tableForm.vue';
import { getAllDictDataFun } from '@/utils/common';

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

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

const emit = defineEmits(['update:modelValue', 'submit']);
const visible = ref(false);
const tableFormRef = ref<any>();

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

const getDetailFun = () => {
  const params = {
    uuid: props.data.uuid,
  };
  getDictionaryClassDetailApi(params).then((res: any) => {
    if (res.code === 200) {
      tableFormRef.value.setFormDataFun(res.data);
    }
  });
};

// 提交
const submitFun = async() => {
  const valid = await tableFormRef.value.validateFun();
  if (valid) {
    const fromData = tableFormRef.value.getFormDataFun();
    const params = {
      ...fromData,
    };
    let apiFun = addDictionaryClassApi;
    if (props.data.uuid) {
      params.uuid = props.data.uuid;
      apiFun = updateDictionaryClassApi;
    }
    apiFun(params).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success('操作成功');
        closeFun();
        emit('submit');
        getAllDictDataFun(true);
      }
    });
  }
};

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