<template>
  <el-dialog
    v-model="visible"
    title="应用密钥"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-alert
      title="请妥善保管密钥，密钥重置后旧密钥将立即失效"
      type="warning"
      :closable="false"
      show-icon
      style="margin-bottom: 16px;"
    />
    <el-form label-width="100px">
      <el-form-item label="应用名称">
        <span>{{ appInfo.appName }}</span>
      </el-form-item>
      <el-form-item label="应用编码">
        <span>{{ appInfo.appCode }}</span>
      </el-form-item>
      <el-form-item label="应用密钥">
        <el-input
          v-model="appInfo.appSecret"
          readonly
          style="width: 280px;"
        >
          <template #append>
            <el-button @click="handleCopy">
              <el-icon><DocumentCopy /></el-icon>
              复制
            </el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 应用管理 - 密钥展示弹窗（重置后显示新密钥并支持复制）
 * @author pangu
 */
import { DocumentCopy } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'

const visible = ref(false)

const appInfo = reactive({
  appName: '',
  appCode: '',
  appSecret: ''
})

// 打开弹窗
const open = (row) => {
  visible.value = true
  Object.assign(appInfo, {
    appName: row.appName,
    appCode: row.appCode,
    appSecret: row.appSecret
  })
}

// 复制密钥
const handleCopy = async () => {
  try {
    await navigator.clipboard.writeText(appInfo.appSecret)
    ElMessage.success('复制成功')
  } catch (error) {
    // 降级方案
    const textarea = document.createElement('textarea')
    textarea.value = appInfo.appSecret
    document.body.appendChild(textarea)
    textarea.select()
    document.execCommand('copy')
    document.body.removeChild(textarea)
    ElMessage.success('复制成功')
  }
}

defineExpose({ open })
</script>
