<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="400px"
    :visible="visible"
    :confirm-loading="loading"
    :title="'创建 API key'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :maskClosable="false"
    :cancelText="cancelText"
    :okText="okText"
    @close="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      class="login-form">
      <a-form-item name="accessKey">
        <div class="login-input-group">
          <a-input
            v-if="form.accessSecret"
            allow-clear
            type="text"
            placeholder="请输入API Keys名称"
            v-model:value="form.accessSecret"
          >
          </a-input>
          <a-input
            v-else
            allow-clear
            type="text"
            placeholder="请输入API Keys名称"
            :maxlength="6"
            v-model:value="form.accessKey"
          >
          </a-input>
        </div>
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
import {ref, reactive} from "vue";
import {message} from "ant-design-vue";
import type {AccessKey} from "@/api/system/access-key/model";
import {assignObject} from 'ele-admin-pro';
import type { FormInstance, Rule } from 'ant-design-vue/es/form';
import {addAccessKey} from "@/api/system/access-key";
import {copyText} from "@/utils/common";

defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 修改回显的数据
  data?: AccessKey | null;
}>();

const emit = defineEmits<{
  (e: "done", form: AccessKey): void;
  (e: "update:visible", value: boolean): void;
}>();
// 提交状态
const loading = ref(false);
const cancelText = ref<string>("取消");
const okText = ref<string>("创建");
// 用户信息
const form = reactive<AccessKey>({
  id: 0,
  accessKey: undefined,
  accessSecret: undefined,
  createTime: undefined
});

/* 更新visible */
const updateVisible = (value: boolean) => {
  emit("update:visible", value);
};

// 表单验证规则
const rules = reactive<Record<string, Rule[]>>({
  accessKey: [
    {
      required: true,
      type: "string",
      message: "请输入API Key 名称",
      trigger: "blur"
    }
  ]
});

const formRef = ref<FormInstance | null>(null);

/* 保存编辑 */
const save = () => {
  if(form.accessSecret){
    copyText(form.accessSecret)
    return false;
  }
  if (!formRef.value) {
    return;
  }
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      addAccessKey(form)
        .then((data) => {
          console.log(data,'addData')
          if(data){
            assignObject(form, data);
            cancelText.value = "关闭";
            okText.value = "复制";
          }
          loading.value = false;
          message.success('创建成功');
          emit("done", {});
        })
        .catch((e) => {
          loading.value = false;
          message.error(e.message);
        });
    })
    .catch(() => {
    });
};
</script>
