<template>
  <div class="comp-content">
    <el-drawer
      v-model="visible"
      :title="`${id ? '编辑' : '新增'}用户`"
      :size="400"
      :close-on-click-modal="false"
      @close="closeFun"
    >
      <div class="content">
        <TableForm ref="tableFormRef" :tableName="tableName" />
      </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 TableForm from '@/components/common/table/tableForm.vue';
import { userAddUserApi, userQueryUserDetailApi, userUpdateUserApi } from '@/api/system/user';

interface Props {
  modelValue: boolean;
  tableName: string;
  id: number | string;
}

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

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.id) {
        getDetailFun();
      }
    } else {
      if (tableFormRef.value) {
        tableFormRef.value.resetFun();
      }
    }
  }
);

const getDetailFun = () => {
  const params = {
    id: props.id,
  };
  userQueryUserDetailApi(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 api = props.id ? userUpdateUserApi : userAddUserApi;
    const params = {
      id: props.id || '',
      ...fromData,
      status: Number(fromData.status),
    };
    api(params).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success('操作成功');
        closeFun();
        emit('submit');
      }
    });
  }
};

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