<template>
  <Modal :maskClosable="false" :keyboard="false" v-model:open="data.isShowModal" :footer="null" :title="$t('system.user.updateSecretKeyTitle')" width="50%" @cancel="_close">
    <Form ref="formRef" :model="form" :label-col="{ span: 6 }" labelAlign="left"
           :labelWrap="true">
      <Row :gutter="24">
        <Col :span="24">
          <FormItem :label="$t('system.user.originalSecretKey')" name="originalSecretKey">
            <Input v-model:value="form.originalSecretKey" allowClear readonly :placeholder="$t('common.placeholderIn')"/>
          </FormItem>
        </Col>
        <Col :span="24">
          <FormItem :label="$t('system.user.newSecretKey')" name="newSecretKey">
            <Input v-model:value="form.newSecretKey" allowClear readonly :placeholder="$t('common.placeholderIn')"/>
          </FormItem>
        </Col>
        <Col :span="24" v-if="form.newSecretKey">
          <FormItem :label="'二维码'">
            <div class="qrcode-container">
              <img :src="qrCodeUrl" alt="OTP QR Code" class="qrcode" />
            </div>
          </FormItem>
        </Col>
      </Row>
      <FormItem style="text-align: right">
        <Button @click="_close" :disabled="data.loading">{{ $t('common.cancel') }}</Button>
        <Button type="primary" style="margin-left: 10px" @click="handleUpdate" :loading="data.loading"
                 :disabled="data.loading">{{ $t('common.update') }}
        </Button>
      </FormItem>
    </Form>
  </Modal>
</template>

<script setup lang="ts">
import {reactive, ref, computed, watch} from "vue";
import { $t } from '@vben/locales';
import {Modal, Form, Input, Row, Col, Button, message} from 'ant-design-vue';
import { update2faApi } from '#/api';
import QRCode from 'qrcode';

const FormItem = Form.Item;

interface Emits {
  (e: 'close', submit: Boolean): void
}
const emits = defineEmits<Emits>()

const data = reactive({
  isShowModal: false,
  loading: false,
})

const form = reactive({
  uuid: null,
  username: '',
  originalSecretKey: '',
  newSecretKey: '',
})

// 二维码图片的 Base64 数据
const qrCodeUrl = ref('');

// 计算OTP Auth URL
const otpAuthUrl = computed(() => {
  if (!form.newSecretKey || !form.username) return '';
  const issuer = form.username;
  const accountName = form.username;
  const secret = form.newSecretKey;
  return `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(accountName)}?secret=${encodeURIComponent(secret)}&issuer=${encodeURIComponent(issuer)}`;
});

// 监听OTP Auth URL变化，生成二维码
watch(otpAuthUrl, async (newUrl) => {
  if (newUrl) {
    try {
      qrCodeUrl.value = await QRCode.toDataURL(newUrl);
    } catch (error) {
      console.error('生成二维码失败:', error);
      qrCodeUrl.value = '';
    }
  } else {
    qrCodeUrl.value = '';
  }
});

function _open(item) {
  data.isShowModal = true;
  form.uuid = item.uid;
  form.username = item.username || '';
  form.originalSecretKey = item.secretKey || '';
  form.newSecretKey = '';
}

function _close() {
  data.isShowModal = false;
  emits('close', false);
}

async function handleUpdate() {
  if (!form.uuid) {
    message.error($t('common.invalidUuid'));
    return;
  }

  data.loading = true;
  try {
    const res = await update2faApi({ uuid: form.uuid });
    if (res.error) {
      message.error(res.error.message || $t('common.updateFailed'));
      return;
    }
    
    message.success($t('common.updateSuccess'));
    // 假设API返回的数据中包含新的secretKey
    form.newSecretKey = res.data || '';
    
    // 不立即关闭，让用户可以看到新的秘钥和二维码
    // emits('close', true);
  } catch (error) {
    message.error($t('common.updateFailed'));
  } finally {
    data.loading = false;
  }
}

defineExpose({
  _open,
  _close
})
</script>

<style scoped>
.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.qrcode {
  width: 200px;
  height: 200px;
  margin-bottom: 16px;
}

.qrcode-url {
  font-size: 12px;
  color: #666;
  word-break: break-all;
  text-align: center;
  max-width: 100%;
}
</style>