<script setup lang="ts">
import type { FormInstance } from 'element-plus';

import { onMounted, ref } from 'vue';

import { EasyFlowFormModal } from '@easyflow/common-ui';

import { ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus';

import { api } from '#/api/request';
import { $t } from '#/locales';

const emit = defineEmits(['reload']);
// vue
onMounted(() => {});
defineExpose({
  openDialog,
});
const saveForm = ref<FormInstance>();
// variables
const dialogVisible = ref(false);
const isAdd = ref(true);
const entity = ref<any>({
  requestInterface: '',
  title: '',
});
const btnLoading = ref(false);
const rules = ref({});
// functions
function openDialog(row: any) {
  if (row.id) {
    isAdd.value = false;
  }
  entity.value = row;
  dialogVisible.value = true;
}
function save() {
  saveForm.value?.validate((valid) => {
    if (valid) {
      btnLoading.value = true;
      api
        .post(
          isAdd.value
            ? 'api/v1/sysApiKeyResourcePermission/save'
            : 'api/v1/sysApiKeyResourcePermission/update',
          entity.value,
        )
        .then((res) => {
          btnLoading.value = false;
          if (res.errorCode === 0) {
            ElMessage.success(res.message);
            emit('reload');
            closeDialog();
          }
        })
        .catch(() => {
          btnLoading.value = false;
        });
    }
  });
}
function closeDialog() {
  saveForm.value?.resetFields();
  isAdd.value = true;
  entity.value = {};
  dialogVisible.value = false;
}
</script>

<template>
  <EasyFlowFormModal
    v-model:open="dialogVisible"
    :closable="!btnLoading"
    :title="isAdd ? $t('button.add') : $t('button.edit')"
    :before-close="closeDialog"
    :confirm-loading="btnLoading"
    :confirm-text="$t('button.save')"
    :submitting="btnLoading"
    @confirm="save"
  >
    <ElForm
      ref="saveForm"
      :model="entity"
      status-icon
      :rules="rules"
      label-position="top"
      class="easyflow-modal-form easyflow-modal-form--compact"
    >
      <ElFormItem
        prop="requestInterface"
        :label="$t('sysApiKeyResourcePermission.requestInterface')"
      >
        <ElInput v-model.trim="entity.requestInterface" />
      </ElFormItem>
      <ElFormItem prop="title" :label="$t('sysApiKeyResourcePermission.title')">
        <ElInput v-model.trim="entity.title" />
      </ElFormItem>
    </ElForm>
  </EasyFlowFormModal>
</template>

<style scoped></style>
