<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>
    <!-- 上传配置文件弹层 -->
    <el-dialog
      title="上传配置文件"
      v-model="uploadDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleUploadCancel"
    >
      <div style="padding: 10px 0;">
        <el-upload
          drag
          action=""
          :auto-upload="false"
          :file-list="uploadFileList"
          :on-change="handleFileChange"
          :show-file-list="true"
          :limit="1"
        >
          <i class="el-icon-upload" style="font-size:48px;color:#409EFF;"></i>
          <div class="el-upload__text" style="font-size:16px;color:#909399;">点击或拖拽文件到此处进行上传</div>
        </el-upload>
      </div>
      <div style="text-align:center;margin-top:20px;">
        <el-button @click="handleUploadCancel">取消</el-button>
        <el-button type="primary" :loading="uploadLoading" @click="handleUploadConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { queryKeys, showKeyParams, editIsUse, testCallKey, saveKeyParams, uploadHsmConfig, createParam,
   downloadHsmConfig, downloadCloudHsmConfig, downloadSanWeiConfig, downloadZdxlzjceConfig } from '@/api/ruleConfig/keyManagement.js';
import ParamsConfig from './components/ParamsConfig.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 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);
  }
};

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'
    });
  }
};

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);
    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 () => {
  if (!uploadFile.value) {
    ElMessageBox.alert('请先选择文件', '提示', {
      confirmButtonText: '确定',
      type: 'warning'
    });
    return;
  }
  uploadLoading.value = true;
  try {
    const formData = new FormData();
    formData.append('file', uploadFile.value);
    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) {
    console.error('上传配置文件失败:', error);
    ElMessageBox.alert('上传异常', '提示', {
      confirmButtonText: '确定',
      type: 'error'
    });
  } finally {
    uploadLoading.value = false;
  }
};

const handleUploadCert = async (type) => {
  if (!uploadFile.value) {
    ElMessageBox.alert('请先选择证书文件', '提示', {
      confirmButtonText: '确定',
      type: 'warning'
    });
    return;
  }
  uploadLoading.value = true;
  try {
    const formData = new FormData();
    formData.append('file', uploadFile.value);
    formData.append('type', type);
    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 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'
    });
  }
};

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>