<script setup lang="ts">
import { reactive, ref } from "vue";
import { message } from "@/utils/message";
import type { FormInstance } from "element-plus";
import { cloneDeep } from "@pureadmin/utils";
import * as $api from "@/api/auth/index";

defineOptions({ name: "templateEdit" });
const isDetail = ref(false);
const formRef = ref<FormInstance>();
// 初始化数据
const initData = {
  code: undefined
};

// 页面数据
const pageData: any = reactive({
  code: "",
  // 表单数据
  formData: initData,
  formRules: {
    code: [{ required: true, message: "验证码不能为空", trigger: "blur" }]
  }
});
// 暴露给父级调用
const emits = defineEmits(["ok", "close"]);
const qrcode = ref("");
// 打开弹窗
const open = (data: any, dataSource: any, mode: string) => {
  $api.createGoogleOtp().then((res: any) => {
    qrcode.value = res.message;
  });
  isDetail.value = false;
  pageData.dialogVisible = true;
};
// 确定并关闭弹窗
const handleConfirm = () => {
  formRef.value!.validate((isValid: boolean) => {
    if (isValid) {
      _save();
    } else {
      message("表单校验失败", { type: "warning" });
    }
  });
};
const _save = () => {
  pageData.formLoading = true;
  const _data = cloneDeep(pageData.formData);
  $api
    .save(_data)
    .then((res: any) => {
      if (res.success) {
        _confirm();
      } else {
        message(res.message, { type: "warning" });
      }
    })
    .finally(() => {
      pageData.formLoading = false;
    });
};
const _confirm = () => {
  pageData.dialogVisible = false;
  emits("ok");
};
defineExpose({ open });
const showClose = ref(false);
</script>

<template>
  <el-dialog
    v-model="pageData.dialogVisible"
    :show-close="showClose"
    :width="500"
  >
    <template #header>
      <el-text class="mx-1" type="primary" size="large">绑定谷歌验证器</el-text>
    </template>

    <div class="el-dialog-content">
      <el-form
        :model="pageData.formData"
        ref="formRef"
        style="width: 90%; margin: 20px auto 0"
        label-width="auto"
        :rules="pageData.formRules"
      >
        <el-form-item label="二维码">
          <img :src="qrcode" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="pageData.formData.code" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" @click="handleConfirm">确认</el-button>
    </template>
  </el-dialog>
</template>
