<template>
  <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"
        />
      </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>
</template>

<script>
import { queryKeys, showKeyParams, editIsUse, testCallKey, saveKeyParams, uploadHsmConfig} from "@/api/ruleConfig/keyManagement.js"
import ParamsConfig from './components/ParamsConfig.vue'

/**
 * 规则管理-密钥管理
 */
export default {
  components: {
    ParamsConfig
  },
  name: 'KeyManagement',
  data() {
    return {
      keyManageType: '',
      isEnabled: false,
      keyManageData: [], // 存储完整的数据
      configParams: {}, // 参数配置数据
      isEditing: false, // 是否处于编辑状态
      uploadDialogVisible: false, // 上传配置文件弹层可见性
      uploadFile: null,
      uploadFileList: [],
      uploadLoading: false // 上传按钮加载状态
    }
  },
  created() {
    this.getKeyManageOptions()
  },
  computed: {
    // 获取配置类型
    getConfigType() {
      const typeMap = {
        '本地管理': 'local',
        '加密机': 'machine',
        '云加密机': 'cloud',
        '国芯加密卡': 'card',
        'KMS': 'kms',
        'THKMS': 'thkms',
        '得安加密机': 'dean',
        '量子加密机': 'star',
        '三未加密机': 'threeTerm'
      }
      const selectedOption = this.keyManageData.find(item => item.typeid === this.keyManageType)
      return selectedOption ? typeMap[selectedOption.typename] : ''
    }
  },
  watch: {},
  methods: {
    // 获取密管方式选项
    async getKeyManageOptions() {
      try {
        const res = await queryKeys()
        console.log('获取密管方式选项:', res)
        if (res.code === "POP_00014") {
          // 存储完整数据
          this.keyManageData = res.data
          // 设置选项数据
          // 找到 isuse 为 1 的选项并设置为默认值
          const activeOption = res.data.find(item => item.isuse === "1")
          if (activeOption) {
            this.keyManageType = activeOption.typeid
            // 设置启用状态
            this.isEnabled = true
          }
        }
      } catch (error) {
        console.error('获取密管方式选项失败:', error)
      }
    },

    // 处理密管方式变更
    async handleKeyManageChange(newVal) {
      // 设置启用状态
      const selectedOption = this.keyManageData.find(item => item.typeid === newVal)
      this.isEnabled = selectedOption ? selectedOption.isuse === "1" : false

      // 退出编辑状态
      this.isEditing = false 

      // 清空之前的参数
      this.configParams = {}

      // 调用showKeyParams获取参数
      try {
        const res = await showKeyParams({ typeid: newVal })
        if (res.code === "POP_00014") {
          this.configParams = res.data
        } else {
          this.$modal.msgError('获取参数失败')
        }
      } catch (error) {
        console.error('获取密管参数失败:', error)
        this.$modal.msgError('获取参数失败')
      }
    },

    // 处理启用状态变更
    // 处理下载配置模板
    handleDownloadTemplate() {
      // TODO: 实现下载配置模板的逻辑
      this.$modal.msgSuccess('开始下载配置模板')
    },

    // 处理上传配置文件
    handleUploadConfig() {
      console.log('上传配置文件')
      this.uploadDialogVisible = true;
      this.uploadFile = null;
      this.uploadFileList = [];
    },

    // 处理证书上传
    handleUploadCert(type) {
      // TODO: 实现证书上传的逻辑
      this.$modal.msgSuccess(`开始上传${type}证书`)
    },

    async handleEnableChange(newVal) {
      if (!this.keyManageType) {
        // this.isEnabled = false
        this.$modal.msgError('请先选择密管方式')
        return
      }

      const oldVal = !newVal
      try {
        const res = await editIsUse({
          typeid: this.keyManageType,
          isuse: newVal ? "1" : "0"
        })
        if (res.code === "POP_00014") {
          this.$modal.msgSuccess(newVal ? '启用成功' : '禁用成功')
          // 重新获取列表以更新状态
          await this.getKeyManageOptions()
        } else {
          // 如果失败，恢复之前的状态
          this.isEnabled = oldVal
          this.$modal.msgError('操作失败')
        }
      } catch (error) {
        // 发生错误时恢复之前的状态
        this.isEnabled = oldVal
        console.error('修改启用状态失败:', error)
        this.$modal.msgError('操作失败')
      }
    },
    // 取消编辑
    handleCancel() {
      // 可选：重置参数
     this.isEditing = false
    },
    // 测试
    async handleTest() {
      try {
        const res = await testCallKey({typeid: this.keyManageType})
        if (res.code === 'POP_00014') {
          this.$modal.msgSuccess('测试成功')
        } else {
          this.$modal.msgError(res.msg || '测试失败')
        }
      } catch (error) {
        this.$modal.msgError('测试异常')
      }
    },
    // 确认
    async handleConfirm() {
      try {
        const res = await saveKeyParams({ ...this.configParams, typeid: this.keyManageType })
        if (res.code === 'POP_00014') {
          this.$modal.msgSuccess('保存成功')
          this.isEditing = false
        } else {
          this.$modal.msgError(res.msg || '保存失败')
        }
      } catch (error) {
        
        this.$modal.msgError('保存异常')
      } finally {
        await this.handleCancel()
        // 重新获取密管方式选项
        await this.getKeyManageOptions()
      }
    },
    // 处理文件变更
    handleFileChange(file, fileList) {
      this.uploadFile = file.raw;
      this.uploadFileList = fileList;
    },
    // 处理上传取消
    handleUploadCancel() {
      this.uploadDialogVisible = false;
      this.uploadFile = null;
      this.uploadFileList = [];
    },
    // 处理上传确认
    async handleUploadConfirm() {
      console.log('上传文件:', this.uploadFile);
      if (!this.uploadFile) {
        this.$modal.msgWarning('请先选择文件');
        return;
      }
      this.uploadLoading = true;
      try {
        const filePath = this.configParams.sdkPath || '';
        const formData = new FormData();
        formData.append('file', this.uploadFile);
        formData.append('filePath', filePath);
        const res = await uploadHsmConfig(formData);
        if (res.code === 'POP_00014') {
          this.$modal.msgSuccess('上传成功');
          this.uploadDialogVisible = false;
        } else {
          this.$modal.msgError(res.msg || '上传失败');
        }
      } catch (error) {
        this.$modal.msgError('上传异常');
      } finally {
        this.uploadLoading = false;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.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>