<template>
    <el-dialog
        v-model="dialogVisible"
        title="程序激活"
        width="450px"
        draggable
        :close-on-click-modal="false"
        :before-close="beforeClose"
        :destroy-on-close="true"
    >
        <el-form :label-width="100" label-position="left">
            <el-form-item label="程序版本号">
                <el-text style="margin-left: 82%">{{ 'v' + versionNumber }}</el-text>
            </el-form-item>
        </el-form>
        <el-descriptions class="mode-descriptions" title="授权模块状态" size="small"></el-descriptions>
        <el-form v-if="activationModules.length" label-position="left" :label-width="100">
            <el-form-item v-for="module in activationModules" :key="module.key" class="mode-item" :label="module.label">
                <el-tag class="activated-state" disable-transitions :type="module.permanently === 1 ? 'success' : 'danger'">
                    {{ module.permanently === 1 ? '已激活' : '未激活' }}
                </el-tag>
            </el-form-item>
        </el-form>
        <el-text v-else type="info">暂无可展示的授权模块</el-text>
        <el-row v-if="applicationCode">
            <el-descriptions class="mode-descriptions" title="设备申请码" size="small"></el-descriptions>
            <el-tooltip placement="top-end" effect="light">
                <el-input
                    v-model="applicationCode"
                    :rows="5"
                    type="textarea"
                    readonly
                    resize="none"
                    class="code-display"
                />
                <template #content>
                    <el-button size="small" @click="copyCode" icon="DocumentCopy">复制</el-button>
                </template>
            </el-tooltip>
        </el-row>
        <el-row v-if="applicationCode || hadActivationCode">
            <el-descriptions class="mode-descriptions" title="设备激活码" size="small"></el-descriptions>
            <el-input
                placeholder="请输入设备激活码"
                v-model="activationCode"
                :rows="5"
                resize="none"
                type="textarea"
                class="code-input"
            />
        </el-row>
        <template #footer v-if="!activatedAll">
            <div v-if="!applicationCode && !hadActivationCode">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="getApplicationCode">获取申请码</el-button>
                <el-button type="primary" @click="hadActivationCode = true">已有激活码</el-button>
            </div>
            <div v-if="applicationCode || hadActivationCode">
                <el-button @click="cancel">取消</el-button>
                <el-button :disabled="!activationCode" type="primary" @click="submitActivation">激活</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { version } from '../../../../package.json'
import { generateApplicationCode, verifyActivationCode } from '@/api/activate'
import type { Activate } from '@/api/activate/interface'
import { useAuthStore } from '@/stores/modules/auth'

const authStore = useAuthStore()
const activateInfo = computed(() => authStore.activateInfo)
const versionNumber = ref(version)
const activationModules = computed<Activate.ActivationModuleStatus[]>(() => {
    return Object.keys(activateInfo.value)
        .sort()
        .map((key, index) => ({
            key,
            label: `授权模块 ${index + 1}`,
            permanently: activateInfo.value[key]?.permanently === 1 ? 1 : 0
        }))
})
const activatedAll = computed(() => {
    return activationModules.value.length > 0 && activationModules.value.every(module => module.permanently === 1)
})
const hadActivationCode = ref(false)
const applicationCode = ref('')
const activationCode = ref('')
const dialogVisible = ref(false)
// 获取申请码
const getApplicationCode = async () => {
    const res = await generateApplicationCode()
    if (res.code == 'A0000') {
        applicationCode.value = res.data as string
    }
}
// 复制申请码
const copyCode = async () => {
    try {
        await navigator.clipboard.writeText(applicationCode.value)
        ElMessage.success('已复制到剪贴板')
    } catch {
        ElMessage.error('复制失败，请手动选择内容')
    }
}
const resetDialogState = () => {
    hadActivationCode.value = false
    activationCode.value = ''
    applicationCode.value = ''
}
const openDialog = () => {
    resetDialogState()
    dialogVisible.value = true
}
const beforeClose = (done: Function) => {
    resetDialogState()
    done()
}
const cancel = () => {
    resetDialogState()
    dialogVisible.value = false
}
const submitActivation = async () => {
    const res = await verifyActivationCode(activationCode.value)
    if (res.code == 'A0000') {
        ElMessage.success('激活成功')
        await authStore.setActivateInfo()
        window.location.reload()
    } else {
        ElMessage.error(res.message)
    }
}
defineExpose({ openDialog })
</script>
<style scoped>
.activated-state {
    margin-left: 80%;
}
.code-display,
.code-input {
    font-family: consolas, sans-serif;
}
:deep(.el-tag) {
    user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}
:deep(.el-divider__text) {
    user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}
.mode-descriptions {
    user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    margin-top: 15px;
}
:deep(.el-form-item) {
    border: 1px solid #e5e7eb;
    border-radius: 4px;
    padding: 0 10px !important;
    margin-bottom: 10px !important;
    margin-right: 0 !important;
    user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}
:deep(.el-divider--horizontal) {
    margin: 10px 0 !important;
    margin-top: 20px !important;
}
.mode-item {
    transition: background-color 0.2s ease;
}
.mode-item:hover {
    background-color: #f9fafb;
}
</style>
