<template>
  <div class="encryption-tab">
    <!-- 搜索区域 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="字段名过滤：">
          <el-input
            v-model="filterForm.columnname"
            placeholder="字段名模糊搜索"
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="状态：">
          <el-select style="width: 200px;" v-model="filterForm.flag" placeholder="全部" clearable>
            <el-option label="全部" value="" />
            <el-option v-for="item in encryptFlag" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary"  @click="handleSearch">搜索</el-button>
        </el-form-item> -->
      </el-form>
    </div>
    <!-- 表格区域 -->
    <div class="table-wrapper" style="position:relative;">
      <el-table 
        :data="filteredTableData" 
        border 
        style="width: 100%; margin-top: 15px;"
        max-height="500px"
        :row-class-name="tableRowClassName"
      >
        <!-- 左浮动列 -->
        <el-table-column label="主键" width="60" align="left"  fixed >
          <template #default="scope">
            <el-tag v-if="scope.row.primarykey === '1'" type="success">是</el-tag>
          </template> 
        </el-table-column>
         <el-table-column prop="columnname" label="字段名" width="180" />
        <el-table-column prop="typename" label="类型" width="120" />
        <el-table-column prop="columnsize" label="长度" width="80" />
        <el-table-column prop="maskingrulename" label="加密算法" width="120" align="center" />
        <el-table-column label="密钥" width="120" align="center">
          <template #default="{ row }">
            <el-button v-if="row.typename!=='DATETIME' && row.primarykey !== '1' && row.secretkeyName" link type="primary" @click="openEncryptionDialog(row)">{{ row.secretkeyName }}</el-button>
            <el-button v-if="row.typename!=='DATETIME' && row.primarykey !== '1' && !row.secretkeyName" link type="primary" @click="openEncryptionDialog(row)">设置</el-button>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <span>{{ getFlagName(row.flag) }}</span>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button v-if="row.secretkeyName && ['1', '5', '44', '10', '11'].includes(row.flag)" type="primary" size="small" @click="handleUnEncryptField(row)">解密</el-button>
            <el-button v-if="row.secretkeyName && ['0','4', '6', '7', '9', '12'].includes(row.flag)" type="primary" size="small" @click="handleEncryptField(row)">加密</el-button>
          </template>
        </el-table-column>
        <!-- 源长度 -->
        <el-table-column label="源长度" width="100" align="center">
          <template #default="{ row }">
            <el-button link type="success" v-if="row.secretkeyName">{{ row.columnsize }}</el-button>
          </template>
        </el-table-column>
        <!-- 右浮动列 -->
        <el-table-column prop="remarks" label="注释" align="left" min-width="200" />
        <el-table-column label="描述信息" align="left" fixed="right">
          <template #default="{ row }">
            <el-input 
              v-if="row.typename!=='DATETIME' && row.primarykey !== '1'" 
              v-model="row.description" 
              size="small" 
              :disabled="!isEditing"
            />
          </template>
        </el-table-column>
        <el-table-column prop="plaintextProcess" label="明文处理" align="left" fixed="right"/>
      </el-table>
      <div
        v-if="!isEditing"
        class="table-mask-click"
        @click="handleTableMaskClick"
        style="position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,0.01);z-index:11;cursor:not-allowed;"
      ></div>
    </div>
    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button v-if="!isEditing" type="primary" @click="handleBatchEncrypt">批量加密</el-button>
      <el-button v-if="!isEditing" type="primary" @click="handleBatchDecrypt">批量解密</el-button>
      <el-button v-if="!isEditing" type="primary" @click="handleDeleteColumns">删除多余列</el-button>
      <el-button v-if="!isEditing" type="primary" @click="toggleEditMode">编辑</el-button>
      <el-button v-if="isEditing" type="info" @click="toggleEditMode">取消</el-button>
      <el-button v-if="isEditing" type="primary" @click="handleSave">保存</el-button>
    </div>


    <EncryptionRuleDialog 
      ref="encryptionRuleDialogRef"
      v-model:visible="showEncryptionDialog"
      :field-data="currentField"
      @confirm="handleRuleConfirm"
      @reset="handleRuleReset"
    />
  </div>
</template>

<script setup>
import { ref, computed, reactive, inject, nextTick} from 'vue'
import EncryptionRuleDialog from './EncryptionRuleDialog.vue'
import { ElMessageBox } from 'element-plus'
import { queryOriginalList, queryEncryptionList, hasRedundanceColumns, queryIsLike, queryEncDigit, save, delTableColumn, checkSingleEncOrDecColumn, loadingColumn } from '@/api/classification/classification.js'
const props = defineProps({
  // tableData: {
  //   type: Array,
  //   required: true,
  //   default: () => []
  // }
})

// 获取父组件 provide 的 currentNodeData（响应式）
const currentNodeData = inject('currentNodeData')

const encryptionRuleDialogRef = ref(null)
/**
 * 表格数据
 */
const tableData = ref([])
/**
 * 缓存一份tableData，用于比较是否有修改
 */
const tableDataCache = ref([])

/**
 * 获取表格数据
 */

const getTableData = async () => {
    const node = currentNodeData.value
    // 查询字段原始值配置&字段加密配置
    const [originalListRes, encryptionListRes] = await Promise.all([
      queryOriginalList({
        table_name: node.label,
        datasystem_id: node.parent?.parent?.tid,
        schema: node.parent?.parent?.label,
        projectId: node.parent?.parent?.parent?.project_id
      }),
      queryEncryptionList({
        table_name: node.label,
        datasystem_id: node.parent?.parent?.tid,
        schema: node.parent?.parent?.label,
        projectId: node.parent?.parent?.parent?.project_id
      })
    ])
    if (originalListRes && originalListRes.data) {
      // 处理字段加密配置
      originalListRes.data.forEach(item => {
        const encryptionItem = encryptionListRes.data.find(en => en.fieldName === item.columnname)
        if (encryptionItem) {
          item.maskingruleid = encryptionItem.encryptionIdTrue
          item.maskingrulename = encryptionItem.encryptionTypeName
          item.secretkeyId = encryptionItem.secretKey // 编辑保存时，需要判断是否改变
          item.secretkeyName = encryptionItem.encryptionTypeValue
          item.flag = encryptionItem.flag
          item.description = encryptionItem.describe_info || '', // 编辑保存时，需要判断是否改变
          item.isLike = encryptionItem.isLike, // 编辑保存时，需要判断是否改变
          item.encdigit = encryptionItem.encdigit, // 编辑保存时，需要判断是否改变
          item.keepfirst = encryptionItem.keepfirst, // 编辑保存时，需要判断是否改变
          item.twoindex = encryptionItem.twoindex // 编辑保存时，需要判断是否改变
        }
      })
      tableData.value = originalListRes.data || []
    }

    // 缓存一份tableData，用于比较是否有修改
    tableDataCache.value = JSON.parse(JSON.stringify(tableData.value))
}

// 状态标识对象数组
const encryptFlag = [
  { value: '0', label: '无' },
  { value: '-2', label: '解密中' },
  { value: '-1', label: '加密中' },
  { value: '1', label: '加密完成' },
  { value: '5', label: '加密完成' },
  { value: '4', label: '加密失败' },
  { value: '44', label: '解密失败' },
  { value: '6', label: '解密完成' },
  { value: '7', label: '解密完成' },
  { value: '9', label: '加密替换失败' },
  { value: '10', label: '解密替换失败' },
  { value: '11', label: '解密校验失败' },
  { value: '12', label: '加密校验失败' }
]

/**
 * 加密状态标识
 */
const getFlagName = (flag) => {
  const found = encryptFlag.find(item => item.value === String(flag))
  return found ? found.label : ''
}

// 搜索表单
const filterForm = reactive({
  fieldName: '',
  flag: ''
})

// 编辑模式
const isEditing = ref(false)

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  return row.status === 'encrypted' ? 'encrypted-row' : ''
}

// 切换编辑模式
const toggleEditMode = () => {
  isEditing.value = !isEditing.value
}

/**
 * 处理单个字段加密
 * @param row 
 */
const handleEncryptField = async (row) => {
  // 处理加密逻辑
  const schema = currentNodeData.value.parent?.parent?.label
  const tableName = currentNodeData.value.label
  const key = `${schema}.${tableName}.${row.columnname}`
  
  const params = {
    columnName: row.columnname,
    columnSize: String(row.columnsize),
    columnType: row.typename,
    dataSystemId: currentNodeData.value.parent?.parent?.tid,
    flag: 0,
    map: {
      dataSystemId: currentNodeData.value.parent?.parent?.tid,
      projectId: currentNodeData.value.parent?.parent?.parent?.project_id,
      map: {
        [key]: {
          columnType: row.typename,
          columnSize: String(row.columnsize),
          describe_info: row.description || '',
          encryptionSecretKeyId: row.secretkeyId,
          flag: row.flag || '1'
        }
      }
    },
    primaryKeys: tableData.value.filter(item => item.primarykey === '1').map(item => item.columnname),
    projectId: currentNodeData.value.parent?.parent?.parent?.project_id,
    schema: schema,
    secretKeyId: row.secretkeyId,
    tableName: tableName
  }

  const result = await checkSingleEncOrDecColumn(params)
  if (result && result.code === 'POP_00014' && result.flag) {
    const loadingResult = await loadingColumn(params)
    if (loadingResult && loadingResult.code === 'POP_00014' && loadingResult.flag) {
      // 重新获取表格数据
      await getTableData()
      // 退出编辑模式
      isEditing.value = false
    } else {
      ElMessageBox.alert(loadingResult ? loadingResult.message : '加密失败，请重试', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
    }
  } else {
    ElMessageBox.alert(result ? result.message : '加密失败，请重试', '错误', {
      confirmButtonText: '确定',
      type: 'error'
    })
  }
}

/**
 * 处理单个字段解密
 * @param row 
 */
const handleUnEncryptField = (row) => {
  // 处理解密逻辑
}

// 批量加密
const handleBatchEncrypt = () => {
  emit('batch-encrypt')
}

// 批量解密
const handleBatchDecrypt = () => {
  emit('batch-decrypt')
}

// 删除多余列
const handleDeleteColumns = async () => {
  const res = await delTableColumn({
    projectId: currentNodeData.value.parent?.parent?.parent?.project_id,
    dataSystemId: currentNodeData.value.parent?.parent?.tid,
    schema: currentNodeData.value.parent?.parent?.label,
    tableName: currentNodeData.value.label
  })
  if (res && res.code === 'POP_00014' && res.flag) {
    ElMessageBox.alert('删除成功', '成功', {
      confirmButtonText: '确定',
      type: 'success'
    })
    // 重新获取表格数据
    await getTableData()
  } else {
    ElMessageBox.alert(res ? res.message : '删除失败，请重试', '错误', {
      confirmButtonText: '确定',
      type: 'error'
    })
  }
}

/**
 * 保存修改
 */
const handleSave = async () => {
    // 判断数据是否有修改
    const changedData = {}
    let hasChanges = false

    tableData.value.forEach(current => {
      const original = tableDataCache.value.find(item => item.columnname === current.columnname)
      if (original) {
        // console.log('检测到字段变更:', current.columnname)
        // console.log('检测到字段变更:', current)
        // console.log('检测到字段变更:', original)
        const fieldsToCompare = ['secretkeyId', 'description', 'isLike', 'encdigit', 'keepfirst', 'twoindex']
        const isChanged = fieldsToCompare.some(field => current[field] !== original[field])
        if (isChanged) {
          // 构建key：schema#|#table#|#column格式
          const key = `${currentNodeData.value.parent?.parent?.label}#|#${currentNodeData.value.label}#|#${current.columnname}`
          changedData[key] = {
            columnType: current.typename,
            describe_info: current.description || '',
            keepfirst: String(current.keepfirst || '0'),
            encdigit: String(current.encdigit || '0'),
            encryptionSecretKeyId: current.secretkeyId || '',
            flag: current.flag || '0',
            note: current.remarks || '',
            realitycolumnsize: String(current.columnsize || ''),
            twoindex: String(current.twoindex || '0'),
            isLike: String(current.isLike || '0')
          }
          hasChanges = true
        }
      }
    })

    if (!hasChanges) {
      ElMessageBox.alert('没有检测到更改', '提示', {
        confirmButtonText: '确定',
        type: 'info'
      })
      return
    }
 
    console.log('修改的字段changedData', changedData)
    ElMessageBox.confirm('确认保存更改吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const res = await save({
        projectId: currentNodeData.value.parent?.parent?.parent?.project_id,
        datasystemid: currentNodeData.value.parent?.parent?.tid,
        map: changedData
      }) 
      if (res && res.code === 'POP_00014' && res.flag) {
        ElMessageBox.alert('保存成功', '成功', {
          confirmButtonText: '确定',
          type: 'success'
        })
        // 重新获取表格数据
        await getTableData()
        // 退出编辑模式
        isEditing.value = false
      } else {
        ElMessageBox.alert(res ? res.message : '保存失败，请重试', '错误', {
          confirmButtonText: '确定',
          type: 'error'
        })
      }
    })
}

// 过滤表格数据
const filteredTableData = computed(() => {
  return tableData.value.filter(item => {
    const matchesName = filterForm.columnname 
      ? item.columnname.includes(filterForm.columnname)
      : true
    
    const matchesStatus = filterForm.flag 
      ? item.flag === filterForm.flag
      : true
    
    return matchesName && matchesStatus
  })
})



const showEncryptionDialog = ref(false)
const currentField = ref({})

// 点击密钥列的【密钥】或 设置
const openEncryptionDialog = async (row) => {
  if(!isEditing.value) return
  //验证table是否有重复的字段,如果重复提示
  if(row.secretkeyId){
    const hasRedundance = await hasRedundanceColumns({
      table: currentNodeData.value.label,
      datasystemid: currentNodeData.value.parent?.parent?.tid,
      schema: currentNodeData.value.parent?.parent?.label,
      projectid: currentNodeData.value.parent?.parent?.parent?.project_id
    })
    if (hasRedundance && !hasRedundance.flag) {
      ElMessageBox.alert('当前表存在重复字段，请先处理重复字段', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      })
      isEditing.value = false
      return
    }
  }
  // console.log('设置密钥openEncryptionDialog', row)
  // console.log('当前字段:', row.columnname)
  const [isLikeRes, encDigitRes] = await Promise.all([
    queryIsLike({
      tablename: currentNodeData.value.label,
      datasystemid: currentNodeData.value.parent?.parent?.tid,
      tablecat: currentNodeData.value.parent?.parent?.label,
      projectid: currentNodeData.value.parent?.parent?.parent?.project_id,
      columnname: row.columnname
    }),
    queryEncDigit({
      tablename: currentNodeData.value.label,
      datasystemid: currentNodeData.value.parent?.parent?.tid,
      tablecat: currentNodeData.value.parent?.parent?.label,
      projectid: currentNodeData.value.parent?.parent?.parent?.project_id,
      columnname: row.columnname
    })
  ])

  currentField.value = {
    // tablecat: row.tablecat, // 库名
    // tablename: row.tablename, // 表名
    columnname: row.columnname, // 字段
    columnSize: Number(row.columnsize), // 长度
    realitycolumnsize: Number(row.columnsize),
    columnType: row.typename, // 类型
    note: row.remarks,
    maskingruleid: row.maskingruleid,//加密规则
    maskingrulename: row.maskingrulename,//加密规则名称
    encryptionSecretKeyId: row.secretkeyId, // 密钥ID
    secretkeyName: row.secretkeyName, // 密钥名称
    isLike: Number(isLikeRes.data),
    encdigit: Number(encDigitRes.data.encdigit),
    keepfirst: Number(encDigitRes.data.keepfirst),
    twoindex: Number(encDigitRes.data.twoindex),
    flag: "0"
  }
  showEncryptionDialog.value = true
  // 计算加密后长度
  if(row.secretkeyId){
    nextTick(() => {
      encryptionRuleDialogRef.value.calculateLength()
    })
  }
}

/**
 * 确认加密规则-回调方法
 */
const handleRuleConfirm = () => {
  // 更新表格数据或调用API
  const field = tableData.value.find(f => f.columnname === currentField.value.columnname)
  if (field) {
    Object.assign(field, {
      maskingruleid: currentField.value.maskingruleid,//加密规则
      maskingrulename: currentField.value.maskingrulename,//加密规则名称
      secretkeyId: currentField.value.encryptionSecretKeyId,
      secretkeyName: currentField.value.secretkeyName, // 密钥名称
      isLike: currentField.value.isLike,
      encdigit: currentField.value.encdigit,
      keepfirst: currentField.value.keepfirst,
      twoindex: currentField.value.twoindex,
    })
  }
}

/**
 * 重置加密规则
 */
const handleRuleReset = () => {
  console.log('重置加密规则')
  currentField.value.encryptionSecretKeyId = ''
  const field = tableData.value.find(f => f.columnname === currentField.value.columnname)
  if (field) {
      field.maskingruleid = ''//加密规则
      field.maskingrulename = ''//加密规则名称
      field.secretkeyId = ''
      field.secretkeyName = '' // 密钥名称
  }
}

const handleTableMaskClick = () => {
  ElMessageBox.alert('当前是只读状态，编辑可点击编辑按钮进行编辑!')
}

/**
 * 暴露给父组件的数据
 */
defineExpose({
  getTableData
})

</script>

<style scoped>
.encryption-tab {
  padding: 15px;
  background-color: white;
}

.filter-section {
  margin-bottom: 15px;
}

.filter-form {
  display: flex;
  align-items: center;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-table .encrypted-row) {
  background-color: #f0f9eb;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  color: #333;
  font-weight: normal;
}

.table-mask-click {
  /* 只拦截点击事件，不影响滚动和悬浮 */
  pointer-events: auto;
}
</style>