<script setup lang="ts">
import { ref, shallowRef } from "vue";
import { ElForm, ElMessage } from "element-plus"
import { httpAdd } from "/@/api/system/action";


const emit = defineEmits(["refresh"]);

const initialState = {
  action_name: "",
  action_code: "",
  action_desc: ""
}

const rules = {
  action_code: [{ required: true, message: '请输入按钮编码', trigger: "change" }],
  action_name: [{ required: true, message: '请输入按钮名称', trigger: "change" }]
}

const visible = shallowRef(false);
const loading = shallowRef(false);
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const formData = ref<Record<string, string>>({ ...initialState });

async function handleSave() {
  loading.value = true;

  try {
    await formRef.value?.validate();
    const { code, message } = await httpAdd(formData.value);
    if (Number(code) !== 0) { 
      ElMessage.warning(message);
      return loading.value = false;
    }
    visible.value = false;
    emit("refresh");
  } catch (err) {
    console.log(err)
  } finally { 
    loading.value = false;
  }
}


defineExpose({
  onDisplay: () => { visible.value = true; }
});
</script>

<template>
  <ElDialog
    v-model="visible"
    title="添加按钮"
    center
    :close-on-click-modal="false"
    @close="formData = {}"
  >
    <ElForm :model="formData" :rules="rules" ref="formRef">
      <ElFormItem label="按钮编码" label-width="100px" prop="action_code">
        <ElInput v-model="formData.action_code" />
      </ElFormItem>
      <ElFormItem label="按钮名称" label-width="100px" prop="action_name">
        <ElInput v-model="formData.action_name" />
      </ElFormItem>

      <ElFormItem>
        <div w-full flex justify-end>
          <ElButton :loading="loading" type="primary" @click="handleSave">保存</ElButton>
        </div>
      </ElFormItem>
    </ElForm>
  </ElDialog>
</template>
