<template>
  <div class="key-management-wrapper">
    <div class="key-management">
      <!-- 标题 -->
      <div class="title">
        <i class="el-icon-lock"></i>
        密钥管理
      </div>

      <!-- 密管选择区域 -->
      <div class="section-card">
        <div class="section-title">密管选择区域:</div>
        <div class="section-content">
          <div class="form-item">
            <span class="label">密管方式</span>
            <el-select 
              v-model="keyManageType" 
              placeholder="请选择" 
              style="width: 200px;padding-right: 10px;"
              @change="handleKeyManageChange">
              <el-option
                v-for="item in keyManageData"
                :key="item.typeid"
                :label="item.typename"
                :value="item.typeid">
              </el-option>
            </el-select>
            <el-checkbox v-model="isEnabled" @change="handleEnableChange">是否启用</el-checkbox>
            <span class="tip">
              * 平台只能选择一种密管方式，切换加密规则，平台可切换密管方式。
            </span>
          </div>
        </div>
      </div>

      <!-- 参数配置区域 -->
      <div class="section-card">
        <div class="section-title">参数配置区域:</div>
        <div class="section-content">
          <params-config
            v-model="configParams"
            :type="getConfigType"
            :editable="isEditing"
            @download-template="handleDownloadTemplate"
            @upload-config="handleUploadConfig"
            @upload-cert="handleUploadCert"
            @generate-params="generateParams"
          />
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="footer">
        <template v-if="isEditing">
          <el-button @click="handleCancel">取消</el-button>
          <el-button @click="handleTest">测试</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="isEditing = true">编辑</el-button>
        </template>
      </div>
    </div>
    <!-- 上传配置文件弹层组件 -->
    <UploadDialog
      v-model:visible="uploadDialogVisible"
      :title="'上传配置文件'"
      :loading="uploadLoading"
      :fileList="uploadFileList"
      @file-change="handleFileChange"
      @confirm="handleUploadConfirm"
      @cancel="handleUploadCancel"
    />

    <!-- 上传证书弹层组件 -->
    <UploadDialog
      v-model:visible="uploadCertDialogVisible"
      :title="'上传证书'"
      :loading="uploadCertLoading"
      :fileList="uploadCertFileList"
      @file-change="handleCertFileChange"
      @confirm="handleCertUploadConfirm"
      @cancel="handleCertUploadCancel"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { queryKeys, showKeyParams, editIsUse, testCallKey, saveKeyParams, uploadHsmConfig, createParam,
   downloadHsmConfig, downloadCloudHsmConfig, downloadSanWeiConfig, downloadZdxlzjceConfig, uploadSanWeiConfig } from '@/api/ruleConfig/keyManagement.js';
import ParamsConfig from './components/ParamsConfig.vue';
import UploadDialog from './components/UploadDialog.vue';
import { testData } from '@/constants/keyConfigDefaultData.js';
import { ElMessageBox } from 'element-plus';
const keyManageType = ref('');
const isEnabled = ref(false);
const keyManageData = ref([]);
const configParams = ref({});
const isEditing = ref(false);
const uploadDialogVisible = ref(false);
const uploadFile = ref(null);
const uploadFileList = ref([]);
const uploadLoading = ref(false);
const uploadCertDialogVisible = ref(false);
const uploadCertFile = ref(null);
const uploadCertFileList = ref([]);
const uploadCertLoading = ref(false);
let currentCertType = '';

const getConfigType = computed(() => {
  const typeMap = {
    '本地管理': 'local',
    '加密机': 'machine',
    '云加密机': 'cloud',
    '国芯加密卡': 'card',
    'KMS': 'kms',
    'THKMS': 'thkms',
    '得安加密机': 'dean',
    '量子加密机': 'star',
    '三未加密机': 'threeTerm'
  };
  const selectedOption = keyManageData.value.find(item => item.typeid === keyManageType.value);
  return selectedOption ? typeMap[selectedOption.typename] : '';
});

const getKeyManageOptions = async () => {
  try {
    const res = await queryKeys();
    if (res.code === 'POP_00014') {
      keyManageData.value = res.data;
      const activeOption = res.data.find(item => item.isuse === '1');
      if (activeOption) {
        keyManageType.value = activeOption.typeid;
        isEnabled.value = true;
      }
    }
  } catch (error) {
    console.error('获取密管方式选项失败:', error);
  }
};

/**
 * 处理密管方式变化
 * @param newVal 
 */
const handleKeyManageChange = async (newVal) => {
  const selectedOption = keyManageData.value.find(item => item.typeid === newVal);
  isEnabled.value = selectedOption ? selectedOption.isuse === '1' : false;
  isEditing.value = false;
  configParams.value = {};

  try {
    const res = await showKeyParams({ typeid: newVal });
    if (res.code === 'POP_00014') {
      if (!res.data.id) {
        const configType = getConfigType.value;
        if (configType && testData[configType]) {
          configParams.value = { ...testData[configType] };
        }
      } else {
        configParams.value = { ...res.data };
      }
    } else {
      ElMessageBox.alert('获取参数失败，使用默认配置', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      });
    }
  } catch (error) {
    ElMessageBox.alert('获取参数失败，使用默认配置', '提示', {
      confirmButtonText: '确定',
      type: 'warning'
    });
  }
};

/**
 * 是否启用
 * @param newVal 
 */
const handleEnableChange = async (newVal) => {
  if (!keyManageType.value) {
    ElMessageBox.alert('请先选择密管方式', '提示', {
      confirmButtonText: '确定',
      type: 'warning'
    });
    return;
  }

  const oldVal = !newVal;
  try {
    const res = await editIsUse({
      typeid: keyManageType.value,
      isuse: newVal ? '1' : '0'
    });
    if (res.code === 'POP_00014') {
      ElMessageBox.alert(newVal ? '启用成功' : '禁用成功', '提示', {
        confirmButtonText: '确定',
        type: 'success'
      });
      await getKeyManageOptions();
    } else {
      isEnabled.value = oldVal;
    }
  } catch (error) {
    isEnabled.value = oldVal;
  }
};

const handleCancel = () => {
  isEditing.value = false;
};

/**
 * 执行测试
 */
const handleTest = async () => {
  try {
    const res = await testCallKey({ typeid: keyManageType.value });
    if (res.code === 'POP_00014') {
      ElMessageBox.alert('测试成功', '提示', {
        confirmButtonText: '确定',
        type: 'success'
      });
    } else {
      ElMessageBox.alert(res.msg || '测试失败', '提示', {
        confirmButtonText: '确定',
        type: 'error'
      });
    }
  } catch (error) {
    ElMessageBox.alert('测试异常', '提示', {
      confirmButtonText: '确定',
      type: 'error'
    });
  }
};

/**
 * 保存参数配置
 */
const handleConfirm = async () => {
  try {
    const res = await saveKeyParams({ ...configParams.value, typeid: keyManageType.value });
    if (res.code === 'POP_00014') {
      ElMessageBox.alert('保存成功', '提示', {
        confirmButtonText: '确定',
        type: 'success'
      });
      isEditing.value = false;
    } else {
      ElMessageBox.alert(res.msg || '保存失败', '提示', {
        confirmButtonText: '确定',
        type: 'error'
      });
    }
  } catch (error) {
    ElMessageBox.alert('保存异常', '提示', {
      confirmButtonText: '确定',
      type: 'error'
    });
  } finally {
    handleCancel();
    await getKeyManageOptions();
  }
};

const handleFileChange = (file, fileList) => {
  uploadFile.value = file.raw;
  uploadFileList.value = fileList;
};

const handleUploadCancel = () => {
  uploadDialogVisible.value = false;
  uploadFile.value = null;
  uploadFileList.value = [];
};

/**
 * 上传配置文件-执行后台调用
 */
const handleUploadConfirm = async () => {
  if (!uploadFile.value) {
    ElMessageBox.alert('请先选择文件', '提示', {
      confirmButtonText: '确定',
      type: 'warning'
    });
    return;
  }
  uploadLoading.value = true;
  try {
    const formData = new FormData();
    formData.append('file', uploadFile.value);
    // 如果是三未密管配置
    if (keyManageType.value === '8') {
      const res = await uploadSanWeiConfig(formData);
      if (res.code === 'POP_00014') {
        ElMessageBox.alert('上传成功', '提示', {
          confirmButtonText: '确定',
          type: 'success'
        });
        uploadDialogVisible.value = false;
      } else {
        ElMessageBox.alert(res.msg || '上传失败', '提示', {
          confirmButtonText: '确定',
          type: 'error'
        });
      }
      return
    }

     //如果量子加密机配置
     if (keyManageType.value === '9'){
        formData.append('filePath', configParams.value.zdxlzjcedir);
     }else{
      // 如果是其他类型的密管配置
       formData.append('filePath', configParams.value.hsmfiledir);
     }
    const res = await uploadHsmConfig(formData);
    if (res.code === 'POP_00014') {
      ElMessageBox.alert('上传成功', '提示', {
        confirmButtonText: '确定',
        type: 'success'
      });
      uploadDialogVisible.value = false;
    } else {
      ElMessageBox.alert(res.msg || '上传失败', '提示', {
        confirmButtonText: '确定',
        type: 'error'
      });
    }
  } catch (error) {
    ElMessageBox.alert('上传异常', '提示', {
      confirmButtonText: '确定',
      type: 'error'
    });
  } finally {
    uploadLoading.value = false;
  }
};

/**
 * 上传配置回调方法。触发弹层
 */
const handleUploadConfig = async () => {
  uploadDialogVisible.value = true
};

/**
 * 生成国芯加密卡参数
 */
const generateParams = () => {
  ElMessageBox.alert('开始生成国芯加密卡参数', '提示', {
    confirmButtonText: '确定',
    type: 'info'
  });
  createParam({ cphpwd: configParams.cphpwd }).then(res => {
    if (res.code === 'POP_00014') {
      ElMessageBox.alert('生成成功', '提示', {
        confirmButtonText: '确定',
        type: 'success'
      });
    } else {
      ElMessageBox.alert(res.msg || '生成失败', '提示', {
        confirmButtonText: '确定',
        type: 'error'
      });
    }
  }).catch(() => {
    ElMessageBox.alert('生成异常', '提示', {
      confirmButtonText: '确定',
      type: 'error'
    });
  });
};
/**
 * 下载配置
 */
const handleDownloadTemplate = async () => { 
  try {
    if (!keyManageType.value) {
      ElMessageBox.alert('请先选择密管方式', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      });
      return;
    }
    if(keyManageType.value === '2'){
      // 加密机的模版
      const res = await downloadHsmConfig();
      const blob = new Blob([res], { type: 'application/octet-stream' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'HsmConfig.properties'; // 文件名与后端一致
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    }

    // 云加密机的模版
    if(keyManageType.value === '3'){
      const res = await downloadCloudHsmConfig();
      const blob = new Blob([res], { type: 'application/octet-stream' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'HsmConfig.properties'; // 文件名与后端一致
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    }


    // 三未加密机的模版
    if(keyManageType.value === '8'){
      const res = await downloadSanWeiConfig();
      const blob = new Blob([res], { type: 'application/octet-stream' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'swsds.ini'; // 文件名与后端一致
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    }

    // 中电信密管的模版
    if(keyManageType.value === '9'){
      const res = await downloadZdxlzjceConfig();
      const blob = new Blob([res], { type: 'application/octet-stream' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'zdxlz.ini'; // 文件名与后端一致
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    }

  } catch (error) {
    ElMessageBox.alert('模板下载异常', '提示', {
      confirmButtonText: '确定',
      type: 'error'
    });
  }
};


const handleUploadCert = (type) => {
  currentCertType = type;
  uploadCertDialogVisible.value = true;
  uploadCertFile.value = null;
  uploadCertFileList.value = [];
};
const handleCertFileChange = (file, fileList) => {
  uploadCertFile.value = file.raw;
  uploadCertFileList.value = fileList;
};
const handleCertUploadCancel = () => {
  uploadCertDialogVisible.value = false;
  uploadCertFile.value = null;
  uploadCertFileList.value = [];
};

const handleCertUploadConfirm = async () => {
  if (!uploadCertFile.value) {
    ElMessageBox.alert('请先选择证书文件', '提示', {
      confirmButtonText: '确定',
      type: 'warning'
    });
    return;
  }
  uploadCertLoading.value = true;
  try {
    const formData = new FormData();
    let certPath = '';
    switch (currentCertType) {
      case 'cloud-client':
        certPath = configParams.value.keystoredir;
        break;
      case 'cloud-ca':
        certPath = configParams.value.truststoredir;
        break;
      case 'thkms-sm2':
        certPath = configParams.value.keystoredir;
        break;
      case 'thkms-sm2pub':
        certPath = configParams.value.truststoredir;
        break;
      case 'star-certs':
        certPath = configParams.value.certspem;
        break;
      case 'star-sigkey':
        certPath = configParams.value.sigkeypem;
        break;
      case 'star-ca':
        certPath = configParams.value.cacrtpem;
        break;
      default:
        certPath = '';
    }
    formData.append('filePath', certPath);
    formData.append('file', uploadCertFile.value);
    formData.append('type', currentCertType);
    const res = await uploadHsmConfig(formData);
    if (res.code === 'POP_00014') {
      ElMessageBox.alert('证书上传成功', '提示', {
        confirmButtonText: '确定',
        type: 'success'
      });
      uploadCertDialogVisible.value = false;
    } else {
      ElMessageBox.alert(res.msg || '证书上传失败', '提示', {
        confirmButtonText: '确定',
        type: 'error'
      });
    }
  } catch (error) {
    ElMessageBox.alert('证书上传异常', '提示', {
      confirmButtonText: '确定',
      type: 'error'
    });
  } finally {
    uploadCertLoading.value = false;
  }
};

onMounted(() => {
  getKeyManageOptions();
});
</script>

<style lang="scss" scoped>
.key-management-wrapper {
  .key-management {
    padding: 20px;
    .title {
      font-size: 18px;
      color: #333;
      margin-bottom: 20px;
      
      i {
        color: #409EFF;
        margin-right: 8px;
      }
    }

    .section-card {
      background: #fff;
      border-radius: 4px;
      padding: 20px;
      margin-bottom: 20px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

      .section-title {
        color: #409EFF;
        font-size: 14px;
        margin-bottom: 20px;
        position: relative;
        padding-left: 12px;

        &:before {
          content: '';
          width: 4px;
          height: 14px;
          background: #409EFF;
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }

      .section-content {
        .form-item {
          display: flex;
          align-items: center;
          
          .label {
            width: 100px;
            margin-right: 10px;
          }

          .tip {
            color: #f56c6c;
            margin-left: 10px;
            font-size: 12px;
          }
        }

        .button-group {
          button {
            margin-right: 10px;
          }
        }
      }
    }

    .footer {
      text-align: center;
      margin-top: 20px;
    }
  }
}
</style>