<template>
  <el-dialog
    title="设置加密规则"
    v-model="dialogVisible"
    width="800px"
    :before-close="handleClose"
  >
    <div class="encryption-rule-dialog">
      <!-- 上部：规则和密钥选择 -->
      <div class="selection-section">
        <!-- 左侧加密规则选择 -->
        <div class="rule-selection">
          <div class="section-title gradient-title">
            <i class="el-icon-lock" style="margin-right:6px;color:#409EFF;font-size:18px;"></i>
            选择加密规则
          </div>
          <el-radio-group v-model="fieldData.maskingruleid" class="rule-radio-group">
            <el-radio 
              v-for="rule in encryptionRules" 
              :key="rule.id" 
              :value="rule.id"
              class="rule-radio"
            >
              {{ rule.name }}
              <span style="color: #409eff;">（{{ rule.list.length || 0 }}）</span>
            </el-radio>
          </el-radio-group>
        </div>
        <!-- 分割线 -->
        <div class="divider"></div>
        <!-- 右侧加密密钥选择 -->
        <div class="key-selection">
          <div class="section-title gradient-title">
            <i class="el-icon-key" style="margin-right:6px;color:#67C23A;font-size:18px;"></i>
            选择加密密钥
          </div>
          <el-radio-group v-model="fieldData.encryptionSecretKeyId" @change="handleKeyChange" class="key-radio-group">
            <el-radio 
              v-for="key in currentKeys" 
              :key="key.id" 
              :value="key.id"
              class="key-radio"
            >
              {{ key.name }}
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <!-- 下部：配置区域 -->
      <div class="config-section">
        <div class="config-row">
          <!-- 加密位置 -->
          <div class="config-item">
            <span class="required-label">*加密位置:</span>
            <el-select v-model="fieldData.keepfirst" style="width: 120px">
              <el-option label="保留前" :value="0" />
              <el-option label="保留后" :value="1" />
              <el-option label="既保留前" :value="2" />
            </el-select>
            <el-input-number 
              v-model="fieldData.encdigit" 
              :min="0" 
              :max="100" 
              controls-position="right"
              style="width: 100px; margin-left: 10px;"
            />
            <span class="unit">位</span>
            <span v-if="fieldData.keepfirst === 2">
              <span class="unit">又保留后</span>
              <el-input-number 
                v-model="fieldData.twoindex" 
                :min="0" 
                :max="100" 
                controls-position="right"
                style="width: 100px; margin-left: 10px;"
              />
              <span class="unit">位</span>
            </span>
          </div>
        </div>
        <div class="config-row">
          <!-- 源长度 -->
          <div class="config-item">
            <span class="label">源长度:</span>
            <el-input-number 
              v-model="fieldData.columnSize" 
              :min="0" 
              :max="1000" 
              controls-position="right"
              style="width: 100px;"
            />
            <el-button 
              type="primary" 
              size="small" 
              style="margin-left: 10px;"
              @click="calculateLength"
            >
              计算
            </el-button>
          </div>

          <!-- 加密后长度 -->
          <div class="config-item">
            <span class="label">加密后长度:</span>
            <span class="value">{{ encryptedLength || '--' }}</span>
          </div>
        </div>
        <div class="action-row">
          <el-checkbox v-model="fieldData.isLike" :true-value="1" :false-value="0">支持模糊</el-checkbox>
          <div class="action-buttons">
            <el-button @click="resetRules">重置规则</el-button>
            <el-button type="primary" @click="confirmRules">确定规则</el-button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, inject, onMounted, nextTick } from 'vue'
import { encryptionQuery, queryExtendColumnSize } from '@/api/classification/classification.js'
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  fieldData: {
    type: Object,
    default: () => ({
      columnname: '', // 字段
      columnSize: '', // 长度
      realitycolumnsize: '',
      columnType: '', // 类型
      note: '',
      maskingruleid: '',//加密规则
      maskingrulename: '',
      encryptionSecretKeyId: '', // 密钥ID
      secretkeyName: '', // 密钥名称
      isLike: 0,
      encdigit: 0,
      keepfirst: 0,
      twoindex: 0,
      flag: "0"
    })
  }
})

// 获取父组件 provide 的 currentNodeData（响应式）
const currentNodeData = inject('currentNodeData')
// console.log(' currentNodeData.value', currentNodeData.value)
const emit = defineEmits(['update:visible', 'confirm', 'reset'])

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 加密规则数据
const encryptionRules = ref([])


// 当前显示的密钥列表
const currentKeys = computed(() => {
  const rule = encryptionRules.value.find(r => r.id === props.fieldData.maskingruleid)
  props.fieldData.maskingrulename = rule ? rule.name : ''
  return rule && rule.list ? rule.list.map(key => ({
    id: key.id,
    name: key.secret_key_name
  })) : []
})

const handleKeyChange = (value) => {
  const selectedKey = currentKeys.value.find(key => key.id === value)
  props.fieldData.secretkeyName = selectedKey ? selectedKey.name : ''
}

onMounted(async () => {
  const res = await encryptionQuery()
  if (res && res.data) {
    // 处理加密规则
    encryptionRules.value = res.data.map(item => ({
      id: item.id,
      name: item.encryption_name,
      list: item.list || []
    }))
  }
})

// 加密后长度
const encryptedLength = ref('')
// 计算加密后长度
const calculateLength = async() => {
  if (!props.fieldData || !props.fieldData.encryptionSecretKeyId) {
    encryptedLength.value = ''
    return
  }
  // 这里应该是实际的加密长度计算逻辑
  const res = await queryExtendColumnSize({
          projectid: currentNodeData.value.projectid,
          datasystemid: currentNodeData.value.dataSystemId,
          tablecat: currentNodeData.value.tablecat,
          tablename: currentNodeData.value.tablename,
          columnname: props.fieldData.columnname,
          columnsize: String(props.fieldData.columnSize),
          columntype: props.fieldData.columnType,
          dbtype: currentNodeData.value.dbtype,
          islike: props.fieldData.isLike,
          encryptionsecretkeyid: props.fieldData.encryptionSecretKeyId
    })
    encryptedLength.value = res.data?.extendcolumnsize
}


// 重置规则
const resetRules = () => {
  emit('reset')
  dialogVisible.value = false
}

// 确认规则
const confirmRules = () => {
  emit('confirm')
  dialogVisible.value = false
}

// 关闭弹窗前处理
const handleClose = (done) => {
  done()
}

defineExpose({
  calculateLength
})

</script>

<style scoped>
.encryption-rule-dialog {
  padding: 10px;
}

.selection-section {
  display: flex;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.rule-selection, .key-selection {
  flex: 1;
  padding: 0 15px;
}

/* 新增的分割线样式 */
.divider {
  width: 1px;
  background-color: #ebeef5;
  margin: 0 10px;
}

.section-title {
  margin-bottom: 15px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.gradient-title {
  background: linear-gradient(90deg, #e3f0ff 0%, #f5fff7 100%);
  border-radius: 6px;
  padding: 6px 12px;
  display: flex;
  align-items: center;
  font-size: 15px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.rule-radio-group, .key-radio-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-left: 24px;
}

.rule-radio, .key-radio {
  margin: 5px 0;
}

.config-section {
  padding: 0 15px;
}

.config-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.config-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.required-label {
  width: 80px;
  text-align: right;
  margin-right: 10px;
  font-size: 14px;
  color: #f56c6c;
}

.label {
  text-align: right;
  margin-right: 10px;
  font-size: 14px;
  color: #666;
}

.unit {
  margin-left: 5px;
  font-size: 14px;
  color: #666;
}

.value {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.action-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>