<template>
  <div class="part-box">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="授权信息" name="info">
        <el-descriptions :column="1" border class="info-descriptions">
          <el-descriptions-item label="当前信息">
            {{ authInfo.auth ? '已授权' : '未授权' }}
          </el-descriptions-item>
          <el-descriptions-item label="过期时间">
            {{ authInfo.expireTime || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="授权模式">
            <span>{{ authInfo.authMode }}</span>
            <span>:</span>
            <span v-if="authInfo.doubleTrack">双评轨迹授权</span>
            <span v-if="authInfo.yjsObjectiveEnable">客观题卡</span>
            <span v-if="authInfo.groupDeleteWarn">开启删除分组警告</span>
            <span v-if="authInfo.trialMode"
              >试评：{{ authInfo.trialMode }}</span
            >
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      <el-tab-pane label="更新授权" name="update">
        <el-form
          ref="formRef"
          :model="updateForm"
          :rules="rules"
          label-width="120px"
          class="update-form"
        >
          <el-form-item label="授权模式">
            <el-select
              v-model="updateForm.authMode"
              placeholder="请选择授权模式"
            >
              <el-option label="离线激活" value="offline"></el-option>
              <el-option label="在线激活" value="online"></el-option>
            </el-select>
          </el-form-item>

          <template v-if="updateForm.authMode === 'offline'">
            <el-form-item label="导出">
              <el-button type="primary" @click="exportHardwareInfo"
                >导出硬件信息</el-button
              >
            </el-form-item>
            <el-form-item label="导入授权文件" prop="offlineFile">
              <el-upload
                action="#"
                :before-upload="beforeUpload"
                :show-file-list="true"
                :limit="1"
              >
                <el-button type="primary">选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip"> 请选择授权文件进行导入 </div>
                </template>
              </el-upload>
            </el-form-item>
          </template>

          <template v-if="updateForm.authMode === 'online'">
            <el-form-item label="密钥" prop="onlineKey">
              <el-input
                v-model="updateForm.onlineKey"
                placeholder="请输入密钥"
              ></el-input>
            </el-form-item>
            <el-form-item label="秘钥" prop="onlineSecret">
              <el-input
                v-model="updateForm.onlineSecret"
                placeholder="请输入秘钥"
              ></el-input>
            </el-form-item>
          </template>

          <el-form-item>
            <el-button type="primary" :loading="loading" @click="handleSave"
              >保存</el-button
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import type { FormInstance, FormRules } from 'element-plus';
  import { getAuthInfo, updateAuthInfo } from '@/api/admin';
  import { AuthInfo, AuthUpdateParams } from '@/api/types/admin';
  import { modalConfirm } from '@/utils/ui';
  import { downloadExport } from '@/utils/download-export';

  import useLoading from '@/hooks/loading';

  const activeTab = ref('info');

  const authInfo = reactive<AuthInfo>({
    auth: false,
    expireTime: null,
    authMode: '离线激活',
    doubleTrack: false,
    groupDeleteWarn: false,
    trialMode: '成绩汇总模式',
    yjsObjectiveEnable: false,
  });

  const updateForm = reactive<AuthUpdateParams>({
    authMode: 'offline', // 默认离线激活
    offlineFile: null,
    accessKey: '',
    accessSecret: '',
  });

  const formRef = ref<FormInstance>();
  const rules: FormRules<keyof AuthUpdateParams> = {
    authMode: [{ required: true, message: '请选择模式', trigger: 'change' }],
    offlineFile: [
      { required: true, message: '请选择授权文件', trigger: 'change' },
    ],
    accessKey: [
      {
        required: true,
        message: '请输入key',
        trigger: 'change',
      },
      {
        max: 200,
        message: '最多200字符',
        trigger: 'change',
      },
    ],
    accessSecret: [
      {
        required: true,
        message: '请输入secret',
        trigger: 'change',
      },
      {
        max: 200,
        message: '最多200字符',
        trigger: 'change',
      },
    ],
  };

  // 模拟获取授权信息
  const fetchAuthInfo = async () => {
    // 实际应调用API获取数据
    const response = await getAuthInfo();
    Object.assign(authInfo, response.data);
  };

  onMounted(() => {
    // fetchAuthInfo();
    // 模拟数据
    authInfo.status = '已授权';
    authInfo.expireTime = '2025-12-31';
    authInfo.authMode = '离线激活: 双评轨迹授权 试评: 成绩汇总模式';
  });

  // 导出授权管理信息
  const exportHardwareInfo = async () => {
    await downloadExport('exportHardwareInfo');
  };

  const beforeUpload = (file: File) => {
    // 校验文件类型等，如果需要
    // const isLt2M = file.size / 1024 / 1024 < 2;
    // if (!isLt2M) {
    //   ElMessage.error('上传文件大小不能超过 2MB!');
    //   return false;
    // }
    updateForm.offlineFile = file;
    ElMessage.success(`文件 ${file.name} 已选择`);
    return false; // 阻止el-upload自动上传
  };

  const { loading, setLoading } = useLoading();
  const handleSave = async () => {
    const valid = await formRef.value?.validate().catch(() => false);
    if (!valid) return;

    const confirm = await modalConfirm(
      '确定要保存当前的授权设置吗?',
      '提示'
    ).catch(() => false);
    if (!confirm) return;

    if (!formRef.value) return;

    // 实际应调用API保存授权信息
    try {
      setLoading(true);
      let params = {};
      if (updateForm.authMode === 'offline') {
        const formData = new FormData();
        formData.append('file', updateForm.offlineFile);
        formData.append('authMode', updateForm.authMode);
        params = formData;
        await updateAuthInfo(formData);
      } else if (updateForm.authMode === 'online') {
        params = {
          authMode: updateForm.authMode,
          accessKey: updateForm.accessKey,
          accessSecret: updateForm.accessSecret,
        };
        await updateAuthInfo(params);
      }
      ElMessage.success('授权信息保存成功');
      fetchAuthInfo(); // 重新获取授权信息
      activeTab.value = 'info'; // 切换回信息展示
    } catch (error) {
      ElMessage.error('授权信息保存失败');
    } finally {
      setLoading(false);
    }

    // ElMessage.success('模拟保存成功');
    // fetchAuthInfo();
    // activeTab.value = 'info';
  };
</script>

<style scoped lang="scss">
  .info-descriptions {
    margin-top: 20px;
    :deep(.el-descriptions__label) {
      width: 120px; // 统一标签宽度
      font-weight: bold;
    }
  }

  .update-form {
    margin-top: 20px;
    max-width: 600px;
  }

  .el-upload__tip {
    font-size: 12px;
    color: #909399;
    margin-top: 7px;
  }
</style>
